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 memory leaks Memory leak refers to a situation in computer programming where dynamically allocated memory is not properly released or freed, leading to a gradual accumulation of unreleased memory over time. 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 and unique_ptr:

Get hands-on with 1400+ tech skills courses.