Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

The goto-less goto!

, 12 Oct 2011
Rate this:
Please Sign up or sign in to vote.
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.

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:

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)

Share

About the Author

CashCow2

United States United States
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140814.1 | Last Updated 12 Oct 2011
Article Copyright 2011 by CashCow2
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid