Dealing with weak pointers to shared objects
In the recipe about shared_ptr
, we learned how useful and easy to use shared pointers are. Together with unique_ptr
, they pose an invaluable improvement for code that needs to manage dynamically allocated objects.
Whenever we copy shared_ptr
, we increment its internal reference counter. As long as we hold our shared pointer copy, the object being pointed to will not be deleted. But what if we want some kind of weak pointer, which enables us to get at the object as long as it exists but does not prevent its destruction? And how do we determine if the object still exists, then?
In such situations, weak_ptr
is our companion. It is a little bit more complicated to use than unique_ptr
and shared_ptr
, but after following this recipe, we will be ready to use it.
How to do it...
We will implement a program that maintains objects with shared_ptr
instances, and then, we mix in weak_ptr
to see how this changes the behavior of smart pointer memory handling:
- At...