Topic 11 of 27 · Advanced
RAII & Smart Pointers
unique_ptr, shared_ptr, weak_ptr and automatic cleanup.
Concept
RAII (Resource Acquisition Is Initialization) ties a resource's lifetime to an object: acquire in the constructor, release in the destructor. Cleanup is automatic, even with exceptions.
unique_ptr is sole ownership (zero overhead, move-only). shared_ptr counts references and deletes when the last owner goes. weak_ptr observes without owning, breaking cycles.
Create them with make_unique / make_shared; avoid raw new/delete in modern code.
Cheat sheet
| Pointer | Ownership | Copyable |
|---|---|---|
| unique_ptr | Exclusive | No (move only) |
| shared_ptr | Shared, ref-counted | Yes |
| weak_ptr | Non-owning observer | Yes |
Code (C++20)
#include <iostream>
#include <memory>
struct Node {
int val;
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev; // weak breaks the cycle
explicit Node(int v) : val(v) {}
~Node() { std::cout << "free " << val << '\n'; }
};
int main() {
auto u = std::make_unique<int>(42);
auto u2 = std::move(u); // ownership moved, u is null
auto a = std::make_shared<Node>(1);
auto b = std::make_shared<Node>(2);
a->next = b;
b->prev = a;
std::cout << a.use_count() << '\n'; // 1
} // both nodes freedRemember
- Default to unique_ptr.
- Cycles of shared_ptr leak — use weak_ptr.
- No raw new/delete.
Interview questions
What is RAII?
Managing a resource with an object whose constructor acquires it and destructor releases it, so cleanup is automatic and exception-safe.
Why use make_shared?
One allocation for object and control block (faster, better locality) and exception safety.
Lesson test
Take an 8-question test on “RAII & Smart Pointers” — concepts, output prediction, bug spotting and interview questions.