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_ptr
andunique_ptr
:
struct Thing {string_view thname{ "unk" };Thing() {cout << format("default ctor: {}\n", thname);}Thing(const string_view& n) : thname(n) {cout << format("param ctor: {}\n", thname);}~Thing() {cout << format("dtor: {}\n", thname);}};
This class has a default constructor, a parameterized constructor, and a destructor. Each of these has a simple print statement to tell us what was called.
We also need ...