Resource Acquisition Is Initialization - C++ Example

C++ Example

The following C++ example demonstrates usage of RAII for file access and mutex locking:

#include #include #include #include #include void write_to_file (const std::string & message) { // mutex to protect file access static std::mutex mutex; // lock mutex before accessing file std::lock_guard lock(mutex); // try to open file std::ofstream file("example.txt"); if (!file.is_open) throw std::runtime_error("unable to open file"); // write message to file file << message << std::endl; // file will be closed 1st when leaving scope (regardless of exception) // mutex will be unlocked 2nd (from lock destructor) when leaving // scope (regardless of exception) }

This 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