I've made a quick finally
type in C++:
template<class F>
class finally_type {
public:
explicit finally_type(F f) : function(f) {}
~finally_type() { try { function(); } catch (...) {} }
private:
F function;
};
template<class F>
finally_type<F> finally(F f) { return finally_type<F>(f); }
(Edited to add swallower to prevent exceptions from propagating out of the callback.)
With C++0x, it's convenient to use this class as follows:
void test() {
int* i = new int;
auto cleanup = finally([i]() { delete i; });
may_throw();
}
Regardless of whether may_throw()
throws, the finally
ensures that the cleanup code executes when the stack is unwound. The equivalent idiom in C++03 is using a local type:
void test() {
int* i = new int;
struct finally {
finally(int* i) : i(i) {}
~finally() { delete i; }
int* i;
} cleanup(i);
may_throw();
}
As you can see, the closure must be managed explicitly, with loads of repetitive (and consequently error-prone) code; with a lambda, this process is vastly simplified.
Frankly, I don't see much use to it, since if you're interfacing with legacy code, you're probably just going to wrap the types or use a shared_ptr
with a custom deleter. You could use it to manage low-level locks in multithreaded code, if that's your fancy for some reason.
Anyway, assuming someone does find it useful, is there anything important that I missed?