RAII in C++: Ensuring Safe Vulkan Resource Management¶
RAII (resource acquisition is initialization) is a programming idiom what was invented by Bjarne Stroustrup, the creator of C++. The basic idea is to use object oriented programming with classes to ensure resource safety. This works by creating an object in the constructor of a class, and doing the cleanup for this object in the destructor of the class. The constructor either fails by throwing an exception, or it leaves behind a valid object. Scott Meyers sometimes calls this type of resource safety mechanism “correct by construction”. It’s important to note that C++ does not have a garbage collector, because it has something that is far more powerful: destructors. According to Scott Meyers, destructors are arguably the most important feature of C++, because they resemble a general-purpose cleanup mechanism. Garbage collection on the other hand only deals with memory. For the rest of the resources, we do not have a cleanup from the garbage collector. The use of RAII is the fundamental idea of this project behind our abstraction of Vulkan API. If you want to see an easy example, check out the wrapper code for VkInstance or VkDevice. Once we introduced RAII into our code base, all resource leak problems solved themselves!