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 ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.