RAII (C++)
RAII (Resource Acquisition Is Initialization) is a C++ idiom where a resource's lifetime is tied to an object's lifetime. The object acquires the resource in its constructor and releases it in its destructor.
C++
Because a destructor runs automatically when an object goes out of scope — even if an exception is thrown — RAII guarantees cleanup without manual code. This applies to memory, files, locks, and network connections.
RAII is the foundation of smart pointers and standard containers, and it is one of the most important reasons C++ code can be both fast and safe.
Examples
C++
#include <iostream>
#include <fstream>
int main() {
{
std::ofstream file("out.txt"); // opened here
file << "hello";
} // file closed automatically when it goes out of scope
std::cout << "done" << std::endl;
return 0;
}Output:
done