Advanced level · Module 2: Modern Memory Management · Lesson 3 of 4
shared_ptr and weak_ptr
Use shared ownership only when it is genuinely needed, and break reference cycles with weak_ptr.
In this lesson you will
- Use std::shared_ptr for shared ownership
- Break cycles with std::weak_ptr
Key concepts
std::shared_ptrreference countstd::weak_ptrreference cycle
The lesson
std::shared_ptr<T> lets several owners share an object; a reference count tracks the owners, and the object is deleted when the last one disappears. Create it with std::make_shared. Copying a shared_ptr increases the count; this has a small cost, especially across threads.
If two objects hold shared_ptrs to each other, their counts never reach zero and both leak — a reference cycle. Make one direction a std::weak_ptr, which observes without owning; call lock() to get a temporary shared_ptr when you need the object.
Prefer unique_ptr. Use shared_ptr only when ownership is truly shared and lifetimes cannot be expressed more simply; widespread shared_ptr often hides an unclear design.
Step by step
- Share one configuration object between two components with shared_ptr.
- Print use_count() as owners are added and removed.
- Create a parent–child cycle and observe the leak.
- Fix it with weak_ptr and lock().
Which way should this code hold that object?
A quick path to the right choice between a value, a reference, unique_ptr, shared_ptr and weak_ptr.
- YesUse a value. It is the simplest, fastest and safest option — no pointers needed.
- NoDoes this code only use the object while someone else keeps it alive?
- YesUse a reference (or a raw pointer if 'no object' is possible). It means 'I use this but do not own it'.
- NoWill exactly one owner be responsible for deleting it?
- YesUse std::unique_ptr created with std::make_unique, and std::move it to transfer ownership.
- NoDo several owners genuinely share it, with no single clear owner?
- YesUse std::shared_ptr created with std::make_shared, and std::weak_ptr for back-references to avoid cycles.
- NoThe ownership is unclear. Redesign so one component owns the object before choosing a pointer type.
- Yes
- Yes
- Yes
Notes
Raw new and delete never appear in the answers: in modern C++ they belong inside low-level library code, not application code.
Practice activity
Model stations and their sensors where sensors refer back to their station without creating a cycle.
Expected result: All objects are destroyed at the end of the program and the sanitizer reports no leaks.
Check your understanding
-
When is an object owned by shared_ptr deleted?
Show answer
When the last shared_ptr owning it is destroyed or reset.
-
What does weak_ptr do?
Show answer
Observes a shared object without owning it, which breaks reference cycles.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.