All Topics  
Resource Acquisition Is Initialization

 

   Email Print
   Bookmark   Link






 

Resource Acquisition Is Initialization



 
 
Resource Acquisition Is Initialization, often referred to by the acronym RAII, is a popular design pattern
Design pattern (computer science)

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code ....
 in several object oriented programming languages
Object-oriented programming language

An object-oriented programming language is one that allows or encourages, to some degree, object-oriented programming techniques such as Information hiding, Inheritance , module , and Polymorphism ....
 like C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
, D
D (programming language)

The D programming language, also known simply as D, is an Object-oriented programming, Imperative programming, Multi-paradigm programming language system programming language by Walter Bright of Digital Mars....
 and Ada
Ada (programming language)

Ada is a structured programming, statically typed, Imperative programming, and Object-oriented programming high-level language computer programming programming language, extended from Pascal and other languages....
. The technique, invented by Bjarne Stroustrup
Bjarne Stroustrup

Bjarne Stroustrup is a computer scientist at the College of Engineering Chair Professor of Computer Science at Texas A&M University. He is most notable for developing the C++ programming language....
, 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
Stack (data structure)

In computer science, a stack is an abstract data type and data structure based on the principle of LIFO . Stacks are used extensively at every level of a modern computer system....
 are automatically destroyed when the enclosing scope
Scope (programming)

In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes....
 is exited, including the case of exception
Exception handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions - special conditions that change the normal flow of execution....
s ; 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.

lass="link1" onMouseover='showByLink("m2309233",this)' onMouseout='hide("m2309233")'href="http://www.absoluteastronomy.com/topics/C%2b%2b">C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
 and D allow objects to be allocated on the stack
Call stack

In computer science, a call stack is a dynamic Stack data structure that stores information about the active subroutines of a computer program....
 and their scoping rules ensure that destructors are called when a local object's scope ends.






Discussion
Ask a question about 'Resource Acquisition Is Initialization'
Start a new discussion about 'Resource Acquisition Is Initialization'
Answer questions from other users
Full Discussion Forum



Encyclopedia


Resource Acquisition Is Initialization, often referred to by the acronym RAII, is a popular design pattern
Design pattern (computer science)

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code ....
 in several object oriented programming languages
Object-oriented programming language

An object-oriented programming language is one that allows or encourages, to some degree, object-oriented programming techniques such as Information hiding, Inheritance , module , and Polymorphism ....
 like C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
, D
D (programming language)

The D programming language, also known simply as D, is an Object-oriented programming, Imperative programming, Multi-paradigm programming language system programming language by Walter Bright of Digital Mars....
 and Ada
Ada (programming language)

Ada is a structured programming, statically typed, Imperative programming, and Object-oriented programming high-level language computer programming programming language, extended from Pascal and other languages....
. The technique, invented by Bjarne Stroustrup
Bjarne Stroustrup

Bjarne Stroustrup is a computer scientist at the College of Engineering Chair Professor of Computer Science at Texas A&M University. He is most notable for developing the C++ programming language....
, 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
Stack (data structure)

In computer science, a stack is an abstract data type and data structure based on the principle of LIFO . Stacks are used extensively at every level of a modern computer system....
 are automatically destroyed when the enclosing scope
Scope (programming)

In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes....
 is exited, including the case of exception
Exception handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions - special conditions that change the normal flow of execution....
s ; 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.

Language Support

C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
 and D allow objects to be allocated on the stack
Call stack

In computer science, a call stack is a dynamic Stack data structure that stores information about the active subroutines of a computer program....
 and their scoping rules ensure that destructors are called when a local object's scope ends. By putting the resource release logic in the destructor, C++'s and D's scoping provide direct support for RAII.

Typical uses


The RAII technique is often used for controlling thread locks in multi-threaded applications. In that use, the object releases the lock, if held, when destroyed. Another typical example is file management, wherein the file class closes the associated file, if open, when destroyed.

The ownership of dynamically allocated memory (such as memory allocated with new in C++ code) can be controlled with RAII, such that the memory is released when the RAII object is destroyed. For this purpose, the C++ Standard Library defines the smart pointer
Smart pointer

In computer science, a smart pointer is an abstract data type that simulates a pointer while providing additional features, such as garbage collection or bounds checking....
 class stdauto_ptr
Auto ptr

auto_ptr is a class Template available in the C++ C++ standard library that provides some basic Resource Acquisition Is Initialization features for Pointer #C_and_C.2B.2B ....
. Furthermore, smart pointer with shared-ownership semantics such as boostshared_ptr (defined in C++ by Boost
Boost library

The Boost C++ Libraries are a collection of peer-reviewed, open source Library that extend the functionality of C++. Most of the libraries are licensed under the Boost Software License, designed to allow Boost to be used with both open and closed source projects....
 and marked for inclusion in the new C++0x
C++0x

C++0x is the planned new Open standard for the C++. It is intended to replace the existing C++ standard, ISO/IEC 14882, which was published in 1998 and updated in 2003....
 standard), or policy based smart pointers such as LokiSmartPtr (from Loki
Loki (C++)

Loki is the name of a C++ Library written by Andrei Alexandrescu as part of his book Modern C++ Design.The library makes extensive use of C++ template metaprogramming and implements several commonly used tools: typelist, Function_object, Singleton pattern, smart pointer, Factory object, Visitor pattern and Multiple dispatch....
), can also be used to manage lifetime of shared objects.

Mutability (C++)

In C++, an important consideration of classes that implement RAII is their mutability. A class exhibiting mutable RAII provides facilities for instances to be assigned a new resource; one that exhibits immutable RAII does not. An example of the former is stdauto_ptr
Auto ptr

auto_ptr is a class Template available in the C++ C++ standard library that provides some basic Resource Acquisition Is Initialization features for Pointer #C_and_C.2B.2B ....
; examples of the latter are the STLSoft library's stlsoftscoped_handle and Boost.SmartPtr
Boost

Boost can refer to:...
's boostscoped_ptr.

Classes exhibiting immutable RAII are considerably easier to implement in C++, since the design need not account for assignment (including copy-assignment), except to explicitly prohibit it. Consider the following RAII class template that illustrates the simplicity of implementing immutable RAII. Compare this with the implementation of stdauto_ptr
Auto ptr

auto_ptr is a class Template available in the C++ C++ standard library that provides some basic Resource Acquisition Is Initialization features for Pointer #C_and_C.2B.2B ....
 or another mutable RAII smart pointer, which will have many more member functions and logic to handle premature release in cases of self-assignment.

template class immutable_scoped_ptr ;

C++ example

The following RAII class is a lightweight wrapper of the C standard library
C standard library

The C standard library consists of a set of sections of the ISO C standard which describe a collection of header files and library routines used to implement common operations, such as input/output and character string handling, in the C ....
 file system calls.
  1. include
  2. include // stdruntime_error
class file ;

Class file can then be used as follows: void example_usage



This works because the class file encapsulates the management of the FILE* file handle. When objects file are local to a function, C++ guarantees that they are destroyed at the end of the enclosing scope (the function in the example), and the file destructor releases the file by calling stdfclose(file_). Furthermore, file instances guarantee that a file is available by throwing an exception if the file could not be opened when creating the object.

Local variables easily manage multiple resources within a single function: They are destroyed in the reverse order of their construction, and an object is only destroyed if fully constructed. That is, if no exception propagates from its constructor.

Using RAII-enabled resources simplifies and reduces overall code size and helps ensure program correctness.

Resource management without RAII


In Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
, objects are not allocated on the stack and must be accessed through references; hence you cannot have automatic variables of objects that "go out of scope." Instead, all objects are dynamically allocated
Dynamic memory allocation

In computer science, dynamic memory allocation is the allocation of computer storage storage for use in a computer program during the runtime of that program....
. In principle, dynamic allocation does not make RAII unfeasible per se; it could still be feasible if there were a guarantee that a "destructor" ("finalize") method would be called as soon as an object were pointed to by no references (i.e., if the object lifetime management were performed according to reference counting
Reference counting

In computer science, reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object or block of memory....
).

However, Java objects have indefinite lifetimes which cannot be controlled by the programmer, because, according to the Java Virtual Machine
Java Virtual Machine

A Java Virtual Machine is a set of computer software programs and data structures which use a virtual machine model for the execution of other computer programs and Scripting language....
 specification, it is unpredictable when the garbage collector
Garbage collection (computer science)

In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage , or memory used by Object that will never be accessed or mutated again by the Application software....
 will act. Indeed, the garbage collector may even never act at all to collect objects pointed to by no references. Hence the "finalize" method of an unreferenced object might be never called or called only long after the object became unreferenced. Resources must thus be closed manually by the programmer.

The preceding example would be written like this:

void java_example The burden of releasing resources falls on the programmer each time a resource is used.

Ruby
Ruby (programming language)

Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
 and Smalltalk
Smalltalk

Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al...
 do not support RAII, but have a simpler and more flexible pattern that makes use of methods that pass resources to closure blocks. Here is an example in Ruby:

File.open("logfile.txt", "w+") do |logfile| logfile.write("hello logfile!") end The open method ensures that the file handle is closed without special precautions by the code writing to the file. This is similar to Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
's -based macros.

Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
's and the 'using' statement in C# and Visual Basic 2005
Visual Basic .NET

Visual Basic , formerly called Visual Basic .NET , is an object-oriented programming computer language that can be viewed as an evolution of Microsoft Visual Basic implemented on the .NET Framework....
 provide deterministic resource management within a block and do away with the requirement for explicit finally-based cleanup and release.

Perl manages object lifetime by reference counting, making it possible to use RAII in a limited form. Objects that are no longer referenced are immediately released, so a destructor can release the resource at that time. However, object lifetime isn't necessarily bound to any lexical scope. One can store a reference to an object in a global variable, for example, thus keeping the object (and resource) alive indeterminately long. This makes it possible to accidentally leak resources that should have been released at the end of some scope.

C
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
 requires significant administrative code since it doesn't support exceptions, try-finally blocks or RAII of any kind. A typical approach is to separate releasing of resources at the end of the function and jump there with gotos in the case of error. This way the cleanup code need not be duplicated.

int c_example Variations exist, but the example illustrates the general approach.

External links


  • Article "" by Wikipedia editor Jon Hanna (Talliesin)
  • Wiki from the Portland Pattern Repository
  • Sample Chapter "" by Stephen Dewhurst
  • Interview "" by Bill Venners
  • Article "" by Bjorn Karlsson and Matthew Wilson
  • Blog Entry "" by Jonathan Dodds
  • Article "" by Danny Kalev
  • Article "" by Mike Nordell
  • Article "" by Roland Pibinger
  • Article "" by Tom Cargill
  • Blog ""
  • Blog Entry ""
  • Article "" by Julio M. Merino Vidal
  • Blog Entry "" by Michael Feathers