FinallyScopeExit

suggest change

For 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:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents