Skip to main content
Be Bitwise
C++C++ Basics & RAII

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:

c
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:

cpp
#include <fstream>
void process_file() {
std::ifstream file("data.txt"); // opens the file
// ... use file ...
} // file's destructor runs here, closing the file automatically

Whichever 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.

Key Concept

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

cpp
#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:

cpp
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:

cpp
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:

  1. FileHandle in(src, "r") calls fopen, which returns a valid FILE *. The constructor body finishes, so in is now a fully constructed object, and C++ promises to destroy it.
  2. FileHandle out(dst, "w") calls fopen, which returns NULL (with errno set to ENOENT, as the directory doesn't exist). The constructor throws std::runtime_error.
  3. out never finished constructing, so its destructor doesn't run. That's correct here: there's no file to close.
  4. 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 only in. ~FileHandle sees a non-null fp and calls fclose.
  5. The caller's catch receives 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:

cpp
{
ResourceA a; // constructed first
ResourceB b; // constructed second
} // b destroyed first, then a

That 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.

Try itMove the throw above Tracer b, or delete it, and watch which destructors still run.
C++ (GCC 9.2.0)

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.

cpp
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:

cpp
#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() exits

Forgetting 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
  1. static pthread_mutex_t table_lock =
  2. PTHREAD_MUTEX_INITIALIZER;
  3. int parse(FILE *fp, char *buf);
  4. int process(const char *path) {
  5. int rc = -1;
  6. FILE *fp;
  7. char *buf;
  8. fp = fopen(path, "r");
  9. if (!fp)
  10. goto out;
  11. buf = malloc(4096);
  12. if (!buf)
  13. goto close_file;
  14. if (pthread_mutex_lock(&table_lock) != 0)
  15. goto free_buf;
  16. rc = parse(fp, buf);
  17. pthread_mutex_unlock(&table_lock);
  18. free_buf:
  19. free(buf);
  20. close_file:
  21. fclose(fp);
  22. out:
  23. return rc;
  24. }
Resource state
File openNot yet
Buffer allocatedNot yet
Mutex heldNot yet

Press Next to start.

C++ with RAII

9 steps
  1. // FileHandle and ScopedLock: the classes above
  2. std::mutex table_lock;
  3. int parse(std::FILE *fp, char *buf); // may throw
  4. int process(const char *path) {
  5. FileHandle file(path, "r");
  6. std::vector<char> buf(4096);
  7. ScopedLock guard(table_lock);
  8. return parse(file.get(), buf.data());
  9. }
Resource state
File openNot yet
Buffer allocatedNot yet
Mutex heldNot yet
Live locals, newest on top
none
Destructors run
none 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::string manages character buffers
  • std::vector manages dynamic arrays
  • std::unique_ptr manages heap objects
  • std::lock_guard manages mutex locks
  • std::fstream manages file handles

In modern C++ you almost never reach for new or delete by hand.