-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscope_exit.hpp
46 lines (37 loc) · 894 Bytes
/
scope_exit.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#ifndef SCOPE_EXIT_HPP
#define SCOPE_EXIT_HPP
#include <utility>
template <typename EF>
class scope_exit {
EF cb_;
bool cancelled_{false};
public:
scope_exit() = delete;
scope_exit(const scope_exit &) = delete;
scope_exit & operator=(const scope_exit &) = delete;
scope_exit & operator=(scope_exit &&) = delete;
template <typename EFP>
explicit scope_exit(EFP && cb)
: cb_{std::forward<EFP>(cb)}
{
}
scope_exit(scope_exit && other)
: cb_{std::move(other.cb_)}
, cancelled_{other.cancelled_}
{
other.release();
}
~scope_exit()
{
if (!cancelled_) {
cb_();
}
}
void release() noexcept { cancelled_ = true; }
};
template <typename EF>
auto make_scope_exit(EF && exit_function)
{
return scope_exit<std::decay_t<EF>>(std::forward<EF>(exit_function));
}
#endif