Is there a way to make multiple "boxes" point to the same heap of memory?
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 someMutex
, 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 to share