Search code examples
c++c++11shared-ptrweak-ptrmake-shared

std::make_shared(), std::weak_ptr and cyclic references


My question is about this claim:

If any std::weak_ptr references the control block created by std::make_shared after the lifetime of all shared owners ended, the memory occupied by T persists until all weak owners get destroyed as well, which may be undesirable if sizeof(T) is large. Source

I read here, that this object live until last weak_ptr is present. Does it free object made with make_shared, with cyclic reference to self or it will live in memory forever?

For example:

struct A
{
    std::weak_ptr<A> parent;
}

void fn()
{
    auto a=std::make_shared<A>();
    a->parent = a;
} // Will it destroy here or not?

Solution

  • It is destroyed. That's one of the reason why weak_ptr exists.

    When a is destroyed, the reference counter becomes 0, so the object is destroyed. That means the destructor of the object is called, which destroys a->parent too.

    Don't confuse destruction with deallocation. When reference counter becomes 0, or no shared_ptr owns the object, the object is destroyed. If there is any weak_ptr which points the control block, the memory won't be deallocated - because the object was allocated with std::make_shared - but the object is definitely destroyed.