Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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.

like image 678
wind2412 Avatar asked Apr 05 '17 09:04

wind2412


People also ask

What is stack memory heap?

Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution. Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it.

Which is better stack or heap?

Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be access by owner thread. Memory allocation and de-allocation is faster as compared to Heap-memory allocation.

Can the heap run out of space?

In a word, yes, it can. While the heap can grow and shrink, it does have lower and upper bounds (usually defined by the -Xms and -Xmx arguments, unless you choose to se the defaults). If the heap size is exceeded, the allocation will fail and you'll get a java. lang.

What is the difference between heap and stack?

The Heap Space contains all objects are created, but Stack contains any reference to those objects. Objects stored in the Heap can be accessed throughout the application. Primitive local variables are only accessed the Stack Memory blocks that contain their methods.


1 Answers

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.
like image 152
Matthieu M. Avatar answered Oct 05 '22 06:10

Matthieu M.