aboutsummaryrefslogtreecommitdiff
path: root/src/libutil/finally.hh
blob: 49263ee6d9825d0377146341e65dd35d94fb9e02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#pragma once
///@file

/**
 * A trivial class to run a function at the end of a scope.
 */
template<typename Fn>
class Finally
{
private:
    Fn fun;
    bool movedFrom = false;

public:
    Finally(Fn fun) : fun(std::move(fun)) { }
    // Copying Finallys is definitely not a good idea and will cause them to be
    // called twice.
    Finally(Finally &other) = delete;
    Finally(Finally &&other) : fun(std::move(other.fun)) {
        other.movedFrom = true;
    }
    ~Finally() { if (!movedFrom) fun(); }
};