C++ Example
The following C++ example demonstrates usage of RAII for file access and mutex locking:
#includeThis code is exception-safe because C++ guarantees that all stack objects are destroyed at the end of the enclosing scope. The destructor of both the lock and file objects are therefore guaranteed to be called when returning from the function, whether an exception has been thrown or not.
Local variables allow easy management of multiple resources within a single function: they are destroyed in the reverse order of their construction, and an object is only destroyed if fully constructed—that is, if no exception propagates from its constructor.
Using RAII greatly simplifies resource management, reduces overall code size and helps ensure program correctness. RAII is therefore highly recommended in C++, and most of the C++ standard library follows the idiom.
Read more about this topic: Resource Acquisition Is Initialization