Module 9 · Modern C++ — topic 2 of 3
Smart Pointers
unique_ptr, shared_ptr and weak_ptr manage heap objects automatically. Learn ownership models, make_unique/make_shared, transferring ownership and breaking cycles.
Learning objectives
- Use unique_ptr for exclusive ownership
- Use shared_ptr and weak_ptr correctly
- Transfer ownership with std::move
Definition
Smart pointers are RAII class templates in<memory>that own dynamically allocated objects:std::unique_ptrhas sole ownership,std::shared_ptrshares ownership with reference counting, andstd::weak_ptrobserves a shared object without owning it.
Introduction
Manual new/delete leaks when an exception or early return skips the delete. Smart pointers delete the object in their destructor, so memory is released on every path — the RAII idea applied to heap objects.
Why it matters
Modern C++ guidelines say: no naked new/delete in application code.
Polymorphic containers, trees and graphs are built with smart pointers.
Detailed explanation
std::unique_ptr<T>: exactly one owner; not copyable, only movable (std::move). Zero overhead compared with a raw pointer. Create with std::make_unique<T>(args).
std::shared_ptr<T>: several owners; a reference count tracks them and the object is deleted when the last one goes away. Create with std::make_shared<T>(args) (one allocation for object and count).
std::weak_ptr<T>: a non-owning reference to a shared object. lock() returns a shared_ptr if the object still exists. Use it to break cycles (parent ↔ child).
Pass smart pointers by value only to transfer or share ownership; otherwise pass T& or T* to functions that merely use the object.
Syntax
- Prefer unique_ptr by default.
- Never create two shared_ptrs from the same raw pointer.
.get()returns the raw pointer without releasing ownership.
Code examples
unique_ptr frees automatically
open sales using sales close sales after scope
Moving ownership
a empty, b = 42
More examples
shared_ptr counts and weak_ptr breaking a cycle
employee owners: 2 Asha works in Platform team Platform destroyed Asha destroyed scope ended
Step-by-step explanation
- The employee is owned by
eand by the team's vector: use_count 2. - The employee points back to its team with a weak_ptr, so there is no ownership cycle.
lock()temporarily obtains a shared_ptr to read the team.- At scope end,
eis released first (declared later), thent; the team's destructor drops the last owner of the employee.
Expected output
Running “shared_ptr counts and weak_ptr breaking a cycle” prints exactly:
Practical applications
- GUI widget trees use unique_ptr children.
- Caches hand out shared_ptrs to shared resources.
- Observer patterns use weak_ptr to avoid keeping subjects alive.
Best practices
- Default to unique_ptr; use shared_ptr only for genuinely shared ownership.
- Create with make_unique/make_shared.
- Pass raw references to functions that don't own.
Common mistakes
Two owners of one raw pointer
Avoid
Prefer
Each shared_ptr created from a raw pointer starts its own count; both delete.
shared_ptr cycles
Avoid
Prefer
Two shared_ptrs pointing at each other keep both objects alive forever — a leak.
Important notes
- shared_ptr reference counting is thread-safe, but access to the pointed-to object is not.
- unique_ptr supports arrays (
std::unique_ptr<int[]>) and custom deleters (e.g. forFILE*).
Key takeaways
- unique_ptr: sole owner, movable only.
- shared_ptr: reference-counted shared ownership.
- weak_ptr: observe without owning; breaks cycles.
Try it yourself
- 1Build a binary tree with
std::unique_ptr<Node>children and compute its height. - 2Use
std::unique_ptr<FILE, decltype(&fclose)>to close a C file automatically.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
6 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhich smart pointer expresses sole ownership and cannot be copied?
- BeginnerWhat is printed?
- ModerateWhat is printed?