RAII Idiom

Get an overview of resource acquisition in initialization (RAII).

We'll cover the following

Overview

Programming languages can be divided into two types:

  • Managed, in which we have automatic memory management and garbage collection. Java is an example of a managed language.
  • Unmanaged, in which we don’t have automatic memory management and garbage collection. C/C++ is an example of an unmanaged language.

In unmanaged languages, whenever the program acquires memory from the operating system, the program should manually release these resources. For example, in our C++ program, we might allocate some memory for an array at runtime and hold its pointer in a local variable. We might forget to release the dynamically allocated memory portion before the variable holding the pointer goes out of scope. In such a case, the allocated memory isn’t marked as free by the operating system and isn’t available for use by other programs. This is called a memory leak.

RAII stands for resource acquisition is initialization and is a programming idiom specifically used to handle the situation described above. In RAII, the object that holds a resource release is in its destructor. The destructor of an object always runs when the object goes out of scope.

This technique is known as constructor acquires, destructor releases (CADRe). It’s not mandatory to allocate the resources in the constructor in this idiom, although that is one option.

Get hands-on with 1200+ tech skills courses.