Search code examples
c++c++11shared-ptrsmart-pointersweak-ptr

Finding weak_ptrs referring to a shared_ptr


Is there a way to find out the number of weak_ptrs a shared_ptr is being referred by?

unique()/use_count() could be used for finding the shared_ptrs but is there a similar construct for finding the referring weak_ptrs.

I want to release the resource held by the shared_ptr only if there are no weak_ptrs referring to it. So that sometime in future if I try creating a shared_ptr from this weak_ptr, I shouldn't end up with a nullptr.

Is this possible currently in C++11?


Solution

  • No.

    There is no interface for doing this thing, because it would miss the entire point.

    The resource is released if no std::shared_ptr refers to it.

    By using std::weak_ptr you specifically allow your resource to be released. Don't use it if that's not what you want.