Click here to Skip to main content
15,883,623 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

The goto-less goto!

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
12 Oct 2011CPOL 5.4K   1
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralI don't think I'd call this "the correct way"... it's just a... Pin
Albert Holguin14-Oct-11 5:05
professionalAlbert Holguin14-Oct-11 5:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.