Every day people behave in a terrific way in my environment. This is my daily rant about this, my life, the universe and everything.
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.
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. ;-)
3 comments:
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?
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. ;-)
Post a Comment