4 ms·
To be clear: Rust has quite a few smart pointer types, but because Rust makes regular references completely safe, people just use those a lot of the time. For
by Jweb_Guru 12y ago
To be clear: Rust has quite a few smart pointer types, but because Rust makes regular references completely safe, people just use those a lot of the time. For example, very few functions are written to take `Vec<T>`s (the equivalent of C++'s `std::vector`), because they can simply take slices (`&[T]`) which are just a pointer and a length. Storing a slice in a structure isn't unsafe in Rust, so people do it all the time. The same goes for strings (Rust's `&str` is equivalent to C++'s `std::string_view`). It is also very common to pass references directly into slices, strings, or other data structures rather than copying, allocating, or moving, since it's completely safe to do so. You end up only really requiring explicit smart pointers for recursive data structures, or in very rare cases where you need complex ownership behavior.
- shmerl 12y agoThanks for clarifying. That's good, since I assume using smart pointers is more expensive in Rust than using references, same as in C++.
- AlisdairO 12y agoReference counted smart pointers are more expensive than regular references in rust, but not as expensive as those in C++: Regular Rc pointers live on a single thread, and so don't have to use atomic increment/decrement like they do in C++. In addition, Rust's support for borrowing means that when passing smart pointers around you typically don't need to increment/decrement the pointer at all - because the compiler statically enforces that the borrowed reference lives for a shorter time than the smart pointer it's borrowed from.