-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscopeguard.hpp
More file actions
57 lines (45 loc) · 1.11 KB
/
scopeguard.hpp
File metadata and controls
57 lines (45 loc) · 1.11 KB
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
#pragma once
#include "object.hpp"
#include <type_traits>
#include <utility>
template<typename F>
class ScopeGuard
{
DISABLE_COPY(ScopeGuard)
public:
ScopeGuard() = delete;
explicit ScopeGuard(F &&func) noexcept
: m_func(std::move(func))
{}
explicit ScopeGuard(const F &func) noexcept
: m_func(func)
{}
ScopeGuard(ScopeGuard &&other) noexcept
: m_func(std::move(other.m_func))
, m_invoke(std::exchange(other.m_invoke, false))
{}
ScopeGuard &operator=(ScopeGuard &&other) noexcept
{
if (this != &other) {
m_func = std::move(other.m_func);
m_invoke = std::exchange(other.m_invoke, false);
}
}
~ScopeGuard() noexcept
{
if (m_invoke) {
m_func();
}
}
void dismiss() noexcept { m_invoke = false; }
private:
F m_func;
bool m_invoke = true;
};
template<typename F>
ScopeGuard(F (&)()) -> ScopeGuard<F (*)()>;
template<typename F>
[[nodiscard]] auto scopeGuard(F &&func) -> ScopeGuard<std::decay_t<F>>
{
return ScopeGuard<std::decay_t<F>>(std::forward<F>(func));
}