Explain it simply
Explain it simply
A resource is anything you must give back after using it: heap memory, an open file, a network connection, a locked mutex. Forgetting to give it back is a leak; giving it back twice is a crash. RAII, short for Resource Acquisition Is Initialization, solves this with one rule: wrap the resource in an object whose destructor gives it back.
Think of a library book with a self-returning tag: the moment you leave the building, the book is returned for you, whether you walked out calmly or ran out because of a fire alarm. In C++, "leaving the building" is the end of a scope, and smart pointers such as std::unique_ptr are ready-made tags for memory.
Problem → Why → Solution
The problem: manual delete misses the unhappy paths
With raw new and delete, every way out of a function must remember to clean up. The function below allocates a report buffer, returns early when the text is empty, and calls a function that might throw. Each of those paths skips the delete, so memory leaks a little on every bad request. Add a second resource, such as a file, and the number of cleanup paths doubles. Copying the pointer into a second variable and deleting both is the opposite bug, a double delete, which is undefined behaviour.
#include <stdexcept>
#include <string>
struct Buffer {
std::string data;
};
void validate(const std::string& text) {
if (text.size() > 100) throw std::length_error("too long");
}
void saveReport(const std::string& text) {
Buffer* buffer = new Buffer;
if (text.empty()) return; // leak: delete never runs
validate(text); // throws -> leak
buffer->data = text;
delete buffer; // only the happy path gets here
}Why cleanup code is not enough
The problem is not forgetting once; it is that cleanup lives in a different place from acquisition, and every early return or exception creates a new path that must repeat it. C++ guarantees one thing on every path out of a scope, including stack unwinding for a caught exception: destructors of local objects run. RAII moves the cleanup into a destructor, so it happens exactly once, on all paths, without you writing it again.
Core concept: ownership follows lifetime
RAII pairs two moments in an object's life. The constructor acquires the resource, and the destructor, the special member function named ~TypeName(), releases it. A local object's destructor runs automatically when control leaves its scope: at the closing brace, at a return, at a break, or while an exception is propagating out. Objects in the same scope are destroyed in the reverse order of their construction, so something built on top of another resource is torn down first.
Where the destructor runs
-------------------------
void runReport() {
auto temp = std::make_unique<Connection>("report"); // open
...use temp... // a return or throw here: same
} // <- scope ends: temp is destroyed, Connection closesThe standard library is full of RAII types. std::string and std::vector free their memory, std::ifstream closes its file, std::lock_guard unlocks its mutex, and std::jthread joins its thread. If your class only holds members like these, it needs no destructor of its own; their destructors already do the work.
For a single object on the heap, use std::unique_ptr<T>, created with std::make_unique<T>(args...). It is the sole owner: when the unique_ptr is destroyed, it deletes the object. It cannot be copied, because two owners would both delete, but ownership can be moved with std::move, after which the source is guaranteed to be empty (nullptr). It typically has the same size as a raw pointer and no runtime overhead.
When several parts of a program genuinely need to keep one object alive, use std::shared_ptr<T>, made with std::make_shared. It keeps a reference count, and the object is deleted when the last shared_ptr to it goes away. std::weak_ptr observes a shared object without owning it; its lock() returns a shared_ptr only if the object still exists. Raw pointers and references remain fine for non-owning access. What disappears from modern code is the naked new and delete.
| Smart pointer | Owners | Use it when |
|---|---|---|
| std::unique_ptr<T> | exactly one | the default for a heap object |
| std::shared_ptr<T> | many, reference counted | ownership is truly shared |
| std::weak_ptr<T> | none (an observer) | back links, caches, breaking cycles |
- Constructor acquires the resource
- The object owns it while in scope
- Scope ends: return, brace or throw
- Destructor releases it, exactly once
If you can name the object that owns a resource, its destructor is where the release belongs.
General pattern
struct Resource {
Resource() { /* acquire */ }
~Resource() { /* release */ }
};
auto one = std::make_unique<Type>(args); // sole owner
std::unique_ptr<Type> other = std::move(one); // transfer; one is now empty
auto shared = std::make_shared<Type>(args); // reference counted
std::weak_ptr<Type> observer = shared; // does not own
if (auto locked = observer.lock()) { /* the object is still alive */ }Write a destructor only for a class that directly manages a resource. Everywhere else, hold resources in members or smart pointers and let their destructors work. make_unique and make_shared replace new, and nothing in the pattern calls delete.
Example: connections that close themselves
Connection prints a line when it opens and when it closes, so you can watch lifetimes. runReport() owns a temporary connection that closes as the function ends; main then creates a second connection and moves its ownership to another unique_ptr. Match each output line with the place in the code that caused it.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
struct Connection {
std::string name;
explicit Connection(std::string n) : name(std::move(n)) {
std::cout << "open " << name << '\n';
}
~Connection() { std::cout << "close " << name << '\n'; }
};
void runReport() {
auto temp = std::make_unique<Connection>("report");
std::cout << "using " << temp->name << '\n';
}
int main() {
runReport();
auto db = std::make_unique<Connection>("db");
std::unique_ptr<Connection> owner = std::move(db);
std::cout << std::boolalpha << "db is empty: " << (db == nullptr) << '\n';
std::cout << "end of main\n";
}Code breakdown
- Lines 9-11
explicit Connection(std::string n) : name(std::move(n)) {The constructor acquires the resource; here it just prints open. Constructor syntax is covered fully in the Constructors lesson; for now, read it as "store the name, then print".
- Line 12
~Connection() { std::cout << "close " << name << '\n'; }The destructor is the release half of RAII. Nobody calls it by hand: C++ runs it when the owning object is destroyed.
- Lines 15-18
auto temp = std::make_unique<Connection>("report");make_unique creates the Connection on the heap and returns its sole owner. When runReport() ends, temp is destroyed and destroys the Connection, which is why close report appears before open db.
- Lines 24-25
std::unique_ptr<Connection> owner = std::move(db);A unique_ptr cannot be copied, but it can hand ownership over. After the move, db is guaranteed to be null, which the next line prints as true.
- Lines 27-28
std::cout << "end of main\n";end of main prints first; only then does main's scope end and owner close db. The program never calls delete, yet every Connection is closed exactly once.
open report
using report
close report
open db
db is empty: true
end of main
close dbstd::shared_ptr: shared ownership
Sometimes no single object is the natural owner: an image used by several open documents in an editor must stay loaded until the last document closes. std::shared_ptr counts its owners. Copying a shared_ptr adds an owner, destroying one removes an owner, and use_count() reports the current number. Shared ownership has a cost, a thread-safe reference count and a separate control block, so use it when ownership really is shared, not as a default.
#include <iostream>
#include <memory>
#include <string>
int main() {
auto logo = std::make_shared<std::string>("logo.png");
std::cout << "owners: " << logo.use_count() << '\n'; // 1
{
std::shared_ptr<std::string> header = logo;
std::shared_ptr<std::string> footer = logo;
std::cout << "owners: " << logo.use_count() << '\n'; // 3
}
std::cout << "owners: " << logo.use_count() << '\n'; // 1
}Cycles and std::weak_ptr
Reference counting has one blind spot. If A holds a shared_ptr to B and B holds a shared_ptr to A, each keeps the other's count above zero, so neither is ever destroyed, even after every outside pointer is gone. That is a memory leak, and it happens silently. The fix is to make one direction non-owning with std::weak_ptr, typically the back link from child to parent. A weak_ptr does not affect the count; call lock() to get a temporary shared_ptr, which is empty if the object has already been destroyed.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
struct Node {
std::string name;
std::shared_ptr<Node> next; // owning link
std::weak_ptr<Node> prev; // non-owning back link
explicit Node(std::string n) : name(std::move(n)) {}
~Node() { std::cout << "destroy " << name << '\n'; }
};
int main() {
{
auto a = std::make_shared<Node>("A");
auto b = std::make_shared<Node>("B");
a->next = b;
b->next = a; // cycle: A owns B and B owns A
}
std::cout << "cycle scope ended\n"; // no "destroy A" or "destroy B"
{
auto c = std::make_shared<Node>("C");
auto d = std::make_shared<Node>("D");
c->next = d;
d->prev = c; // weak back link: does not own C
if (auto back = d->prev.lock()) {
std::cout << "D can still reach " << back->name << '\n';
}
}
std::cout << "weak scope ended\n"; // C and D were destroyed above
}Never mix raw delete with smart pointers
Do not call delete on p.get(), and do not create two smart pointers from the same raw pointer: writing std::shared_ptr<T>(raw) twice gives two separate counts and a double delete. Create objects with make_unique or make_shared and let the smart pointer be the only owner from the start.
In real projects
Where this shows up in real projects
RAII is the backbone of C++ resource handling. Database client libraries return connection objects that close in their destructors; std::lock_guard and std::scoped_lock make it impossible to forget an unlock in multithreaded code; file wrappers flush and close on scope exit. Because destructors also run during stack unwinding, this is what makes C++ code exception-safe without finally blocks.
In application code, std::unique_ptr is the everyday smart pointer: a std::vector<std::unique_ptr<Shape>> holding different shapes, a pimpl member hiding a class's implementation, or a factory function returning std::unique_ptr<Plugin>. std::shared_ptr appears in caches, observer lists and asynchronous code where a callback must keep an object alive until it runs, and weak_ptr backs parent links in trees and UI hierarchies. Many teams' style rules simply forbid naked new and delete in reviewed code.
Common mistakes
Common mistakes
1. Writing new and delete by hand
auto* p = new Report; ... delete p; leaks on every early return or exception between the two lines. Write auto p = std::make_unique<Report>(); and delete nothing.
2. Trying to copy a unique_ptr
std::unique_ptr<int> p2 = p1; fails with use of deleted function 'std::unique_ptr<...>::unique_ptr(const std::unique_ptr<...>&)'. That is the type protecting you from two owners. Use std::move(p1) to transfer ownership, or pass a reference or raw pointer (p1.get()) to code that only needs to look.
3. Using shared_ptr everywhere
Making every pointer a shared_ptr hides who owns what, costs a reference-count update on each copy, and invites cycles. Start with unique_ptr; switch to shared_ptr only when two owners genuinely need to outlive each other.
4. Building ownership cycles
A parent and child that hold shared_ptr to each other are never destroyed. Make the back link a weak_ptr, or a raw pointer when the parent is known to outlive the child.
Best practices
Best practices
- Give every resource an owner object; that owner's destructor is the one place it is released.
- Create heap objects with std::make_unique (or std::make_shared), never with naked new.
- Pass T& or T* to functions that only use an object; pass std::unique_ptr by value only to transfer ownership.
- Keep destructors short and never let them throw.
Mini challenge
Mini challenge: steps that always finish
Build a tiny job runner whose steps print when they start and finish. Prove that RAII finishes every step even when the job fails half-way, and hand a heap step to a function that takes ownership.
- struct Step: the constructor prints "start <name>", the destructor prints "finish <name>"
- void runJob(bool diskFull) creates download and unzip steps and throws std::runtime_error("disk full") when diskFull is true
- main runs the job once normally and once inside try/catch, printing "caught: " and the message
- Create an upload step with std::make_unique, pass it to void consume(std::unique_ptr<Step> step), then print whether main still owns it
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
struct Step {
std::string name;
// TODO: constructor that stores the name and prints "start <name>"
// TODO: destructor that prints "finish <name>"
};
void runJob(bool diskFull) {
// TODO: two local Steps; throw when diskFull, otherwise print "job done"
}
void consume(std::unique_ptr<Step> step) {
// TODO: print "consuming <name>"; the step finishes when this returns
}
int main() {
// TODO: runJob(false), then runJob(true) inside try/catch
// TODO: make_unique an "upload" step, move it into consume(), then check it
}Expected: The output should be: start download start unzip job done finish unzip finish download start download start unzip finish unzip finish download caught: disk full start upload consuming upload finish upload upload still owned here: false
Show hint
Throwing inside runJob() still destroys download and unzip, in reverse order, before the catch block runs. consume() takes its parameter by value, so std::move(upload) is required, and afterwards upload is guaranteed to be nullptr.
Show solution
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
struct Step {
std::string name;
explicit Step(std::string n) : name(std::move(n)) {
std::cout << "start " << name << '\n';
}
~Step() { std::cout << "finish " << name << '\n'; }
};
void runJob(bool diskFull) {
Step download("download");
Step unzip("unzip");
if (diskFull) {
throw std::runtime_error("disk full");
}
std::cout << "job done\n";
}
void consume(std::unique_ptr<Step> step) {
std::cout << "consuming " << step->name << '\n';
}
int main() {
runJob(false);
try {
runJob(true);
} catch (const std::exception& e) {
std::cout << "caught: " << e.what() << '\n';
}
auto upload = std::make_unique<Step>("upload");
consume(std::move(upload));
std::cout << std::boolalpha << "upload still owned here: "
<< (upload != nullptr) << '\n';
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- RAII: a constructor acquires a resource and the destructor releases it on every path out of the scope.
- Local objects are destroyed automatically, in reverse order, including during exception unwinding.
- std::unique_ptr is the single owner of a heap object: create it with make_unique, transfer it with std::move.
- Use std::shared_ptr only for real shared ownership, and std::weak_ptr for back links that would form cycles.
C++ Core Guidelines — Standard C++ Foundation