Skip navigation.

Tip: Scoped resource in C++

In two interesting articles, Kevlin Henney describes C++’s idiomatic approach to exception-safe acquisition and
release of resources, such as memory and file handles.

The articles present the implementation of a scoped class template. Using class scoped looks like so.

source file
   nonstd::scoped< type * > ptr( new type );

   // use ptr, exceptions possible

   // ptr goes out of scope, object allocated is deleted.

The action to perform when the scoped object goes out of scope is not limited to a delete operation, but it can be specfied by the second template parameter destructor_type. For example.

source file
struct file_closer
   void operator()( FILE *to_close )
      fclose( to_close );

   nonstd::scoped< FILE *, file_closer > file( std::fopen( filename, mode ) );

   // use file, exceptions possible
   . . .
   // file goes out of scope, file is closed.

The code of the scoped class template is not available in a form suitable for compiler consumption, so I created a small package with the source code.

download the package: scoped-20070301.tar.gz (62 kByte)

You may also want to read the following articles:

Kevlin's site contains many more good reads, so don't waste your time here, go there now!