Module lessons (2/2)
std::weak_ptr
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_ptrpointing at each other creates a permanent memory leak. - Use
std::weak_ptras a non-proprietary observer that does not incrementuse_count(). - Safely convert a temporary
weak_ptrtoshared_ptrvialock()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
- 11. The Cycle between two
shared_ptrand the Solutionweak_ptr - 22. Creating from
shared_ptrand Controllingexpired() - 33. Atomic Access Via
.lock() - 44. Why prefer
if (auto sp = wp.lock())toif (!wp.expired()) - 5Practical exercises
- 6Check for understanding
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.