Resource Acquisition Is Initialization (RAII)
It is a C++ design pattern where a resource is acquired when an object
is created (constructor), and the resource is released automatically
when the object is destroyed(destructor). ie tie resource to object
lifetime
Used in: Smart pointer(std::unique_ptr and
std::lock_guard), lock_guard are RAII based
Benefits:It helps prevent memory leaks, dangling pointers, and
unreleased file handles.
Example
#include <iostream>
class FileHandle {
public:
FileHandle(const char* name) {
file = fopen(name, "w");
if (!file) {
throw std::runtime_error("Could not open file");
}
std::cout << "File opened\n";
}
~FileHandle() {
if (file) {
fclose(file);
std::cout << "File closed automatically\n";
}
}
void write(const char* text) {
if (file) {
fputs(text, file);
}
}
private:
FILE* file;
};
int main() {
FileHandle logFile("demo.txt");
logFile.write("Hello from RAII!\n");
return 0;
} // destructor runs automatically here