RAII (Resource Acquisition Is Initialization) is the single most important architectural idiom in the C++ programming language. Invented by Bjarne Stroustrup, it completely eliminates resource leaks without requiring a garbage collector.
#include <iostream>
#include <fstream>
#include <string>
class SafeFile {
private:
std::ofstream fileStream;
public:
// 1. Acquire resource in constructor
explicit SafeFile(const std::string& filename) {
fileStream.open(filename);
std::cout << "File opened successfully.\n";
}
// 2. Deterministically release resource in destructor
~SafeFile() {
if (fileStream.is_open()) {
fileStream.close();
std::cout << "File closed deterministically on scope exit!\n";
}
}
void writeLine(const std::string& text) {
fileStream << text << "\n";
}
};
int main() {
{
SafeFile log("audit.log");
log.writeLine("User logged in at 10:00 AM");
} // File is closed automatically right here! No manual close() needed!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
The premier standard library implementation of RAII.
How stack unwinding guarantees destructor calls.
RAII thread lock guards (std::lock_guard).