Resource Acquisition is Initialization
Seen in CS247 - Software Engineering Principles, introduced in Lecture 13.
In C++, when you need to manage resources such as dynamically allocated memory or file handlers, it is often recommended to use the RAII idiom.
RAII is a programming technique that associates resource acquisition with object initialization, ensuring that resources are properly acquired and released in a deterministic and Exception Safe manner.
One way to achieve RAII for managing resources like pointers is by using smart pointers, such as std::unique_ptr
or std::shared_ptr
, which automatically handle resource cleanup.
Here’s an example:
In this example, std::unique_ptr
is used to hold a pointer to a Base
object, which is actually a derived Derived
object. The smart pointer takes ownership of the dynamically allocated object and ensures that it is properly deleted when it goes out of scope, regardless of whether an exception is thrown or not.
Helpful during stack unwinding
The RAII principle ensures that the resource (in this case, the dynamically allocated object) is automatically released when the RAII object (the smart pointer) goes out of scope. This approach helps prevent resource leaks and eliminates the need for manual resource management and explicit memory deallocation.
Similarly, the RAII idiom can also be applied to other resources, such as file handles, by using classes that encapsulate the resource and handle its acquisition and release in their constructors and destructors.
In this example, the ifstream
object file
is an RAII object that automatically opens the file in its constructor and closes it in its destructor when it goes out of scope, ensuring proper resource management.
By utilizing RAII and smart pointers or RAII classes no memory leaks, good exception safe code