[Rc, Weak][Smart pointer internals] which part is value being dropped?

inside source code , rust rc source

which part is value being dropped?

at line 1559

unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
             .........code omitted..........
            
            // destroy the contained object
                ptr::drop_in_place(Self::get_mut_unchecked(self));
            .........code omitted..........

}

it said "destory the contained object" , is it at this point ?

or is it at line 1566?

unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
        .........code omitted..........
        Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
       .........code omitted..........
}

i'm a little confused by the "strong weak", does it mean weak count is initialized to be 1 at the beginning of the Rc construction? what's purpose of this special weak pointer and how is it being useful?

there's also similiar implmentation at line 2470

 unsafe impl<#[may_dangle] T: ?Sized> Drop for Weak<T> {
        .........code omitted..........
        if inner.weak() == 0 {
            unsafe {
                Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
            }
        }
       .........code omitted..........
}

i don't seem to grasp the meaning of this part, should weak not suppose to manage the memory all by it self? why it is deallocating?

ptr::drop_in_place is where the object's destructor is called, Global.deallocate removes the backing storage where the object was.

The weak count and Weak<T> are made to enable certain types of cyclical references without leaking memory. For example, one might imagine a tree-like structure where nodes contain a reference to both parent and child nodes. Obviously, the parent and child holding a reference to each other is a reference cycle (and a memory leak), but doing something like making the parent pointer a Weak<T> rather than an Rc<T> will break the cycle, since holding a Weak<T> won't prevent destructors from running.

2 Likes

Just to clarify that last point:

Either the Rc will call deallocate XOR Weak will call deallocate.

If the last Rc to drop still has a non-zero weak count, it can't deallocate the memory yet because there are still weak references. When the last Weak drops it will do the deallocation.

3 Likes