Less commonly, but more clearly, called Scope-Bound Resource Management (SBRM).
To quote from http://en.cppreference.com/w/cpp/language/raii
"Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object."
So?
Binding the resource to the lifetime of the object before use means that the resources are tidied up when they go out of scope.
The resource is freed up correctly when the object is destroyed.
Memory leaks were probably the earlier instance we looked at in wanting to make sure we appropriately tidy up.
See https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e6-use-raii-to-prevent-leaks
RAII can be summarized as follows:
encapsulate each resource into a class, where
The constructor acquires the resource and establishes all class invariants or throws an exception if that cannot be done,
The destructor releases the resource and never throws exceptions;
always use the resource via an instance of a RAII-class that either
has automatic storage duration or temporary lifetime itself, or
has a lifetime that is bounded by the lifetime of an automatic or temporary object.
The idea of using the resource via a RAII-class is bundled up with the idea of resource ownership.
We expect that if object A owns object B, object A managing the lifetime of object B and a user of object A shouldn’t be able to directly manage B by making calls like delete B, fclose(B) ...
Standard container classes will be RAII compliant.
Note though that iterators, or pairs of iterators defining a range, don’t own the data elements they reference.
This example is also from http://en.cppreference.com/w/cpp/language/raii. A mutex, short for a mutual exclusion object, is created to make sure that when multiple threads of a program need to access the same resource, such as a file, they don’t do so at the same time.
Mutexs are used to deal with concurrency problems.
std::mutex m;
void bad()
{
m.lock(); // acquire the mutex
f(); // if f() throws an exception, the mutex is never released
if(!everything_ok()) return; // early return, the mutex is never released
m.unlock(); // if bad() reaches this statement, the mutex is released
}
void good()
{
std::lock_guard<std::mutex> lk(m); // RAII class: mutex acquisition is initialization
f(); // if f() throws an exception, the mutex is released
if(!everything_ok()) return; // early return, the mutex is released
} // if good() returns normally, the mutex is released
On Resource Acquisition is Initialization Some comments from Bjarne Stroustrup. https://www.artima.com/intv/modern3.html