I am reading Scott Meyers "Effective C++" book. It was mentioned that there are tr1::shared_ptr
and tr1::weak_ptr
act like built-in pointers, but they keep track of how many tr1::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 tr1::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 tr1::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).
A
shared_ptr
wraps a reference counting mechanism around a raw pointer. So for each instance of theshared_ptr
the reference count is increased by one. If twoshare_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 ashared_ptr
but does not increase its reference count.This means that the underying object can still be deleted even though there is aweak_ptr
reference to it.The way that this works is that the
weak_ptr
can be use to create ashared_ptr
for whenever one wants to use the underlying object. If however the object has already been deleted then an empty instance of ashared_ptr
is returned. Since the reference count on the underlying object is not increased with aweak_ptr
reference, a circular reference will not result in the underlying object not being deleted.