Cyclic References
In this lesson, we'll see how the use of shared pointers can create a reference cycle and why this could be harmful.
You get cyclic references of std::shared_ptr
if they refer to each other. So, the resource counter never becomes 0, and the resource is not automatically released. You can break this cycle if you embed an std::weak_ptr
in the cycle. std::weak_ptr
does not modify the reference counter.
The result of the code sample is that the daughter is automatically released, but neither the son nor the mother is. The mother refers to her son via an std::shared_ptr
and to her daughter via an std::weak_ptr
. Maybe it helps to see the structure of the code in an image.
Get hands-on with 1400+ tech skills courses.