c++c++11shared-ptrweak-ptrcyclic-reference

How does a weak_ptr prevent cyclic references?


I am reading Scott Meyers "Effective C++" book. It was mentioned that there are std::shared_ptr and std::weak_ptr act like built-in pointers, but they keep track of how many std::shared_ptrs point to an object.

This is known as reference counting. This works well in preventing resource leaks in acyclic data structures, but if two or more objects contain std::shared_ptrs such that a cycle is formed, the cycle may keep each other's reference count above zero, even when all external pointers to the cycle have been destroyed.

That's where std::weak_ptrs come in.

My question is how cyclic data structures make the reference count above zero. I kindly request an example C++ program. How is the problem solved by weak_ptrs? (again, with example please).


Solution

  • A shared_ptr wraps a reference counting mechanism around a raw pointer. So for each instance of the shared_ptr the reference count is increased by one. If two share_ptr objects refer the each other they will never get deleted because they will never end up with a reference count of zero.

    weak_ptr points to a shared_ptr but does not increase its reference count.This means that the underying object can still be deleted even though there is a weak_ptr reference to it.

    The way that this works is that the weak_ptr can be use to create a shared_ptr for whenever one wants to use the underlying object. If however the object has already been deleted then an empty instance of a shared_ptr is returned. Since the reference count on the underlying object is not increased with a weak_ptr reference, a circular reference will not result in the underlying object not being deleted.