FinallyScopeExit
suggest changeFor cases when we don’t want to write special classes to handle some resource, we may write a generic class:
template<typename Function>
class Finally final
{
public:
explicit Finally(Function f) : f(std::move(f)) {}
Finally(const Finally&) = delete;
Finally(Finally&& other) : f(std::move(other.f)), call(other.call) { other.call = false; }
Finally& operator=(const Finally&) = delete;
Finally& operator=(Finally&&) = delete;
~Finally() { if (call) f(); } // (1) See below
private:
Function f;
bool call = true;
};
// Execute the function f when the returned object goes out of scope.
// The moved-from object does not call f, so returning the guard runs it once.
// std::decay_t is C++14.
template<typename Function>
auto onExit(Function &&f) { return Finally<std::decay_t<Function>>{std::forward<Function>(f)}; }
And its example usage
void foo(std::vector<int>& v, int i)
{
// ...
v[i] += 42;
auto autoRollBackChange = onExit([&](){ v[i] -= 42; });
// ... code as recursive call `foo(v, i + 1)`
}
Note (1): The destructor has to decide what to do if f() throws:
~Finally() noexcept { f(); }:std::terminateis called in case of exception~Finally() noexcept(noexcept(f())) { f(); }: terminate() is called only in case of exception during stack unwinding.~Finally() noexcept { try { f(); } catch (...) { /* ignore exception (might log it) */} }Nostd::terminateis called, but the error cannot be handled, including when the stack is not unwinding.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents