Introduction - RAII
RAII (Resource Acquisition is Initialization) is a programming concept in C++. We're going to describe it very simply:
Problem: Memory leaks occur when heap allocated (new keyword) variables/objects don't get deleted because of unexpected problems. For example...
The above code has a memory leak, because a resource is initialized, but is never deleted. This is where RAII comes in...
Solution: Encapsulate variables in classes, and design the destructors to deallocate the resource from memory when the object itself is deleted.
The reason this works is because the object will have it's destructor called when it's scope ends (for example, when the throw happens).
The best way to make this happen is with smart pointers. There are a few types, but we'll look at two in this blog post.
Unique pointers are a good RAII technique for objects you only want to have one pointer too. (Meaning, only one pointer is allowed access to the variable/object.)
The output of the above code (compiled with c++14) is:
Shared Pointer is the same as unique pointers, except there can be multiple pointers to one variable/object.
The code will output the following:
RAII is an important C++ technique, where the code is designed so that even unexpected code breaking will assure that objects are cleaned up and memory leaks don't occur. We've seen how Smart Pointers, such as unique pointer and shared pointer, allow us to automatically handle RAII, but RAII is a design principle that can be applied to even our custom classes where any type of resource that we're responsible for needs to be designed carefully.
To explain it simply: Put a resource in the constructor of a class. Clean up that resource in the destructor of that class. And use a smart pointer to handle using that class. EZ.
Like this content and want more? Feel free to look around and find another blog post that interests you. You can also contact me through one of the various social media channels.
Hi, I'm srcmake. I play video games and develop software.
Pro-tip: Click the "DIRECTORY" button in the menu to find a list of blog posts.
License: All code and instructions are provided under the MIT License.