C++11 scope exit guard, a good idea?

But is it a good idea?

Sure. A related topic is the RAII paradigm.

Or are there potential problems I have missed?

You don't handle exceptions.

Is there already a similar solution (with C++0x features) in boost or similar?

Alexandrescu came up with ScopeGuard a long time back. Both Boost and std::tr1 has a thing called scoped_ptr and shared_ptr (with a custom deleter) that allows you to accomplish just this.


For the record, there is Boost ScopeExit.


Scope guards are definitely a good idea. I think the scope guard concept is potent tool for exception safety. If you can make a safer, cleaner version that Boost's ScopeExit using C++0x syntax, I think it would be well worth your time.

Similar to Alexandrescu's ScopeGuard and Boost's ScopeExit , the D programming language has direct syntax for this sort of thing. The D programming team thought the scope guard was a good enough idea that they added it directly to the language (ie it's not implemented in a library).

Example.

void foo( bool fail )
{
   scope(exit)
   {
      writeln("I'm always printed");
   }

   scope(success) writeln("The function exited normally");

   scope(error)
      writeln("The function exited with an exception.");

   if( fail )
      throw new Exception("Die Die Die!");
}

The scope based guards aren't anything new. It's functionality can easily be replicated with a class destructor (RAII and all that). It's also possible to replace with try/finally in C# or Java. Heck, even pthreads provides a rudimentary scope guard, called pthread_cleanup_push.

What makes scope guards so powerful is when you have multiple scope(*) statements in the function. It scales incredibly well, as opposed to try/finally which require super human powers to manage anything more than two.

Tags:

C++

C++11