Imagine opening a file in C++, reading its contents, and then returning from a function.
You remember to close the file.
Great!
But what happens if an error occurs halfway through the function? What if an exception is thrown? What if someone adds an early return later?
Suddenly, that cleanup code might never run.
This is one of the reasons C++ has a powerful programming technique called RAII .
What is RAII?
RAII stands for Resource Acquisition Is Initialization .
The basic idea is simple:
Connect the lifetime of a resource to the lifetime of an object.
When an object is constructed, it acquires or takes ownership of a resource.
When that object is destroyed, it releases the resource.
In C++, this works especially well because objects with automatic storage duration are destroyed when their scope ends.
Resources can include:
Dynamically allocated memory.
Files.
Mutex locks.
Network connections.
Operating-system handles.
Other objects that require cleanup.
The problem with manual…