Skip to main content

Command Palette

Search for a command to run...

RAII and Its Advantages

Updated
2 min read
T

Hey there! I am a Software Developer who is passionate about data structures, algorithms and application development with C/C++.

What is RAII?

RAII (Resource Acquisition Is Initialization) is a common pattern in C++ for writing classes that manage resources.

What does this pattern look like?

  1. The resource is stored as a private member of the class.
  2. Then, the class constructor takes ownership of the resource.
  3. Then, the classes public member function controls access to the resource.
  4. Finally, the class destructor releases the resource when it is no longer being used.

Advantages of RAII

  • Obtaining access to the resource is straight forward and deterministic. Either the instance is successfully created or the resource is not usable.
  • The instance will use move constructors and move assignments to correctly transfer ownership of the resource.
  • You don't have to worry about the complex implementation of managing that resource through encapsulation.
  • It also provides exception safety in your code.
  • It is used to implement many classes in the standard library, such as strings, vectors and fstream.

More from this blog

Tomislav Kraljic's Blog

24 posts