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:

    A building is akin to dogma; it is insolent, like dogma. Whether or no it is permanent, it claims permanence, like a dogma. People ask why we have no typical architecture of the modern world, like impressionism in painting. Surely it is obviously because we have not enough dogmas; we cannot bear to see anything in the sky that is solid and enduring, anything in the sky that does not change like the clouds of the sky.
    Gilbert Keith Chesterton (1874–1936)

    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)