RAII: Resource Acquisition Is Initialization

Difficulty: Intermediate

Question

What is RAII? Why is it considered the most important idiom in C++, and can you give examples from the standard library?

Answer

If I had to pick one idea that separates good C++ from C-with-classes, it would be RAII. The name is famously awkward, but the concept is simple and powerful, so let's unpack it.

RAII stands for Resource Acquisition Is Initialization. The rule: tie the lifetime of a resource (heap memory, a file handle, a mutex lock, a database connection, a socket) to the lifetime of an object. You acquire the resource in the constructor and release it in the destructor. Because C++ guarantees that destructors of automatic objects run when they leave scope, whether by normal flow, an early return, or an exception, the resource is released deterministically without you writing cleanup code at every exit path.

A good analogy is a hotel room key card that automatically deactivates at checkout. You do not have to remember to return anything: once you walk out of the door of scope, the card is dead. Compare that with the C style of goto cleanup labels or matching every malloc with a free on every return path, which is fragile and breaks the moment someone adds a new early return or a call that can throw.

The standard library is full of RAII. std::vector and std::string own their heap buffers. std::unique_ptr and std::shared_ptr own objects. std::ifstream and std::ofstream close their files on destruction. std::lock_guard and std::unique_lock unlock a mutex when they die, which is the standard defence against forgotten unlocks and deadlocks caused by exceptions. Even std::thread must be joined or detached before destruction, and C++20 introduced std::jthread, an RAII thread that joins automatically.

Designing your own RAII class means paying attention to copying. If the object owns something exclusive, like a file handle, the copy constructor should be deleted and you should provide a move constructor that transfers ownership, leaving the source empty. Otherwise two objects would release the same resource, causing a double free. This is exactly why RAII and the rule of five go together.

Destructors should not throw: if a destructor throws during stack unwinding from another exception, std::terminate is called. So destructors must swallow or log errors, and are implicitly noexcept in modern C++.

Compare with Java's try-finally or Python's with-statement. Those need the caller to remember to use the construct; RAII bakes cleanup into the type itself, so it is impossible to use it wrong. That is the payoff to emphasise: it makes correctness the default, and makes exception safety nearly free.

Code examples

A tiny RAII file wrapper and lock_guard

#include <cstdio>
#include <iostream>
#include <mutex>
#include <stdexcept>

class File {
    std::FILE* f_;
public:
    explicit File(const char* path, const char* mode) : f_(std::fopen(path, mode)) {
        if (!f_) throw std::runtime_error("open failed");
        std::cout << "opened\n";
    }
    ~File() { if (f_) { std::fclose(f_); std::cout << "closed\n"; } }
    File(const File&) = delete;              // exclusive ownership
    File& operator=(const File&) = delete;
    std::FILE* get() const { return f_; }
};

std::mutex m;
int shared = 0;

void work(bool fail) {
    std::lock_guard<std::mutex> lock(m);     // unlocked on every exit path
    ++shared;
    if (fail) throw std::runtime_error("oops");
}

int main() {
    try {
        File f("raii_demo.tmp", "w");
        std::fputs("hi", f.get());
        throw std::runtime_error("something went wrong");
    } catch (const std::exception& e) {
        std::cout << "caught: " << e.what() << "\n";
    }
    try { work(true); } catch (...) {}
    work(false);                              // works: lock was released
    std::cout << shared << "\n";
    std::remove("raii_demo.tmp");
}

The file is closed during stack unwinding before the catch block runs. The mutex is released even though work(true) threw, so the second call does not deadlock.

Key points

Common follow-up questions

Interview tips

Concepts covered

RAII, destructors, exception safety, lock_guard

More C++ & STL questions