More C++ Idioms/Scope Guard

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Scope Guard
[edit | edit source]

Intent[edit | edit source]

  • To ensure that resources are always released in face of an exception but not while returning normally
  • To provide basic exception safety guarantee

Also Known As[edit | edit source]

Motivation[edit | edit source]

Resource Acquisition is Initialization (RAII) idiom allows us to acquire resources in the constructor and release them in the destructor when scope ends successfully or due to an exception. It will always release resources. This is not very flexible. Sometime we don't want to release resources if no exception is thrown but we do want to release them if an exception is thrown.

Solution and Sample Code[edit | edit source]

Enhance the typical implementation of the Resource Acquisition is Initialization (RAII) idiom with a conditional check.

class ScopeGuard
{
public:
  ScopeGuard () 
   : engaged_ (true) 
  { /* Acquire resources here. */ }
  
  ~ScopeGuard ()  
  { 
    if (engaged_) 
     { /* Release resources here. */} 
  }
  void release () 
  { 
     engaged_ = false; 
     /* Resources will no longer be released */ 
  }
private:
  bool engaged_;
};
void some_init_function ()
{
  ScopeGuard guard;
  // ...... Something may throw here. If it does we release resources.
  guard.release (); // Resources will not be released in normal execution.
}

Known Uses[edit | edit source]

  • boost::mutex::scoped_lock
  • boost::scoped_ptr
  • std::auto_ptr
  • ACE_Guard
  • ACE_Read_Guard
  • ACE_Write_Guard
  • ACE_Auto_Ptr
  • ACE_Auto_Array_Ptr

Related Idioms[edit | edit source]

References[edit | edit source]