most fundamental C++ idiom: RAII (Resource Acquisition Is Initialization) โ€” a cornerstone of safe memory and resource management in modern C++.


๐Ÿ’ก What is RAII?

RAII (Resource Acquisition Is Initialization) is a C++ programming idiom where resource allocation (like memory, file handles, sockets, locks, etc.) is tied to the lifetime of an object. When the object is created, the resource is acquired. When the object is destroyed, the resource is released.

Key Idea


๐Ÿ” Why is RAII Useful?


๐Ÿง  Python Correlation

Python has a rough equivalent in context managers (with statements).

Example:

with open("file.txt") as f:
    data = f.read()
# file is automatically closed

This is like RAII: open the resource in a defined scope and auto-clean it when done.


๐Ÿงช C++ Example: RAII with File Handling

#include <iostream>
#include <fstream>

class FileWrapper {
    std::ofstream file;

public:
    FileWrapper(const std::string& filename) {
        file.open(filename);
        if (!file.is_open()) {
            throw std::runtime_error("Failed to open file");
        }
        std::cout << "File opened\\n";
    }

    void write(const std::string& data) {
        file << data;
    }

    ~FileWrapper() {
        if (file.is_open()) {
            file.close();
            std::cout << "File closed\\n";
        }
    }
};

int main() {
    try {
        FileWrapper fw("output.txt");
        fw.write("Hello, RAII!");
    } catch (const std::exception& ex) {
        std::cerr << "Exception: " << ex.what() << "\\n";
    }

    return 0;
}