tags:

views:

144

answers:

1

What is meant by Resource Acquisition is Initialization (RAiI)? www.technical-interview.com

+12  A: 

This is a programming idiom which briefly means that you

  • encapsulate a resource into a class (such that its constructor acquires the resource and its destructor releases it)
  • acquire the resource by creating a local instance of the class*
  • the resource is automatically freed when the object gets out of scope

This guarantees that whatever happens while the resource is in use, it will eventually get freed (whether due to normal return, destruction of the containing object, or an exception thrown).

It is a widely used good practice in C++, because apart from being a safe way to deal with resources, it also makes your code much cleaner as you don't need to mix error handling code with the main functionality.

* Update: "local" may mean a local variable, or a nonstatic member variable of a class. In the latter case the member variable is initialized and destroyed with its owner object.

Péter Török
AFAIK, the acronym doesn't imply the object has to be on a local (stack) variable. It could be a member variable of another object, so when the 'holding' object is destroyed, the member object is destroyed too, and the resource is released. In fact, i think the acronym specifically means only that there's no `open()`/`close()` methods to initialize and release the resource, just the constructor and destructor, so the 'holding' of the resource is just the lifetime of the object, no matter if that lifetime is handled by the context (stack) or explicitly (dynamic alloc)
Javier
@Javier I implicitly refer to this by mentioning "destruction of the containing object", but you are right, I made it clearer now.
Péter Török