plugify 1.2.8
Loading...
Searching...
No Matches
guards.hpp
1#pragma once
2
3#include "plg/config.hpp"
4
5namespace plg {
6#if PLUGIFY_HAS_EXCEPTIONS
7 template <class Rollback>
8 struct exception_guard_exceptions {
9 exception_guard_exceptions() = delete;
10
11 constexpr explicit exception_guard_exceptions(Rollback rollback)
12 : rollback_(std::move(rollback))
13 , completed_(false) {
14 }
15
16 constexpr exception_guard_exceptions(
17 exception_guard_exceptions&& other
18 ) noexcept(std::is_nothrow_move_constructible_v<Rollback>)
19 : rollback_(std::move(other.rollback_))
20 , completed_(other.completed_) {
21 other.completed_ = true;
22 }
23
24 exception_guard_exceptions(const exception_guard_exceptions&) = delete;
25 exception_guard_exceptions& operator=(const exception_guard_exceptions&) = delete;
26 exception_guard_exceptions& operator=(exception_guard_exceptions&&) = delete;
27
28 constexpr void complete() noexcept {
29 completed_ = true;
30 }
31
32 constexpr ~exception_guard_exceptions() {
33 if (!completed_) {
34 rollback_();
35 }
36 }
37
38 private:
39 PLUGIFY_NO_UNIQUE_ADDRESS Rollback rollback_;
40 bool completed_;
41 };
42
43 template <class Rollback>
44 using exception_guard = exception_guard_exceptions<Rollback>;
45#else
46 template <class Rollback>
49
50 constexpr explicit exception_guard_noexceptions(Rollback) {
51 }
52
55 ) noexcept(std::is_nothrow_move_constructible_v<Rollback>)
56 : completed_(other.completed_) {
57 other.completed_ = true;
58 }
59
63
64 constexpr void complete() noexcept {
65 completed_ = true;
66 }
67
69 PLUGIFY_ASSERT(completed_, "exception_guard not completed with exceptions disabled");
70 }
71
72 private:
73 bool completed_ = false;
74 };
75
76 template <class Rollback>
78#endif
79
80 template <class Rollback>
81 constexpr exception_guard<Rollback> make_exception_guard(Rollback rollback) {
82 return exception_guard<Rollback>(std::move(rollback));
83 }
84
85 template <class Func>
87 PLUGIFY_NO_UNIQUE_ADDRESS Func func_;
88
89 public:
90 constexpr explicit scope_guard(Func func)
91 : func_(std::move(func)) {
92 }
93
94 constexpr ~scope_guard() {
95 func_();
96 }
97
98 scope_guard(const scope_guard&) = delete;
99 scope_guard& operator=(const scope_guard&) = delete;
100 scope_guard& operator=(scope_guard&&) = delete;
101 scope_guard(scope_guard&&) = delete;
102 };
103
104 template <class Func>
105 constexpr scope_guard<Func> make_scope_guard(Func func) {
106 return scope_guard<Func>(std::move(func));
107 }
108}