4 ms·
Here's a static check Rust's Box<T> offers over C++'s std::unique_ptr<T>. The following program is obviously incorrect to someone familiar with smart pointers.
by koito17 2y ago
Here's a static check Rust's Box<T> offers over C++'s std::unique_ptr<T>.
The following program is obviously incorrect to someone familiar with smart pointers. The code compiles without error, and the program crashes as expected.
% cat demo.cpp
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<std::string> foo = std::make_unique<std::string>("bar");
std::unique_ptr<std::string> bar = std::move(foo);
std::cout << *foo << *bar << std::endl;
}
% clang -std=c++2b -lstdc++ -Weverything demo.cpp
warning: include location '/usr/local/include' is unsafe for cross-compilation [-Wpoison-system-directories]
1 warning generated.
% ./a.out
zsh: segmentation fault ./a.out
The equivalent Rust code fails to compile.
% cat demo.rs
fn main() {
let foo = Box::new("bar");
let bar = foo;
println!("{foo} {bar}")
}
% rustc demo.rs
error[E0382]: borrow of moved value: `foo`
--> demo.rs:5:13
|
2 | let foo = Box::new("bar");
| --- move occurs because `foo` has type `Box<&str>`, which does not implement the `Copy` trait
3 | let bar = foo;
| --- value moved here
4 |
5 | println!("{foo} {bar}")
| ^^^^^ value borrowed here after move
help: consider cloning the value if the performance cost is acceptable
|
3 | let bar = foo.clone();
| ++++++++
Not only does Rust emit an error, but it even suggests a fix for the error.
- sesm 2y agoThat's a very good example, thank you!