The Analogy: A Hotel Room Key Card
Check into a hotel and you are handed a key card. You do not sign a separate undertaking to return it, remember to hand it in on the way out, or leave yourself a note in case you leave in a hurry. Checkout is the return of the card; the two events are the same event. Even if the fire alarm goes off and you leave through a window, the room reverts to the hotel — because the room's release was never something you had to remember to do.
RAII — Resource Acquisition Is Initialization — is that idea applied to code. You tie a resource's lifetime to an object's lifetime. Acquiring happens in the constructor. Releasing happens in the destructor. There is no third step, no cleanup call for a caller to forget, and no path out of the room that skips the return of the card.
The name is unhelpfully academic and describes only half the mechanism. The half that matters is the destructor: C++ guarantees that when an object goes out of scope, its destructor runs. Not usually. Not on the paths you thought of. Always — on a normal return, an early return, a break, and, crucially, on an exception unwinding the stack through your function. That single guarantee is what makes C++ resource handling reliable, and it is the reason the language needs no finally block: the destructor is the finally.
Every tool from the last few lessons is RAII wearing a specific hat. std::vector is RAII for heap memory. std::unique_ptr is RAII for one heap object. std::ofstream is RAII for a file handle. std::lock_guard is RAII for a mutex. Learn the pattern once and all of them stop being separate facts.
Syntax or Core Structure
#include <iostream>
#include <stdexcept>
#include <string>
// The pattern, in its entirety.
class Connection {
public:
// 1. ACQUIRE in the constructor.
explicit Connection(std::string target) : host(std::move(target)) {
std::cout << " open " << host << "\n";
open = true;
}
// 2. RELEASE in the destructor.
~Connection() {
if (open) {
std::cout << " close " << host << "\n";
}
}
// 3. Forbid copying -- two objects must not own one resource.
Connection(const Connection&) = delete;
Connection& operator=(const Connection&) = delete;
void send(const std::string& message) const {
std::cout << " send " << message << " -> " << host << "\n";
}
private:
std::string host;
bool open = false;
};
void scopes() {
std::cout << "before block\n";
{
Connection c("db.internal");
c.send("SELECT 1");
} // <-- destructor here, guaranteed
std::cout << "after block\n";
}
void earlyReturn(bool bail) {
Connection c("cache.internal");
if (bail) {
std::cout << " bailing out\n";
return; // destructor still runs
}
c.send("GET key");
}
void withException() {
Connection c("queue.internal");
throw std::runtime_error("network fault"); // destructor STILL runs
}
int main() {
scopes();
std::cout << "\nearly return:\n";
earlyReturn(true);
std::cout << "\nexception:\n";
try {
withException();
} catch (const std::exception& e) {
std::cout << " caught " << e.what() << "\n";
}
}
Output:
before block
open db.internal
send SELECT 1 -> db.internal
close db.internal
after block
early return:
open cache.internal
bailing out
close cache.internal
exception:
open queue.internal
close queue.internal
caught network fault
Note the order in the last block: the connection closes before the catch runs. Cleanup happens as the stack unwinds, not afterwards.
Technical Depth: The Guarantee, and How Not to Break It
Why manual cleanup cannot be made to work
void manual() {
Connection* c = new Connection("db");
if (!validate()) return; // LEAK
if (risky()) throw std::runtime_error("x"); // LEAK
process(c); // may itself throw -- LEAK
delete c;
}
There are three leaks and only one is visible. The third is the worst: process might throw today, or might start throwing next year when somebody adds a check to it, and your function silently acquires a leak without being edited. You cannot audit your way out of this, because the set of exit paths is not a property of the code you can see.
The RAII version has no exit paths to audit:
void raii() {
Connection c("db"); // that is the whole fix
if (!validate()) return;
if (risky()) throw std::runtime_error("x");
process(c);
}
What the language guarantees, exactly
For an object with automatic storage duration, the destructor runs when control leaves its scope by any means:
| Exit path | Destructor runs? |
|---|---|
| Falling off the end of the block | Yes |
return | Yes |
break, continue, goto out of the scope | Yes |
| An exception unwinding through | Yes |
std::exit() | No — no unwinding |
std::abort(), a signal, std::terminate | No |
longjmp past it | No — undefined behaviour |
The exceptions to the rule are all abnormal terminations. In ordinary control flow the guarantee is absolute, and destruction is in reverse order of construction, which is what makes dependent resources unwind correctly.
The standard library is already RAII
You have been using it since module 1:
| Resource | RAII type | Released by |
|---|---|---|
| Heap array | std::vector, std::string | Destructor |
| One heap object | std::unique_ptr | Destructor |
| Shared heap object | std::shared_ptr | Last owner's destructor |
| File handle | std::ifstream, std::ofstream | Destructor |
| Mutex lock | std::lock_guard, std::scoped_lock | Destructor |
| Thread | std::jthread (C++20) | Destructor joins |
{
std::ofstream out("log.txt"); // opened
out << "entry\n";
} // flushed and closed, even on a throw
You write your own RAII class only for resources the library does not already cover — a C library handle, an OS resource, a temporary state change you must undo.
The rule of three, five and zero
Any class holding a resource must answer: what happens when it is copied?
class Bad {
int* data;
public:
Bad() : data(new int[100]) {}
~Bad() { delete[] data; }
// implicit copy constructor copies the POINTER
};
Bad a;
Bad b = a; // both point at the same array -- DOUBLE FREE at scope exit
Rule of three: if you write a destructor, you almost certainly need a copy constructor and copy assignment operator too. Rule of five adds the move constructor and move assignment. Rule of zero, the one to aim for: write none of them, by holding your resources in types that already manage themselves.
class Good {
std::vector<int> data{100}; // manages itself
// no destructor, no copy, no move -- all correct by default
};
For an exclusive resource that genuinely cannot be copied, say so explicitly:
Connection(const Connection&) = delete;
Connection& operator=(const Connection&) = delete;
Connection(Connection&&) noexcept; // moving is usually fine
Connection& operator=(Connection&&) noexcept;
Destructors must not throw
This is a hard rule, not a preference. If an exception is already unwinding the stack and a destructor throws a second one, the program calls std::terminate immediately.
~Writer() {
try {
flush(); // might throw
} catch (...) {
// swallow it, or log it -- but do NOT let it escape
}
}
Destructors are implicitly noexcept. If a failure genuinely needs reporting, give the class an explicit close() that may throw, and have the destructor call the non-throwing path as a fallback. This is exactly what std::ofstream does: the destructor closes silently, and you check out.good() yourself if you care.
Scope guards: RAII for things that are not resources
The pattern generalises to any "do X, and undo it whatever happens":
class FormatGuard {
public:
explicit FormatGuard(std::ostream& s) : stream(s), saved(s.flags()) {}
~FormatGuard() { stream.flags(saved); } // restore, always
FormatGuard(const FormatGuard&) = delete;
private:
std::ostream& stream;
std::ios_base::fmtflags saved;
};
void printTable() {
FormatGuard guard(std::cout); // save formatting state
std::cout << std::hex << std::setw(8); // change it freely
} // restored on the way out
The same shape handles a temporary directory change, a paused timer, a disabled UI element, or a nesting depth counter. There is no resource being freed — just a state change being undone reliably.
One object, one resource
class Bad {
std::FILE* input;
std::FILE* output;
public:
Bad() {
input = std::fopen("in.txt", "r");
output = std::fopen("out.txt", "w"); // if THIS throws, input leaks
}
};
A constructor that fails part-way through has a real problem: the object was never constructed, so its destructor will not run, and anything already acquired in the body leaks. Only fully constructed members are destroyed. So hold each resource in its own RAII member:
class Good {
std::ifstream input{"in.txt"};
std::ofstream output{"out.txt"}; // if this throws, input's dtor still runs
};
That is the rule of zero paying for itself, and it is why "one resource per class" is not fussiness.
Order of destruction, and why it is reverse
{
Logger log("run.txt");
Transaction tx(log); // uses log
Connection conn(tx); // uses tx
} // conn, then tx, then log
Reverse order means a dependency is always destroyed after the thing depending on it, so tx can still write to log while shutting down. Members are destroyed in reverse declaration order for the same reason — which is also why constructor initialiser lists must follow declaration order.
RAII versus the alternatives
| Approach | Runs on exceptions | Boilerplate | Available in |
|---|---|---|---|
| RAII destructor | Yes | None at the call site | C++ |
try / catch with manual cleanup | Yes, if you write it everywhere | High, repeated | C++ |
finally block | Yes | Per call site | Java, C# |
defer | Yes | Per call site | Go, Zig |
goto cleanup | No | High | C |
RAII's advantage over finally and defer is that the guarantee lives in the type, written once, rather than at every place the resource is used. A caller of Connection cannot get the cleanup wrong, because there is nothing for them to write.
Real World Example: A Transactional File Writer
Writing a file in place is dangerous: if the program dies half-way, the original is already ruined. The safe pattern is to write to a temporary file and rename it over the original only once everything succeeded — an atomic swap. That gives us three separate things to clean up on every exit path, including a thrown exception, which makes it an honest test of the pattern.
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
// RAII #1: a temporary file that deletes itself unless explicitly kept.
class TempFile {
public:
explicit TempFile(std::filesystem::path target)
: path(std::move(target)), stream(path, std::ios::trunc) {
if (!stream) {
throw std::runtime_error("cannot create " + path.string());
}
std::cout << " [temp created " << path.filename().string() << "]\n";
}
~TempFile() {
stream.close();
if (!keep) {
std::error_code ignored;
std::filesystem::remove(path, ignored); // non-throwing overload
std::cout << " [temp discarded]\n";
}
}
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
std::ofstream& out() { return stream; }
const std::filesystem::path& name() const { return path; }
void commit() { keep = true; }
private:
std::filesystem::path path;
std::ofstream stream;
bool keep = false;
};
// RAII #2: a scope guard that restores stream formatting whatever happens.
class FormatGuard {
public:
explicit FormatGuard(std::ostream& s)
: stream(s), flags(s.flags()), precision(s.precision()) {}
~FormatGuard() {
stream.flags(flags);
stream.precision(precision);
}
FormatGuard(const FormatGuard&) = delete;
private:
std::ostream& stream;
std::ios_base::fmtflags flags;
std::streamsize precision;
};
// RAII #3: an indent counter, proving the pattern needs no "resource" at all.
class Trace {
public:
explicit Trace(std::string what) : label(std::move(what)) {
std::cout << pad() << "-> " << label << "\n";
++depth;
}
~Trace() {
--depth;
std::cout << pad() << "<- " << label << "\n";
}
Trace(const Trace&) = delete;
private:
static std::string pad() { return std::string(depth * 2, ' '); }
std::string label;
static int depth;
};
int Trace::depth = 0;
struct Row {
std::string name;
double amount = 0.0;
};
void writeRows(std::ostream& out, const std::vector<Row>& rows) {
Trace t("writeRows");
FormatGuard guard(out); // formatting restored on exit
out << std::fixed << std::setprecision(2);
for (const Row& r : rows) {
if (r.amount < 0.0) {
throw std::invalid_argument("negative amount for " + r.name);
}
out << std::left << std::setw(12) << r.name
<< std::right << std::setw(10) << r.amount << "\n";
}
}
// Writes atomically: the target is only replaced if everything succeeded.
void saveReport(const std::filesystem::path& target,
const std::vector<Row>& rows) {
Trace t("saveReport");
std::filesystem::path temp = target;
temp += ".part";
TempFile scratch(temp);
writeRows(scratch.out(), rows); // may throw -- that is the point
scratch.out().flush();
if (!scratch.out()) {
throw std::runtime_error("write failed");
}
scratch.commit(); // survive the destructor
std::filesystem::rename(scratch.name(), target);
std::cout << " [committed " << target.filename().string() << "]\n";
}
int main() {
const std::vector<Row> good{{"rent", 1200.00}, {"power", 84.50}};
const std::vector<Row> bad{{"rent", 1200.00}, {"refund", -20.00}};
std::cout << std::boolalpha;
std::cout << "=== success ===\n";
saveReport("report.txt", good);
std::cout << "report.txt exists: "
<< std::filesystem::exists("report.txt") << "\n";
std::cout << "\n=== failure ===\n";
try {
saveReport("summary.txt", bad);
} catch (const std::exception& e) {
std::cout << " caught: " << e.what() << "\n";
}
std::cout << "summary.txt exists: "
<< std::filesystem::exists("summary.txt") << "\n";
std::cout << "summary.txt.part exists: "
<< std::filesystem::exists("summary.txt.part") << "\n";
std::cout << "\nformatting still default: " << 3.14159 << "\n";
std::filesystem::remove("report.txt");
}
Output:
=== success ===
-> saveReport
[temp created report.txt.part]
-> writeRows
<- writeRows
[committed report.txt]
<- saveReport
report.txt exists: true
=== failure ===
-> saveReport
[temp created summary.txt.part]
-> writeRows
<- writeRows
[temp discarded]
<- saveReport
caught: negative amount for refund
summary.txt exists: false
summary.txt.part exists: false
formatting still default: 3.14159
The failure case is where the whole lesson lives. writeRows throws part-way through the second row, having already written the first to disk. Nothing in saveReport catches it, and saveReport contains no cleanup code at all — yet by the time main prints caught:, four separate things have already been put right, in reverse order of construction: the FormatGuard restored std::cout's flags, the Trace for writeRows decremented the depth and printed its closing arrow, the TempFile closed and deleted the half-written scratch file, and the outer Trace closed. The final two exists checks prove it: no target file, and no debris left behind. Compare that with the manual version, which would need a try/catch in saveReport duplicating all four steps, and would still miss any exception thrown from a line added later.
commit() is the interesting design detail. A pure RAII object always releases; but a transactional one needs an escape hatch, because success and failure call for different cleanup. Setting a keep flag inverts the default: the destructor still always runs, and it deletes the temporary unless something explicitly told it not to. Crucially, commit() is called after every operation that could fail, so any earlier throw leaves keep false and the file is discarded. Getting that ordering backwards would leave .part files scattered around after every failure. This is the same shape as a database transaction: the destructor is the rollback, and commit is the only way to avoid it.
Note the destructor's care to be non-throwing. It uses the std::error_code overload of std::filesystem::remove rather than the throwing one, because the destructor may be running during an exception unwind — and a second exception escaping there terminates the program outright. That is the hard rule from the technical section, applied. The stream.close() before the remove matters too, since some platforms refuse to delete an open file.
Trace is included precisely because it manages no resource whatsoever. There is nothing to free, no handle, no memory — just an indent counter that must go back down however the function exits. It is RAII used purely for symmetry of control flow, and the perfectly nested arrows in the output, in both the success and the failure case, are that symmetry made visible. Once you see that Trace, FormatGuard and TempFile are the same pattern applied to a counter, some stream flags and a file, you have the idea.
The one thing to notice about saveReport's own body: it reads as a straight-line description of what should happen, with no cleanup interleaved. That is the real product of RAII. The error handling did not disappear — it moved into three small classes, each written and reviewed once, where it cannot be forgotten at a call site.
Common Mistakes
- Writing a destructor but not addressing copying. The default copy duplicates a handle and you get a double release. Delete the copy operations or implement them.
- Letting a destructor throw. During an exception unwind this calls
std::terminate. Catch and swallow, or use non-throwing overloads. - Acquiring several resources in one constructor body. If the second acquisition throws, the destructor never runs and the first leaks. One RAII member per resource.
- Expecting destructors after
std::exitorabort. No unwinding happens. Do not rely on RAII for process-exit cleanup. - Writing your own class where the library already has one. Use
std::vector,std::unique_ptr,std::ofstream,std::lock_guard. - Keeping an explicit
cleanup()that callers must call. If they can forget it, they will. The destructor should be sufficient. - Creating an unnamed guard.
std::lock_guard<std::mutex>(m);is a temporary that dies immediately, unlocking at once. Name it:std::lock_guard<std::mutex> guard(m);. - Using
newfor the guard.new FormatGuard(...)moves it to the heap and its destructor now depends on adeleteyou might skip. Guards belong on the stack. - Ignoring destruction order. Members are destroyed in reverse declaration order; declare a dependency before whatever depends on it.
- Making a guard copyable. Two guards releasing one resource is a double release. Delete the copy, allow the move if it is useful.
Best Practices
- Every resource gets an owner object. If you write
new,fopen,lock, orCreateHandle, the release belongs in a destructor. - Acquire in the constructor, release in the destructor, and nowhere else.
- Aim for the rule of zero. Compose from self-managing members and write no destructor at all.
- One resource per class. It keeps the failure cases trivial.
- Make destructors
noexceptin practice — use non-throwing APIs inside them. - Delete the copy operations for exclusive resources; provide moves if transfer is meaningful.
- Always name your guards, and always put them on the stack.
- Add a
commit()-style flag for transactional cleanup, and set it only after the last operation that can fail. - Use scope guards for state, not just resources — formatting, counters, temporary settings.
- Prefer the standard RAII types to anything you would write yourself.
Practice Exercises
- Write a
Timerclass that records the start time in its constructor and prints the elapsed duration in its destructor. Use it in a function with threereturnstatements and confirm the timing prints on all three paths. - Write a
FileHandleclass wrappingstd::FILE*withfopenin the constructor andfclosein the destructor. Delete its copy operations, then write a comment explaining the exact bug the deletion prevents. - Take the leaky
manual()function from this lesson and fix it twice: once withtry/catchand manualdeleteon every path, once with RAII. Count the lines, then add a fourth exit path to each version and note which one you had to modify. - Write a
ScopeGuardthat takes a lambda in its constructor and calls it in its destructor, so thatScopeGuard g([]{ std::cout << "done\n"; });works. Then explain why it must not be copyable, and why the lambda must not throw.