Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

The goto-less goto!

0.00/5 (No votes)
12 Oct 2011CPOL 5.8K  
The correct way to do this in C++ is to invoke some form of RAII whereby the failure logic happens automatically in an object's destructor.class CleanupObject{public: CleanupObject() : successState( false ) { } void completedOk() { successState = false;...

The correct way to do this in C++ is to invoke some form of RAII whereby the failure logic happens automatically in an object's destructor.


C++
class CleanupObject
{
public:
    CleanupObject() : successState( false )
    {
    }

    void completedOk()
    {
       successState = false;
    }

   ~CleanupObject()
   {
      if( successState )
         normalCleanup();
      else
          failedCleanup();
    
private:
    bool successState;      
};

In your code, add something like:


C++
void doStuff()
{
   CleanupObject obj;

   // whole load of code that might fail

   if( operation.fails() )
        return; // obj will call failed cleanup in destructor

// etc.

    obj.completedOk(); // to make it do normal cleanup on destructor
}

Your cleanup code must not throw any exceptions. Note here that your operations could throw, and your cleanup would still occur. (Your caller would need to catch.)


Using boost's "Scope Exit" might make it easier still to implement "exit code" that must be run at the end of a scope.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)