7 ms·
Is Rusts concept of ownership any different from C++ unique_ptrs?
by Odin78 10y ago
Is Rusts concept of ownership any different from C++ unique_ptrs?
- kibwen 10y agoIt's not identical (Rust statically enforces a lot more than C++ does, move semantics are opt-out rather than opt-in, there's no such thing as move constructors in Rust, etc.), but if you understand unique_ptr then you'll understand Rust's concept of ownership.
- steveklabnik 10y agoAs an example, here are two roughly equivalent programs. First Rust: let x = Box::new(5); let y = x; println!("{}", x); Now C++: unique_ptr<int> x(new int(5)); auto y = std::move(x); cout << *x << endl; (I'm being a bit sloppy with namespaces, and both need a main(), but you get the idea) Here, the C++ will compile and (probably) segfault, as x is nullptr after the move. The Rust will fail at compile time, with "use of moved value." Basically, a (possibly over-)generalization of the situation is "Rust is move by default and captures errors at compile time, C++ is not move by default and cannot statically prevent as many errors as Rust can."