Friday, January 27, 2006

finally clause in C++

The following puzzle was suggested by my former colleague Thomas. Explain how to port a finally clause as used in Java to C++ without loosing its semantics.

3 comments:

Unknown said...

Generally, finally clauses are done using stack objects in C++. I.e. if the code in Java was:

int oldFoo = getFoo();
try {
setFoo(15);
doSomethingThatMayFail();
}
catch( ... )
{
...
}
finally
{
setFoo(oldFoo);
}

You'd write a class

class StFooChanger
{
public:
int mSavedFoo;

StFooChanger( int newVal )
{
mSavedFoo = getFoo();
setFoo( newVal );
}
~StFooChanger()
{
setFoo(mSavedFoo);
}
};

and then use it like:

StFooChanger changer(15);
try {
doSomethingThatMayFail();
}
catch( ... )
{
...
}

And the destructor of changer will take care of setting things back, whether an exception is raised or not. Cookie?

Unknown said...
This comment has been removed by the author.
Robert said...

Yes, stack objects is a good way to go here. Though you could write it down a little more Java-like. But since this was not explicitly requested you may take your cookie. Google websites have a spare one all the time. ;-)