C/C++ Arena

RAII and destructors in C++

Resource Acquisition Is Initialization explained, how destructors free resources automatically, and the rule of zero.

RAII ties a resource to an object's lifetime: the constructor acquires it and the destructor releases it. Because destructors run automatically when an object goes out of scope, including on early returns and exceptions, cleanup can't be forgotten.

The standard library is built on it: std::vector frees its memory, std::fstream closes its file, std::lock_guard unlocks its mutex, and std::unique_ptr deletes its object.

Objects are destroyed in reverse order of creation. Following the rule of zero, most classes should hold RAII members and write no destructor or copy operations at all.

Example

#include <iostream>

struct Guard {
    const char *name;
    explicit Guard(const char *n) : name(n) { std::cout << "acquire " << name << "\n"; }
    ~Guard() { std::cout << "release " << name << "\n"; }
};

int main() {
    Guard a("file");
    {
        Guard b("lock");
    }
    std::cout << "done\n";
    return 0;
}

Output:

acquire file
acquire lock
release lock
done
release file

Watch it run: Constructors, destructors and scope

Practice it