Skip to content
AgileLogics
5 min read

RAII & Resource Management

Prerequisites: Exception handling

RAII (Resource Acquisition Is Initialization) ties a resource's lifetime to an object's lifetime — acquire it in the constructor, release it in the destructor, and the compiler guarantees the destructor runs when the object goes out of scope, even if an exception is thrown in between.

class FileHandle {
private:
    FILE *file;

public:
    FileHandle(const char *path) {
        file = fopen(path, "r");
    }

    ~FileHandle() {
        if (file) fclose(file); // always runs — no way to forget it
    }
};

void readData() {
    FileHandle handle("data.txt");
    // ... whether this function returns normally OR throws,
    // handle's destructor still runs and closes the file.
}

This is C++'s central idiom — nearly every standard library type that owns a resource (std::vector, std::string, smart pointers, std::lock_guard) is built on exactly this pattern, which is why manual free/fclose/unlock calls are rare in idiomatic modern C++.