Repository navigation
Expand file tree
/
Copy pathstate_saver_success_example.cpp
More file actions
99 lines (75 loc) · 2.55 KB
/
Copy pathstate_saver_success_example.cpp
File metadata and controls
99 lines (75 loc) · 2.55 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
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
89
90
91
92
93
94
95
96
97
98
99
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2018 - 2026 Daniil Goncharov <neargye@gmail.com>.
#include <state_saver.hpp>
#include <iostream>
#include <stdexcept>
void foo1(int& a) {
SAVER_SUCCESS(a); // Restore on successful scope exit.
a = 1;
std::cout << "foo1 a = " << a << std::endl;
// The original state is restored when the scope exits without a new exception.
}
void foo2(int& a) {
SAVER_SUCCESS(a); // Restore only on successful scope exit.
a = 2;
std::cout << "foo2 a = " << a << std::endl;
throw std::runtime_error{"error"};
// The original state is not restored during exception unwinding.
}
void foo3(int& a) {
#if defined(__cpp_deduction_guides) && __cpp_deduction_guides >= 201611L
nstd::saver_success state_saver{a}; // Named success saver, without macros.
#else
nstd::saver_success<decltype(a)> state_saver{a}; // Named success saver, without macros.
#endif
a = 3;
std::cout << "foo3 a = " << a << std::endl;
// The original state is restored when the scope exits without a new exception.
}
void foo4(int& a) {
MAKE_SAVER_SUCCESS(state_saver, a); // Named success saver.
a = 4;
std::cout << "foo4 a = " << a << std::endl;
state_saver.dismiss(); // Disable automatic restore.
std::cout << "foo4 state_saver::dismiss" << std::endl;
// The original state is not restored automatically on scope exit.
}
void foo5(int& a) {
MAKE_SAVER_SUCCESS(state_saver, a); // Named success saver.
a = 5;
std::cout << "foo5 a = " << a << std::endl;
state_saver.dismiss(); // Disable automatic restore.
std::cout << "foo5 state_saver::dismiss" << std::endl;
state_saver.restore(); // Restore immediately.
std::cout << "foo5 state_saver::restore" << std::endl;
std::cout << "foo5 a = " << a << std::endl;
// The original state is not restored automatically on scope exit.
}
void foo6(int& a) {
WITH_SAVER_SUCCESS(a) {
a = 1;
std::cout << "foo6 a = " << a << std::endl;
// The original state is restored before control leaves this block.
}
std::cout << "foo6 a = " << a << std::endl;
}
int main() {
int a = 0;
std::cout << "main a = " << a << std::endl;
foo1(a);
std::cout << "main a = " << a << std::endl;
try {
foo2(a);
} catch (...) {}
std::cout << "main a = " << a << std::endl;
foo3(a);
std::cout << "main a = " << a << std::endl;
foo4(a);
std::cout << "main a = " << a << std::endl;
foo5(a);
std::cout << "main a = " << a << std::endl;
foo6(a);
std::cout << "main a = " << a << std::endl;
return 0;
}