RAII (Resource Acquisition Is Initialization)

🔴 Advanced

📖 Definition

RAII is C++'s core memory management idiom: encapsulate resources (heap memory, file handles, mutex locks) inside stack-allocated wrapper objects whose constructor acquires the resource and destructor automatically releases it upon scope exit (even during exception unwinding).

💡 Code Example

#include <iostream>
#include <fstream>

void writeLog() {
    std::ofstream file("log.txt"); // RAII opens file
    file << "Log entry line\n";
} // RAII automatically flushes and closes file here

int main() {
    writeLog();
    std::cout << "File safely written and closed via RAII destructor.\n";
    return 0;
}