Memory deallocation of Weak reference

I noticed this line in the doc of weak reference:

Note however that a Weak reference does prevent the allocation itself (the backing store) from being deallocated.

If I understand it right, if the reference counts turns to 0, the value in the allocated memory will be dropped, but the memory it self is not deallocated if there are weak references.

I checked the code and it seems that the reference count and the memory which store the value are one piece, which means you cannot deallocate the memory which store the value without deallocating the memory witch store the reference count (correct me if I'm wrong).

So is there any other options (crates, or workaround, or some tech I don't know) to avoid this memory wasting?

1 Like

Rc<Box<T>> will store reference count and object data separately. The Box will be freed immediately as strong count goes to zero, because Rc/Arc run the destructors eagerly. The cost is in double indirection.

Weak instances need a stable address to read the refcount from, so I don't think you can avoid the contiguous-leaky vs double-indirection trade-off without without using a clever custom allocator that can partially free memory ranges.

3 Likes

In line with that @kornel already said, it’s important to appreciate that only the direct/shallow memory of the type contained inside of the Arc is kept/“wasted”. I.e. the amount of memory that mem::size_of::<T> returns is kept for an Arc<T>. For most Rust types, this is rather small, of course if you’re having an Arc<[u32; 1000000]>, then it is not small. Any memory behind further (owned) pointers e.g. for a Box or a Vec will be deallocated with outstanding Weaks.

Furthermore, some usage patterns of Weak don’t even ever keep invalidated Weak pointers around for particularly long, e.g. if Weak is used for back-pointers to avoid cycles.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.