Resource Acquisition Is Initialization
|
de:Ressourcenbelegung ist Initialisierung Resource Acquisition Is Initialization (often referred to by the acronym RAII) is a popular programming technique in C++ and D. The technique combines acquisition and release of resources with initialization and uninitialization of variables.
The acquisition is bound to the construction (initialization) whereas the release is bound to the destruction (uninitialization) of the variable. Since a destructor of an automatic variable is called when leaving its scope, it can be guaranteed that the resource is released as soon as the variable's life time ends. This is also true for cases when an exception occurs. Thus, RAII is a key concept for writing exception aware code.
The RAII technique is typically used for controlling thread locks in multi-threaded applications. Another stereotypical example of RAII are file operations, e.g. the C++ standard library's file-streams. An input file stream is opened in the object's constructor, and it is closed upon destruction of the object. Since C++ allows objects to be allocated on the stack, C++'s scoping mechanism can be used to control file access.
Furthermore the ownership of dynamically allocated memory (with new) can be controlled with RAII technique. For this purpose, the C++ Standard Library defines auto_ptr.
External links
- Article "The RAII Programming Idiom (http://www.hackcraft.net/raii/)" by Jon Hanna
- Descriptions from Portland Pattern Repository (http://c2.com/cgi/wiki?InitializationIsResourceAcquisition)
- Sample Chapter "Gotcha #67: Failure to Employ Resource Acquisition Is Initialization (http://awprofessional.com/articles/article.asp?p=30642&seqNum=8)" by Stephen Dewhurst
- Article "A Conversation with Bjarne Stroustrup (http://artima.com/intv/modern3.html)" by Bill Venners
- Article "The Law of The Big Two (http://artima.com/cppsource/bigtwo3.html)" by Bjorn Karlsson and Matthew Wilson
- RAII in C++ (http://jrdodds.blogs.com/blog/2004/08/raii_in_c.html) by Jonathan Dodds
- Article "Implementing the 'Resource Acquisition is Initialization' Idiom (http://gethelp.devx.com/techtips/cpp_pro/10min/2001/november/10min1101.asp)" by Danny Kalev
- Article "RAII (http://sourceforge.net/docman/display_doc.php?docid=8673&group_id=9028)" by Mike Nordell