RAII (Resource Acquisition Is Initialization) is a programming technique used in C++ to manage resources automatically. It is a way to ensure that resources are properly acquired and released within the scope of an object's lifetime.
The basic idea behind RAII is that the acquisition of a resource is tied to the initialization of an object, and the release of the resource is tied to the destruction of that object. By encapsulating resource acquisition and release within an object's constructor and destructor, we can ensure that the resource is always properly managed, even in the presence of exceptions or early returns.
- Dynamic memory allocation:
// Using std::unique_ptr or std::shared_ptr to manage dynamically allocated memory:
std::unique_ptr<MyClass> uptr(new MyClass());
std::shared_ptr<MyClass> sptr(new MyClass());
// Use the object through the pointer
// When the unique_ptr/shared_ptr goes out of scope, the pointed-to object is automatically deleted.
- File handling
// Using std::ifstream and std::ofstream to open and close files
{
std::ifstream file("input.txt");
// Use the file
}
// File is automatically closed when the file object goes out of scope
- Mutex and Locks
// Using std::lock_guard or std::unique_lock to acquire and release mutexes:
{
std::lock_guard<std::mutex> lock(my_mutex);
// Critical section
}
// Mutex is automatically released when the lock_guard goes out of scope
- stl containers(vector, list, map)
- smart pointers(shared_ptr, unique_ptr, weak_ptr)