Quick Q: Why is the count of weak_ptr tracked also?

Quick A: To be able to know when to delete the control block.

Recently on SO:

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

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.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.