Skip to content

Commit 231c3f4

Browse files
Create scope_example.cpp
1 parent 1c666fa commit 231c3f4

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

examples/scope_example.cpp

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2+
3+
#include <cstdlib>
4+
#include <experimental/scope>
5+
#include <iostream>
6+
#include <string_view>
7+
8+
void print_exit_status(std::string_view name, bool exit_status, bool did_throw)
9+
{
10+
std::cout << name << ":\n";
11+
std::cout << " Throwed exception " << (did_throw ? "yes" : "no") << "\n";
12+
std::cout << " Exit status " << (exit_status ? "finished" : "pending") << "\n\n";
13+
}
14+
15+
// Randomly throw an exception (50% chance)
16+
void maybe_throw()
17+
{
18+
if (std::rand() >= RAND_MAX / 2)
19+
throw std::exception{};
20+
}
21+
22+
int main()
23+
{
24+
bool exit_status{false}, did_throw{false};
25+
26+
// Manual handling at "end of scope"
27+
try
28+
{
29+
maybe_throw();
30+
exit_status = true;
31+
}
32+
catch (...)
33+
{
34+
did_throw = true;
35+
}
36+
print_exit_status("Manual handling", exit_status, did_throw);
37+
38+
// Using scope_exit: runs on scope exit (success or exception)
39+
exit_status = did_throw = false;
40+
try
41+
{
42+
auto guard = std::experimental::scope_exit{[&] { exit_status = true; }};
43+
maybe_throw();
44+
}
45+
catch (...)
46+
{
47+
did_throw = true;
48+
}
49+
print_exit_status("scope_exit", exit_status, did_throw);
50+
51+
// Using scope_fail: runs only if an exception occurs
52+
exit_status = did_throw = false;
53+
try
54+
{
55+
auto guard = std::experimental::scope_fail{[&] { exit_status = true; }};
56+
maybe_throw();
57+
}
58+
catch (...)
59+
{
60+
did_throw = true;
61+
}
62+
print_exit_status("scope_fail", exit_status, did_throw);
63+
64+
// Using scope_success: runs only if no exception occurs
65+
exit_status = did_throw = false;
66+
try
67+
{
68+
auto guard = std::experimental::scope_success{[&] { exit_status = true; }};
69+
maybe_throw();
70+
}
71+
catch (...)
72+
{
73+
did_throw = true;
74+
}
75+
print_exit_status("scope_success", exit_status, did_throw);
76+
}

0 commit comments

Comments
 (0)