The RAII Principle
RAII, short for Resource Acquisition Is Initialisation, is the load-bearing pattern of C++. It welds a resource's lifetime (memory, file handle, socket, lock) to an object's lifetime, full stop.
The Problem RAII Solves
In C, you manage resources manually:
FILE *fp = fopen("data.txt", "r");// ... use fp ...// What if an error occurs here? fp leaks!fclose(fp);An early return on error and the file handle is gone for good. C makes you write meticulous cleanup at every exit point.
RAII in C++
In C++, the destructor runs automatically when an object goes out of scope:
#include <fstream>
void process_file() { std::ifstream file("data.txt"); // opens the file // ... use file ...} // file's destructor runs here, closing the file automaticallyWhichever way the function exits (normal return, thrown exception, early bail-out), the destructor still fires. The exceptions are exits that never unwind the stack: std::exit, std::abort and std::terminate skip the destructors of local objects.
With RAII you never explicitly release a resource. The constructor acquires, the destructor releases, and C++ scope rules guarantee the cleanup runs. Whole categories of resource leaks disappear.
Building Your Own RAII Wrapper
#include <cstdio>#include <stdexcept>
class FileHandle { FILE *fp;public: FileHandle(const char *path, const char *mode) : fp(fopen(path, mode)) { if (!fp) throw std::runtime_error("Cannot open file"); }
~FileHandle() { if (fp) fclose(fp); }
// Prevent copying (we own the resource) FileHandle(const FileHandle &) = delete; FileHandle &operator=(const FileHandle &) = delete;
FILE *get() { return fp; }};Usage:
void example() { FileHandle fh("data.txt", "r"); char buffer[256]; fgets(buffer, sizeof(buffer), fh.get()); // No need to call fclose - destructor handles it}Worked Example: When the Second Open Fails
Here's where the wrapper pays for itself. A copy routine needs two files open at once:
void copy_file(const char *src, const char *dst) { FileHandle in(src, "r"); FileHandle out(dst, "w"); // ... read from in, write to out ...}Call it as copy_file("notes.txt", "/no/such/dir/out.txt"), where notes.txt exists and the output directory doesn't.
Predict: does fclose run, and how many times?
Once, for in. Step by step:
FileHandle in(src, "r")callsfopen, which returns a validFILE *. The constructor body finishes, soinis now a fully constructed object, and C++ promises to destroy it.FileHandle out(dst, "w")callsfopen, which returnsNULL(witherrnoset toENOENT, as the directory doesn't exist). The constructor throwsstd::runtime_error.outnever finished constructing, so its destructor doesn't run. That's correct here: there's no file to close.- The exception leaves
copy_file, and on the way out the stack unwinds. Every fully constructed local is destroyed in reverse order, which here means onlyin.~FileHandlesees a non-nullfpand callsfclose. - The caller's
catchreceives the exception, and no handle has leaked.
The C equivalent needs a fclose(in) on the error path for out, and another one for every later failure point. Forget one and the leak only shows up when that particular error happens.
The rule from step 3 is worth carrying with you: a destructor only runs for an object whose constructor completed. If a constructor acquires two resources and the second acquisition throws, the first one is yours to release, unless it's already held by a member that's an RAII object itself.
Scope-Based Lifetime
RAII works because C++ has deterministic destruction. When a scope ends, objects die in reverse order of construction:
{ ResourceA a; // constructed first ResourceB b; // constructed second} // b destroyed first, then aThat reverse ordering keeps dependencies honest — if b leans on a, b gets torn down first.
The same order holds when an exception rips through the scope. Predict the output, then run it: each Tracer announces its own birth and death.
Moving Ownership
FileHandle refuses to be copied, since two objects calling fclose on one FILE * would be a double close. That also means you can't return one from a function or store it in a std::vector. The fix is to make it movable: a move hands the pointer to the new object and leaves the old one empty.
FileHandle(FileHandle &&other) noexcept : fp(other.fp) { other.fp = nullptr; // the old object no longer owns anything}
FileHandle &operator=(FileHandle &&other) noexcept { if (this != &other) { if (fp) fclose(fp); // release what we held fp = other.fp; other.fp = nullptr; } return *this;}The destructor already checks if (fp), so an emptied object destroys itself quietly. Exactly one object owns the file at any moment, and that's the shape of std::unique_ptr and std::fstream too. The move semantics lesson covers && and std::move properly.
The Same Pattern for Locks
RAII isn't only about memory and files. Here's a lock wrapper with the same shape as std::lock_guard:
#include <mutex>
class ScopedLock { std::mutex &m;public: explicit ScopedLock(std::mutex &mtx) : m(mtx) { m.lock(); } ~ScopedLock() { m.unlock(); } ScopedLock(const ScopedLock &) = delete; ScopedLock &operator=(const ScopedLock &) = delete;};
std::mutex counter_mutex;int counter = 0;
void bump() { ScopedLock guard(counter_mutex); // locked here ++counter;} // unlocked here, however bump() exitsForgetting to unlock a mutex on an error path doesn't leak memory. It freezes every other thread that wants the lock. The synchronisation lesson puts the real std::lock_guard and std::scoped_lock to work.
C Cleanup Next to RAII
Here's one function written twice. The C version opens a file, allocates a buffer and locks a mutex, and every failure has to goto the label that releases exactly what's held so far. The C++ version uses FileHandle, std::vector and ScopedLock, and has no cleanup code at all.
Cleanup in C and C++, step by step
Both versions open a file, allocate a buffer and lock a mutex, then call parse. Pick a path and step through to see who releases what, and in which order.
C with goto cleanup
11 steps- static pthread_mutex_t table_lock =
- PTHREAD_MUTEX_INITIALIZER;
- int parse(FILE *fp, char *buf);
- int process(const char *path) {
- int rc = -1;
- FILE *fp;
- char *buf;
- fp = fopen(path, "r");
- if (!fp)
- goto out;
- buf = malloc(4096);
- if (!buf)
- goto close_file;
- if (pthread_mutex_lock(&table_lock) != 0)
- goto free_buf;
- rc = parse(fp, buf);
- pthread_mutex_unlock(&table_lock);
- free_buf:
- free(buf);
- close_file:
- fclose(fp);
- out:
- return rc;
- }
| File open | Not yet |
|---|---|
| Buffer allocated | Not yet |
| Mutex held | Not yet |
Press Next to start.
C++ with RAII
9 steps- // FileHandle and ScopedLock: the classes above
- std::mutex table_lock;
- int parse(std::FILE *fp, char *buf); // may throw
- int process(const char *path) {
- FileHandle file(path, "r");
- std::vector<char> buf(4096);
- ScopedLock guard(table_lock);
- return parse(file.get(), buf.data());
- }
| File open | Not yet |
|---|---|
| Buffer allocated | Not yet |
| Mutex held | Not yet |
Press Next to start.
Step through each failure path and compare the resource tables, then pick "parse throws" and watch the destructors fire newest first. After that, tick "Buggy C" and run "Lock fails": one wrong label and the buffer leaks, while every other path still looks fine.
RAII Everywhere
The standard library uses RAII throughout:
std::stringmanages character buffersstd::vectormanages dynamic arraysstd::unique_ptrmanages heap objectsstd::lock_guardmanages mutex locksstd::fstreammanages file handles
In modern C++ you almost never reach for new or delete by hand.