Skip to main content
Module 7 · Lesson 2 of 216/26 in the course~14 min
Module lessons (2/2)

std::weak_ptr

Lesson preview5 hands-on exercises readyCourse C++ · Module 7 — Smart Pointers

Resolve cyclic dependencies and observe resources managed by shared_ptr with lock() and expired().

What you'll learn in this lesson

  • Understand why two std::shared_ptr pointing at each other creates a permanent memory leak.
  • Use std::weak_ptr as a non-proprietary observer that does not increment use_count().
  • Safely convert a temporary weak_ptr to shared_ptr via lock() while avoiding race conditions.

Overview

Even using smart pointers, there is a case where std::shared_ptr loses memory forever: when two objects contain a shared_ptr pointing to each other (strong loop). In that case the respective use_count() drops from 2 to 1 upon exiting main, but never reaches 0!

To break the loop, one of the two sides (e.g. the pointer from the child to the parent, or a cache/observer) must use std::weak_ptr: it points to the control block without increasing the count of strong owners (strong count):

Sections covered in this lesson

  1. 11. The Cycle between two shared_ptr and the Solution weak_ptr
  2. 22. Creating from shared_ptr and Controlling expired()
  3. 33. Atomic Access Via .lock()
  4. 44. Why prefer if (auto sp = wp.lock()) to if (!wp.expired())
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 7 — Smart Pointers

Unlock "std::weak_ptr" and the full Course C++ curriculum

Resolve cyclic dependencies and observe resources managed by shared_ptr with lock() and expired().

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course C++ plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.