Reputation: 1069
It seems like Box.clone()
copies the heap memory. As I know, Box
will get destructed after it gets out of its scope, as well as the memory area it is pointing to.
So I'd like to ask a way to create more than one Box
object pointing to the same memory area.
Upvotes: 10
Views: 1736
Reputation: 16585
For those coming from a C++ background, consider that Box
is Rust's implementation of a std::unique_ptr
.
A std::unique_ptr
is, by design, not copyable using either a copy constructor or an assignment operator.
It is however movable.
Box
in Rust is the same, except that Rust is a move by default language, whereas C++ is copy by default.
Upvotes: 1
Reputation: 299790
By definition, you shall not.
Box
is explicitly created with the assumption that it is the sole owner of the object inside.
When multiple owners are required, you can use instead Rc
and Arc
, those are reference-counted owners and the object will only be dropped when the last owner is destroyed.
Note, however, that they are not without downsides:
Cell
, RefCell
or some Mutex
for example,Upvotes: 15