Is there a way to make multiple "boxes" point to the same heap of memory?

Seems to Box.clone()

copy heap memory. As I know, Box

will be destroyed after it goes out of scope as well as the memory area it points to.

So, I would like to ask a way to create more than one object Box

pointing to the same memory area.

+3


source to share


1 answer


By definition, you won't .

Box

explicitly created with the assumption that it is the sole owner of the object inside.




If multiple owners are required, you can use Rc

and instead Arc

, these are the referenced owners and the object will only be deleted when the last owner is destroyed.

Note, however, that they have no disadvantages:

  • the contained object cannot be modified without a runtime check; if a mutation is needed, this requires using Cell

    , RefCell

    or some Mutex

    , for example,
  • it is possible to randomly form object loops, and since Rust does not have a garbage collector, such loops will leak.
+10


source







All Articles