-
Book Overview & Buying
-
Table Of Contents
Software Architecture with C++ - Second Edition
By :
RAII (resource acquisition is initialization) is a crucial idiom popularized by C++ creator Bjarne Stroustrup. It uses stack-based objects, constructors, and destructors to manage all resources, including heap memory, sockets, files, mutexes, disk space, and network connections.
When a class object is declared on the stack, it is initialized by calling its constructor, which captures the resource or throws an exception if an error occurs. When the object goes out of scope, it is popped off the stack, but not before the object’s destructor is called to release the captured resource.
This code shows an RAII wrapper class that allocates dynamic memory for an array in its constructor and releases the memory in its destructor:
template <typename T>
class Array final {
public:
explicit Array(std::size_t size) : sz_{size}, data_{new T[size]} {
std::cout << "Resource acquired\n";
}
Array(std::initializer_list<T> list...