Table of Contents

C++ RAII

RAII (Resource Acquisition Is Initialization) ties resource lifetimes to object lifetimes: acquiring a resource (opening a file, allocating memory, locking a mutex) happens in a constructor, and releasing it happens in the destructor. Resources are automatically released when the object goes out of scope, eliminating manual cleanup and preventing leaks.

Use RAII for all resources: use smart pointers for memory, guard locks for mutexes, and wrapper classes for file handles and other system resources.

Example

This example shows RAII automatically releasing a file handle through the destructor.

// compile: g++ -o raii raii.cpp
// run: ./raii
// description: RAII automatically releases resources in destructor
 
#include <iostream>
#include <fstream>
 
class FileGuard {
private:
    std::FILE* file;
public:
    FileGuard(const char* name) {
        file = std::fopen(name, "w");
        if (file) std::cout << "File opened\n";
    }
 
    ~FileGuard() {
        if (file) {
            std::fclose(file);
            std::cout << "File closed\n";
        }
    }
 
    void write(const char* data) {
        if (file) std::fputs(data, file);
    }
};
 
int main() {
    {
        FileGuard f("data.txt");
        f.write("Hello\n");
    }  // destructor runs here, file closed automatically
 
    return 0;
}