Typical Uses
The RAII technique is often used for controlling mutex locks in multi-threaded applications. In that use, the object releases the lock when destroyed. Without RAII in this scenario the potential for deadlock would be high and the logic to lock the mutex would be far from the logic to unlock it. With RAII, the code that locks the mutex essentially includes the logic that the lock will be released when the RAII object goes out of scope.
Another typical example is interacting with files: We could have an object that represents a file that is open for writing, wherein the file is opened in the constructor and closed when the object goes out of scope. In both cases, RAII only ensures that the resource in question is released appropriately; care must still be taken to maintain exception safety. If the code modifying the data structure or file is not exception-safe, the mutex could be unlocked or the file closed with the data structure or file corrupted.
Ownership of dynamically allocated objects (memory allocated with new in C++) can also be controlled with RAII, such that the object is released when the RAII object is destroyed. For this purpose, the C++11 standard library defines the smart pointer classes std::unique_ptr
for single-owned objects and std::shared_ptr
for objects with shared ownership. Similar classes are also available through std::auto_ptr
in C++98, and boost::shared_ptr
in the Boost libraries.
Read more about this topic: Resource Acquisition Is Initialization
Famous quotes containing the word typical:
“New York is the meeting place of the peoples, the only city where you can hardly find a typical American.”
—Djuna Barnes (18921982)
“It is not however, adulthood itself, but parenthood that forms the glass shroud of memory. For there is an interesting quirk in the memory of women. At 30, women see their adolescence quite clearly. At 30 a womans adolescence remains a facet fitting into her current self.... At 40, however, memories of adolescence are blurred. Women of this age look much more to their earlier childhood for memories of themselves and of their mothers. This links up to her typical parenting phase.”
—Terri Apter (20th century)