Resource Acquisition Is Initialization (RAII)


Resource Acquisition Is Initialization, often referred to by the acronym RAII, is a popular design pattern in several object oriented programming languages like C++, D and Ada. The technique, invented by Bjarne Stroustrup[1], ensures that when resources are acquired they are properly released by tying them to the lifespan of suitable objects: resources are acquired during the initialization of objects, when there is no chance of using them before the resource is available, and released with the destruction of the same objects, which is guaranteed to take place even in case of errors.

In C++, objects residing on the stack are automatically destroyed when the enclosing scope is exited, including the case of exceptions [2]; their destructor is called before the exception propagates.

RAII helps in writing exception-safe code: to release resources before permitting exceptions to propagate (in order to avoid resource leaks) one can write appropriate destructors once rather than dispersing and duplicating cleanup logic between exception handling blocks.

object releases the lock, if held, when destroyed
file class closes the associated file, if open, when destroyed
the memory is released when the RAII object is destroyed

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License