5 ms·
So in comparison to C++ would it be correct to say that Box<T> is like unique_ptr<T>, Vec<T> is Vector<T>, and that references are the same in both languages?
by tybit 9y ago
So in comparison to C++ would it be correct to say that Box<T> is like unique_ptr<T>, Vec<T> is Vector<T>, and that references are the same in both languages?
- kibwen 9y agoRust's Box and Vec are analogous to C++'s unique_ptr and vector, yes. But references in Rust really aren't anything like C++ references, given that Rust references 1) are first-class, 2) come in two varieties (mutable/exclusive and immutable/shared), 3) feature mechanically-checked lifetimes, and 4) will be two words in size (rather than one) if the underlying type is dynamically-sized.
- jcelerier 9y ago> Rust references 1) are first-class what makes them more first-class than C++ references ? eg in C++ given a type T, you can use `std::add_lvalue_reference<T>`, `std::remove_reference<T>`, overload on references, check if a type is a reference to another...
- Sharlin 9y agoC++ reference types are first-class. But instances of reference types are not first-class values. References are not objects, in standard speak, they do not have a memory location, you can't take their address, you can't pass them to functions (a reference parameter means passing a value by reference, not a reference by value). And so on. Rust references are more like C/C++ pointers or Java references in that they are actual values, and AFAIK Rust functions, like Java and C functions, are strictly pass-by-value.
- wyldfire 9y agoThis is a really helpful distinction, thanks for clarifying.
- kimundi 9y agoI think they just meant that Rust references are like normal first-class generic types. Eg, you can nest them to get a &mut &T for example, since they behave more like a pointer in that regard. C++ references on the other hand are more like modificators of a type, eg you can have a T or a T&, but having a (T&)& does not make sense. (Outside of templates, where it gets folded down to a T&.)
- jplatte 9y agoThere is one important difference between Box and unique_ptr though: unique_ptr is nullable while Box isn't.