Jump to content

More C++ Idioms/Resource Acquisition Is Initialization

From Wikibooks, open books for an open world

Resource Acquisition Is Initialization

[edit | edit source]

Intent

[edit | edit source]
  • To guarantee release of resource(s) at the end of a scope
  • To provide basic exception safety guarantee

Also Known As

[edit | edit source]
  • Execute-Around Object
  • Resource Release Is Finalization
  • Scope-Bound Resource Management

Motivation

[edit | edit source]

Resources acquired in a function scope should be released before leaving the scope unless the ownership is being transferred to another scope or object. Quite often it means a pair of function calls - one to acquire a resource and another one to release it. For example, new/delete, malloc/free, acquire/release, file-open/file-close, nested_count++/nested_count--, etc. It is quite easy to forget to write the "release" part of the resource management "contract". Sometimes the resource release function is never invoked: this can happen when the control flow leaves the scope because of return or an exception. It is too dangerous to trust the programmer that he or she will invoke resource release operation in all possible cases in the present and in the future. Some examples are given below.

void foo ()
{
  char * ch = new char [100];
  if (...)
     if (...)
        return;
     else if (...)
            if (...)
  else
     throw "ERROR";

  delete [] ch; // This may not be invoked... memory leak!
}
void bar ()
{
  lock.acquire();
  if (...)
     if (...)
        return;
  else
     throw "ERROR";

  lock.release(); // This may not be invoked... deadlock!
}

This is a general control flow abstraction problem. Resource Acquisition is Initialization (RAII) is an extremely popular idiom in C++ that relieves the burden of calling "resource release" operation in a clever way.

Solution and Sample Code

[edit | edit source]

The idea is to wrap the resource release operation in a destructor of an object in the scope. The language guarantees that the destructor will always be invoked (of a successfully constructed object) when control flow leaves the scope because of a return statement or an exception.

//  Private copy constructor and copy assignment ensure classes derived 
//  from class NonCopyable cannot be copied.
class NonCopyable 
{
   NonCopyable (NonCopyable const &); // private copy constructor
   NonCopyable & operator = (NonCopyable const &); // private assignment operator
};
template <class T>
class AutoDelete : NonCopyable
{
  public:
    AutoDelete (T * p = 0) : ptr_(p) {}
    ~AutoDelete () throw() { delete ptr_; } 
  private:
    T *ptr_;
};

class ScopedLock : NonCopyable// Scoped Lock idiom
{
  public:
    ScopedLock (Lock & l) : lock_(l) { lock_.acquire(); }
    ~ScopedLock () throw () { lock_.release(); } 
  private:
    Lock& lock_;
};

void foo ()
{
  X * p = new X;
  // C++ guarantees that the destructors of objects on the stack will be called, even if an exception is thrown.
  AutoDelete<X> safe_del(p); // destruction of safe_del will be called and lock will be released when it goes out of function foo scope

  if (...)
    if (...)
      return; 
 
  // No need to call delete here.
  // Destructor of safe_del will delete memory
}
void X::bar()
{
  ScopedLock safe_lock(l); // Lock will be released certainly
  if (...)
    if (...)
      throw "ERROR"; 
  // No need to call release here.
  // Destructor of safe_lock will release the lock
}

Acquiring resource(s) in constructor is not mandatory in RAII idiom but releasing resources in the destructor is the key. Therefore, it is also known (rarely though) as Resource Release is Finalization idiom. It is important in this idiom that the destructor should not throw exceptions. Therefore, the destructors have no-throw specification but it is optional. std::auto_ptr and boost::scoped_ptr are ways of quickly using RAII idiom for memory resources. RAII is also used to ensure exception safety. RAII makes it possible to avoid resource leaks without extensive use of try/catch blocks and is widely used in the software industry.

Many classes that manage resources using RAII, do not have legitimate copy semantics (e.g., network connections, database cursors, mutex). The NonCopyable class shown before prevents copying of objects that implement RAII. It simply prevents access to the copy-constructor and the copy-assignment operator by making them private. boost::scoped_ptr is an example of one such class that prevents copying while holding memory resources. The NonCopyable class states this intention explicitly and prevents compilation if used incorrectly. Such classes should not be used in STL containers. However, every resource management class that implements RAII does not have to be non-copyable like the above two examples. If copy semantics are desired, boost::shared_ptr can be used to manage memory resources. In general, non-intrusive reference counting is used to provide copy semantics as well as RAII.

Consequences

[edit | edit source]

RAII is not without its limitations. The resources which are not memory and must be released deterministically and may throw exceptions usually aren't handled very well by C++ destructors. That's because a C++ destructor can't propagate errors to the enclosing scope (which is potentially winding up). It has no return value and it should not propagate exceptions outside itself. If exceptions are possible, then the destructor must handle the exceptional case within itself somehow. Nevertheless, RAII remains the most widely used resource management idiom in C++.

Known Uses

[edit | edit source]
  • Virtually all non-trivial C++ software
  • std::unique_ptr (and std::auto_ptr)
  • std::shared_ptr
  • boost::mutex::scoped_lock
[edit | edit source]

References

[edit | edit source]