Use Weak Pointers with Shared Objects
Learn to use weak pointers with shared objects.
We'll cover the following...
Strictly speaking, std::weak_ptr is not a smart pointer. Rather, it's an observer that operates in cooperation with shared_ptr. A weak_ptr object does not hold a pointer on its own. There are circumstances where shared_ptr objects may create dangling pointers or race conditions, which could lead to weak_ptr objects with shared_ptr.
How to do it
In this recipe, we examine the use of std::weak_ptr with std::shared_ptr, using a demonstration class that prints when its constructors and destructor are called.
We start with the same class we've used to demonstrate
shared_ptrandunique_ptr: