wind2412
wind2412

Reputation: 1069

Is there any way to make more than one `Box` pointing to the same heap memory?

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

Answers (2)

user2138149
user2138149

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

Matthieu M.
Matthieu M.

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:

  • the contained object cannot be mutated without runtime checks; if mutation is needed this requires using Cell, RefCell or some Mutex for example,
  • it is possible to accidentally form cycles of objects, and since Rust has no Garbage Collector such cycles will be leaked.

Upvotes: 15

Related Questions