Tag: RAII, resource management, C++

  • How Does RAII (Resource Acquisition Is Initialization) Manage Resource Lifetimes?

    RAII stands for Resource Acquisition Is Initialization. It manages resource lifetimes by tying resource management to object lifetime. Resources are acquired in the constructor and released in the destructor.

    Example of RAII:

    #include 
    
    class FileManager {
        FILE* file;
    public:
        FileManager(const char* filename) {
            file = fopen(filename, "w");
        }
        ~FileManager() {
            if (file) fclose(file);
        }
    };
    
    int main() {
        FileManager fm("example.txt");
        // File is automatically closed when fm goes out of scope
        return 0;
    }