Sobes.tech
Junior — Middle

Can you explain the principle of automatic resource management using RAII?

sobes.tech AI

Answer from AI

RAII (Resource Acquisition Is Initialization) is an idiom in C++ that ties the lifetime of a resource to the lifetime of an object. The idea is that a resource (such as memory, a file, a mutex) is acquired in the object's constructor and released in its destructor.

This allows for automatic resource management: when the object goes out of scope, its destructor is called automatically, and the resource is released, preventing leaks.

Example:

#include <fstream>

void example() {
    std::ifstream file("data.txt"); // file is opened in the constructor
    if (!file) {
        // error handling
    }
    // work with the file
} // when exiting the function, the file is automatically closed in the ifstream destructor

Thus, RAII provides safe and convenient resource management without the need to explicitly call release functions.