Resource Acquisition Is Initialization - Typical Uses

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:

    Consciousness is cerebral celebrity—nothing more and nothing less. Those contents are conscious that persevere, that monopolize resources long enough to achieve certain typical and “symptomatic” effects—on memory, on the control of behavior and so forth.
    Daniel Clement Dennett (b. 1942)

    The books may say that nine-month-olds crawl, say their first words, and are afraid of strangers. Your exuberantly concrete and special nine-month-old hasn’t read them. She may be walking already, not saying a word and smiling gleefully at every stranger she sees. . . . You can support her best by helping her learn what she’s trying to learn, not what the books say a typical child ought to be learning.
    Amy Laura Dombro (20th century)