-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfinally.h
79 lines (64 loc) · 1.75 KB
/
finally.h
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef FINALLY_H
#define FINALLY_H
#include <exception> // std::uncaught_exceptions
#include <type_traits> // std::decay
#include <utility> // std::exchange/forward/move
template <typename T>
class final_action {
public:
explicit final_action(T action) : action_(std::move(action)) {}
final_action(final_action&& other) noexcept
: action_(std::move(other.action_)),
is_active_(std::exchange(other.is_active_, false))
{
}
final_action(const final_action&) = delete;
final_action& operator=(const final_action&) = delete;
final_action& operator=(final_action&&) = delete;
~final_action()
{
if (is_active_) {
action_();
}
}
void dismiss() noexcept
{
is_active_ = false;
}
private:
T action_;
bool is_active_{true};
};
template <typename T>
auto finally(T&& action)
{
return final_action<std::decay_t<T>>(std::forward<T>(action));
}
#if __cpp_lib_uncaught_exceptions >= 201411L
// Similar to final_action but with the key difference that the
// contained action will not be invoked during exception propagation.
// Requires C++17 or later.
template <typename T>
class on_return {
public:
explicit on_return(T action)
: action_(std::move(action)),
uncaught_exceptions_on_entry_(std::uncaught_exceptions())
{
}
on_return(const on_return&) = delete;
on_return(on_return&&) = delete;
on_return& operator=(const on_return&) = delete;
on_return& operator=(on_return&&) = delete;
~on_return()
{
if (std::uncaught_exceptions() == uncaught_exceptions_on_entry_) {
action_();
}
}
private:
T action_;
int uncaught_exceptions_on_entry_;
};
#endif
#endif // FINALLY_H