Use weak pointers with shared objects
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 memory leaks or other problems. The solution is to use 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...