RAII
RAII ties a resource to the lifetime of an object. The constructor acquires the resource, the destructor releases it, so cleanup happens automatically when the object goes out of scope.
Detailed Explanation
RAII stands for Resource Acquisition Is Initialization. The name is unhelpful. A better name would be "the destructor cleans up for you".
Here is the problem it solves. A resource is anything you must give back: heap memory, an open file, a socket, a database connection, a lock. In C you acquire it, use it, and call the matching release function. The trouble is the release call is easy to miss. An early return skips it. A break skips it. In C++, a thrown exception skips it too, and an exception can come from any function you call.
RAII moves the release into a destructor. C++ guarantees that when an object with automatic storage duration goes out of scope, its destructor runs. That guarantee holds for a normal return, an early return, a break, and a thrown exception. This last case is called stack unwinding: as the exception propagates, every fully constructed local object on the way out gets destroyed. So if the release lives in a destructor, it cannot be skipped.
The pattern is a small class that owns exactly one thing:
- The constructor takes ownership of the resource, or acquires it.
- The destructor releases it.
- Copying is either disabled or defined to do something sensible, because two owners releasing the same resource is a double free.
You rarely write these classes yourself anymore. The standard library already provides them. std::unique_ptr owns heap memory. std::vector and std::string own their buffers. std::lock_guard owns a lock. std::fstream owns a file handle. When people say "modern C++ does not leak", they mean the standard library types are RAII types and you compose them instead of calling new and delete by hand.
RAII is also what makes exception safety practical. Without it, writing a function that can throw at three different points and still release four resources means a nest of goto cleanup labels or try/catch blocks. With it, you declare the owning objects and write the straight-line logic. The cleanup path is implied by the declarations.
Two consequences worth internalising. First, ownership becomes visible in the type. A std::unique_ptr<Connection> says "I will close this"; a raw Connection* says nothing. Second, destruction order is deterministic and reverse of construction order within a scope. That matters when one resource depends on another, for example a buffer that must outlive the writer using it.
The cost is low. A destructor call is usually inlined, and for std::unique_ptr the generated code matches a hand-written delete. What you pay is design effort: you must decide who owns each resource, and you must not defeat the mechanism by leaking raw owning pointers out of the class.
Code Examples
#include <cstdio>
#include <stdexcept>
// A minimal RAII wrapper around a C FILE*.
class FileHandle {
public:
explicit FileHandle(const char* path, const char* mode)
: file_(std::fopen(path, mode)) {
if (!file_) throw std::runtime_error("cannot open file");
}
~FileHandle() {
if (file_) std::fclose(file_); // runs on every exit path
}
// A file handle has one owner. Copying would close it twice.
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
std::FILE* get() const { return file_; }
private:
std::FILE* file_;
};
void writeReport() {
FileHandle out("report.txt", "w");
std::fputs("header\n", out.get());
if (somethingWentWrong()) throw std::runtime_error("bad data");
// No fclose here. The destructor runs even when the throw above fires.
}#include <memory>
#include <mutex>
#include <vector>
std::mutex cacheMutex;
std::vector<int> cache;
void addEntry(int value) {
std::lock_guard<std::mutex> lock(cacheMutex); // locks now
cache.push_back(value); // may throw on allocation
} // unlocks here, always
std::unique_ptr<int[]> makeBuffer(std::size_t n) {
auto buffer = std::make_unique<int[]>(n); // owns the allocation
return buffer; // ownership moves to the caller
} // no delete[] needed anywhereCommon Gotchas
Do not throw from a destructor
if a destructor throws while an exception is already propagating, the program calls `std::terminate`. Destructors are implicitly `noexcept`. Catch and log inside the destructor, or expose an explicit `close()` for callers who want to handle failure.
A destructor only runs if the constructor finished
if a constructor throws partway through, the object was never created and its destructor is not called. Members already constructed are destroyed, so put each resource in its own RAII member rather than acquiring several raw handles in one constructor body.
Guard objects need a name
`std::lock_guard<std::mutex>(cacheMutex);` creates a temporary that is destroyed at the end of that statement, unlocking immediately. Always name the variable.
RAII covers more than memory
locks, timers, scoped log contexts, and terminal state restoration all fit the pattern. Anything with a matching acquire and release pair is a candidate.