More C++ Idioms/Scope Guard

< More C++ Idioms

Scope Guard

Intent

Motivation

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 exception is thrown.

Solution and Sample Code

Enhance the typical implementation of 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 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

Related Idioms

References

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.