Use Weak Pointers with Shared Objects
Explore how to use std::weak_ptr as a non-owning observer with std::shared_ptr in C++. Understand its role in preventing memory leaks, managing circular references, and safely accessing shared objects. This lesson demonstrates creating, locking, and resetting weak pointers, enabling you to write safer, more efficient C++ code.
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:
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 a ...