Reputation: 7411
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_ptr
s?
Why do we need weak count here?
Upvotes: 18
Views: 3143
Reputation: 91
Adding to the answer by François Andrieux:
There is a side effect of this that is very important to understand.
If you use an implementation of std::make_shared that uses the WKWYL optimization (We Know Where You Live) of allocating the control block and the actual object together as one contiguous allocation, the memory WILL NOT BE FREED until after all weak_ptr objects have also gone out of scope.
(my account is seldom used, so I cannot add comments, due to not having enough reputation points, thus adding as an answer rather than a comment)
Upvotes: 4
Reputation: 29072
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
.
Upvotes: 23
Reputation: 106609
The shared_ptr
reference count is the count of owners of the object. The weak_ptr
reference count is the count of owners of the reference count control block.
Upvotes: 6