The loan pattern
C++ programmers chant a mantra—Resource Acquisition Is Initialization (RAII). The constructor of an object acquires a finite resource (for example, files, heap memory, db connection, mutex locks), and the destructor, frees them.
Note
RAII is a resource-management technique. No matter how a control flow returns, a control flow returns the destructor that is guaranteed to be invoked. A method/function could exit its scope via an earlier return or due to an exception thrown.
In C++, an object's lifetime is bound by its scope. When a scope is entered, the object is created, that is, its constructor is invoked. In the constructor invocation, we acquire the resource. When the scope is finally exited either via an early return or due to an exception, the object destructor is invoked. In the destructor code, we can release the resource.
For more information on RAII, refer to https://www.hackcraft.net/raii/.
One famous use of this technique is the auto_ptr
template and its friends, such...