Difficulty: Advanced
What is a weak_ptr and what problem does it solve? Show how a shared_ptr cycle leaks memory and how to fix it.
shared_ptr looks like a complete memory management solution until you meet reference cycles. This question checks whether you understand reference counting deeply enough to know its Achilles heel.
Reference counting frees an object when its count reaches zero. Now imagine two objects, a Parent and a Child, where the parent holds a shared_ptr to the child and the child holds a shared_ptr back to the parent. Each is kept alive by the other. When your local variables go out of scope, each object's count drops from 2 to 1, not to 0, so neither destructor ever runs. The objects are unreachable but not freed: a leak. It is like two people each holding the other's rope at the edge of a cliff: neither can let go first, and nobody else can pull them up.
std::weak_ptr is the tool that breaks the cycle. It is a non-owning observer of an object managed by shared_ptr: it does not increase the strong reference count, so it does not keep the object alive. It does share the control block, so it can tell whether the object still exists. You cannot dereference a weak_ptr directly. Instead, you call lock(), which returns a shared_ptr: if the object is still alive, you get a valid shared_ptr (temporarily bumping the count, making the object safe to use for as long as you hold it); if it has been destroyed, you get an empty one. Calling expired() also tells you, but 'if (auto sp = wp.lock())' is the correct, race-free idiom because checking and then using are separate steps that another thread could interleave.
The design rule that resolves cycles: think about who owns whom. Owning direction uses shared_ptr (or unique_ptr); the back reference, which merely needs to observe, uses weak_ptr. A parent owns its children through shared_ptr; each child has a weak_ptr back to the parent. In a doubly linked list, next pointers own and prev pointers are weak. In a tree with parent links, child-to-parent should be non-owning.
Other uses of weak_ptr: caches (hold weak references so cached items can be freed when nobody else uses them), the observer pattern (subjects hold weak_ptrs to listeners so a destroyed listener doesn't cause a dangling call), and callbacks that must safely check that their target still exists before running.
Some subtle points to bring up. use_count reports the strong count; weak_count reports weak observers. With make_shared, the object's memory block remains allocated until the last weak_ptr is gone, even though the object is already destroyed. Also, shared_ptr cycles are not a problem for unique_ptr, since ownership is a tree by construction, but a raw back-pointer inside a unique_ptr tree is fine as long as the parent outlives the child.
#include <iostream>
#include <memory>
struct Child;
struct Parent {
std::shared_ptr<Child> child;
~Parent() { std::cout << "Parent dtor\n"; }
};
struct Child {
std::weak_ptr<Parent> parent; // shared_ptr here would create a cycle
~Child() { std::cout << "Child dtor\n"; }
};
int main() {
auto p = std::make_shared<Parent>();
p->child = std::make_shared<Child>();
p->child->parent = p;
std::cout << p.use_count() << " " << p->child.use_count() << "\n";
if (auto sp = p->child->parent.lock()) // safe access to the parent
std::cout << "parent alive\n";
} // p released -> Parent dtor -> its child member released -> Child dtor
Because the child only holds a weak reference, the parent's strong count stays at 1. When p dies, the parent is destroyed, then its child. Change weak_ptr to shared_ptr and neither destructor prints.
weak_ptr, circular reference, shared_ptr, observer pattern, memory leak