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

Why shared_ptr's reference counting object needs to keep track of the number of weak_ptrs pointing to the object too?


Hi I am reading through this document and some other documents about C++'s shared_ptr and they all seem to suggest that apart from the number of shared_ptr pointing to the allocated object, the reference count object has to keep track of how many weak_ptr pointer pointing to the object as well. My question is why? From my understanding, weak_ptr is non-owning so if the count of shared_ptr pointing to the object reaches zero the object can be deleted. That is why sometimes we need to use expired to check the availability of an object pointed by a weak_ptr. Could you explain the reason for needing to keep track of the number of weak_ptrs?

Why do we need weak count here? enter image description here


Solution

  • std::weak_ptr refers to the control block to know if the object still exists and if so, to provide a std::shared_ptr to it when needed. For that reason, the control block must exist as long as either a std::weak_ptr or a std::shared_ptr exists. You need to track the number of instances of std::weak_ptr to know when the last one is destroyed, just like for std::shared_ptr.