What is RAII?
This chapter is all about resource management. A resource can be a piece of memory, an opened file, or a network socket. Although in this chapter we have only used memory management as examples, the principles for all resources are the same.
Of course, all acquired resources need to be released. In C++, the destructor is a good place to release resources. When working with Lua, the Lua finalizer is a good trigger to release resources.
Resource Acquisition is Initialization, or RAII, is a useful resource management idiom. This means object creation and acquiring the resources the object needs should be an atomic operation – everything should succeed, or the partially acquired resources should be released before raising an error.
By using this technique, the resources are also linked with the object’s life cycle. This ensures that all resources are guaranteed to be available during the life cycle of the object. This will prevent complex failure scenarios...