Been doing Java for number of years so haven\'t been tracking C++. Has finally clause been added to C++ exception handling in the language definition?<
Using C++11 with its lambda expressions, I've recently started using the following code to mimic finally:
class FinallyGuard {
private:
std::function f_;
public:
FinallyGuard(std::function f) : f_(f) { }
~FinallyGuard() { f_(); }
};
void foo() {
// Code before the try/finally goes here
{ // Open a new scope for the try/finally
FinallyGuard signalEndGuard([&]{
// Code for the finally block goes here
});
// Code for the try block goes here
} // End scope, will call destructor of FinallyGuard
// Code after the try/finally goes here
}
The FinallyGuard is an object which is constructed with a callable function-like argument, preferrably a lambda expression. It will simply remember that function until its destructor is called, which is the case when the object goes out of scope, either due to normal control flow or due to stack unwinding during exception handling. In both cases, the destructor will call the function, thus executing the code in question.
It is a bit strange that you have to write the code for the finally before the code for the try block, but apart from that it actually feels a lot like a genuine try/finally from Java. I guess one should not abuse this for situations where an object with its own proper destructor would be more appropriate, but there are cases where I consider this approach above more suitable. I discussed one such scenario in this question.
As far as I understand things, std::function will use some pointer indirection and at least one virtual function call to perform its type erasure, so there will be a performance overhead. Don't use this technique in a tight loop where performance is critical. In those cases, a specialized object whose destructor does one thing only would be more appropriate.