-
Notifications
You must be signed in to change notification settings - Fork 137
/
jacky.cpp
88 lines (77 loc) · 1.55 KB
/
jacky.cpp
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
80
81
82
83
84
85
86
87
88
#include <concepts>
#include <cstdio>
#include <functional>
#include <iostream>
template <class Func, class... Args>
requires std::invocable<Func, Args...>
class scope_guard {
public:
explicit scope_guard(Func&& func, Args&&... args) noexcept
: m_func(std::forward<Func>(func))
, m_args(std::forward<Args>(args)...)
{
}
~scope_guard() noexcept(std::is_nothrow_invocable_v<Func, Args...>)
{
std::apply(m_func, m_args);
}
private:
const Func m_func;
const std::tuple<Args...> m_args;
};
template <class Func, class... Args>
scope_guard(Func&&, Args&&...) -> scope_guard<Func&&, Args&&...>;
struct X {
X()
{
puts("X()");
}
X(const X&)
{
puts("X(const X&)");
}
X(X&&) noexcept
{
puts("X(X&&)");
}
~X()
{
puts("~X()");
}
};
int main()
{
{
auto x = new X{};
auto guard = scope_guard([&] {
delete x;
x = nullptr;
});
}
puts("----------");
{
struct Test {
void operator()(X*& x)
{
delete x;
x = nullptr;
}
};
auto x = new X{};
Test t;
auto guard = scope_guard(t, x);
}
puts("----------");
{
struct Test {
void f(X*& x)
{
delete x;
x = nullptr;
}
};
auto x = new X{};
Test t;
auto guard = scope_guard{&Test::f, &t, x}; // error
}
}