Possible Duplicate:
Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)
Does try/catch/finally construct is supported in C++11?
I'm asking because I couldn't find anywhere information about it.
Thanks.
Possible Duplicate:
Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)
Does try/catch/finally construct is supported in C++11?
I'm asking because I couldn't find anywhere information about it.
Thanks.
Not an excuse to forgo RAII, but useful when e.g. using non RAII aware APIs:
template<typename Functor>
struct finally_guard {
finally_guard(Functor f)
: functor(std::move(f))
, active(true)
{}
finally_guard(finally_guard&& other)
: functor(std::move(other.functor))
, active(other.active)
{ other.active = false; }
finally_guard& operator=(finally_guard&&) = delete;
~finally_guard()
{
if(active)
functor();
}
Functor functor;
bool active;
};
template<typename F>
finally_guard<typename std::decay<F>::type>
finally(F&& f)
{
return { std::forward<F>(f) };
}
Usage:
auto resource = /* acquire */;
auto guard = finally([&resource] { /* cleanup */ });
// using just
// finally([&resource] { /* cleanup */ });
// is wrong, as usual
Note how you don't need a try
block if you don't need to translate or otherwise handle exceptions.
While my example makes use of C++11 features, the same generic functionality was available with C++03 (no lambdas though).
finally_guard<typename std::decay<decltype(functor)>::type>&& guard = { std::move(functor) };
. This is exactly one construction. It can't be refactored into a function (getting a value across a function either means constructing, or returning a dangling reference with no lifetime extension), but can be refactored into a macro. However, this wouldn't work with a lambda expressions due to decltype
. So you can't win them all. –
Cawnpore C++11 does not add support for finally
. The decision makers (especially Stroustrup) have for many many years expressed a preference for other idioms, i.e. RAII. I think it is exceptionally unlikely that C++ will ever include finally
.
You don't need finally
in C++ because C++ has RAII which is much nicer.
scoped_ptr<some_struct> v = new some_struct; load_vector(v);
. If load_vector
throws, you won't leak memory in v
. Done (+ code is even more readable). –
Impersonal © 2022 - 2024 — McMap. All rights reserved.