Lesson 4 of 7
shared_ptr & weak_ptr - Shared & Weak Ownership
`std::shared_ptr<T>` allows **multiple owners** of the same heap object via reference counting. When the last `shared_ptr` to an object is destroyed, the object is deleted. `shared_ptr` has overhead: a **control block** (separate heap allocation) tracking the strong reference count and a weak reference count. `std::weak_ptr<T>` holds a **non-owning** reference - it doesn't increment the strong count, so it doesn't prevent deletion. `weak_ptr` is primarily used to **break reference cycles** that would otherwise cause memory leaks.
shared_ptr - Use Count, Control Block & weak_ptr Cycle Breaking
#include <iostream>
#include <memory>
#include <string>
class Node {
public:
std::string name;
std::shared_ptr<Node> next; // strong - creates cycles!
// Use weak_ptr instead for back/parent pointers:
std::weak_ptr<Node> parent; // weak - doesn't prevent deletion
explicit Node(std::string n) : name(std::move(n)) {
std::cout << "Node(" << name << ") created
";
}
~Node() { std::cout << "Node(" << name << ") destroyed
"; }
};
void shared_ptr_basics() {
// make_shared: single allocation for object + control block (efficient)
auto sp1 = std::make_shared<Node>("root");
std::cout << "use_count after sp1: " << sp1.use_count() << "
"; // 1
{
auto sp2 = sp1; // copy - increments reference count
auto sp3 = sp1;
std::cout << "use_count with sp2, sp3: " << sp1.use_count() << "
"; // 3
// sp2, sp3 destroyed here → count drops to 1
}
std::cout << "use_count after scope: " << sp1.use_count() << "
"; // 1
// sp1 destroyed → count=0 → Node deleted
}
void reference_cycle_demo() {
// ── MEMORY LEAK with shared_ptr cycle ────────────────────
// {
// auto a = std::make_shared<Node>("A");
// auto b = std::make_shared<Node>("B");
// a->next = b; // A owns B
// b->next = a; // B owns A ← CYCLE!
// // a and b both go out of scope
// // a's count: 1 (b->next still holds it)
// // b's count: 1 (a->next still holds it) → LEAK!
// }
// ── CORRECT: weak_ptr breaks the cycle ───────────────────
auto a = std::make_shared<Node>("A");
auto b = std::make_shared<Node>("B");
a->next = b; // A strongly owns B
b->parent = a; // B weakly references A (doesn't own)
// Check if parent is still alive
if (auto locked = b->parent.lock()) { // lock() returns shared_ptr<Node>
std::cout << b->name << "'s parent: " << locked->name << "
";
std::cout << "parent use_count: " << locked.use_count() << "
"; // 2 (sp + locked)
}
// a and b destroyed: b destroyed first (a releases b), then a destroyed
// No cycle → no leak
}
void weak_ptr_patterns() {
auto sp = std::make_shared<Node>("data");
std::weak_ptr<Node> wp = sp;
std::cout << "wp expired? " << wp.expired() << "
"; // false
sp.reset(); // drop the only strong owner - Node deleted
std::cout << "wp expired? " << wp.expired() << "
"; // true
auto locked = wp.lock(); // returns empty shared_ptr (object gone)
if (!locked) std::cout << "wp.lock() returned nullptr - object gone
";
}
int main() {
std::cout << "--- basics ---
";
shared_ptr_basics();
std::cout << "
--- cycle (fixed with weak_ptr) ---
";
reference_cycle_demo();
std::cout << "
--- weak_ptr lifetime ---
";
weak_ptr_patterns();
return 0;
}Common Mistakes
- `std::make_shared` is almost always better than `shared_ptr<T>(new T(...))` - `make_shared` performs ONE allocation (object + control block together). `shared_ptr<T>(new T(...))` performs TWO allocations. Also: `make_shared` is exception-safe; `new T(...)` in argument position can leak if another argument throws.
- Always check `wp.lock()` before using - `weak_ptr` does not give direct access. Call `wp.lock()` to get a `shared_ptr`. If the object was deleted, `lock()` returns an empty `shared_ptr`. Always check before dereferencing.
- `shared_ptr` is not free - each copy increments an atomic reference count. For high-frequency code (millions per second), shared_ptr copy overhead adds up. Prefer `const shared_ptr<T>&` in function parameters to avoid the count increment on each call.
Tip
Tip
Practice sharedptr weakptr Shared Weak Ownership in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Shared ownership reference counting and breaking circular cyclic leaks with weak_ptr
Practice Task
Note
Practice Task - (1) Write a working example of sharedptr weakptr Shared Weak Ownership from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with sharedptr weakptr Shared Weak Ownership is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- `std::shared_ptr<T>` allows **multiple owners** of the same heap object via reference counting.
- `std::make_shared` is almost always better than `shared_ptr<T>(new T(...))` - `make_shared` performs ONE allocation (object + control block together). `shared_ptr<T>(new T(...))` performs TWO allocations. Also: `make_shared` is exception-safe; `new T(...)` in argument position can leak if another argument throws.
- Always check `wp.lock()` before using - `weak_ptr` does not give direct access. Call `wp.lock()` to get a `shared_ptr`. If the object was deleted, `lock()` returns an empty `shared_ptr`. Always check before dereferencing.
- `shared_ptr` is not free - each copy increments an atomic reference count. For high-frequency code (millions per second), shared_ptr copy overhead adds up. Prefer `const shared_ptr<T>&` in function parameters to avoid the count increment on each call.
Finished this lesson?