openMSX
scope_exit.hh
Go to the documentation of this file.
1#ifndef SCOPE_EXIT_HH
2#define SCOPE_EXIT_HH
3
4// Simplified version of
5// https://en.cppreference.com/w/cpp/experimental/scope_exit
6//
7// Typically used to execute some cleanup action whenever a certain scope is
8// left. Either via the fall-through code path, a return/break/continue or via
9// an exception.
10//
11// Example usage:
12// bool f() {
13// char* ptr = some_c_style_function_that_returns_an_owning_pointer()
14// scope_exit e([&]{ free(ptr); });
15// if (some_check(ptr)) return false; // 1
16// stuff_which_might_throw(); // 2
17// return true; // 3
18// }
19//
20// Note: 'free(ptr)' is called when we exit the function via 1) 2) or 3)
21
22#include <concepts>
23#include <utility>
24
25template<std::invocable FUNC>
27{
28public:
29 explicit scope_exit(FUNC&& action_)
30 : action(std::forward<FUNC>(action_))
31 {
32 }
33
35 {
36 action();
37 }
38
39private:
40 [[no_unique_address]] FUNC action;
41};
42
43#endif
scope_exit(FUNC &&action_)
Definition scope_exit.hh:29
STL namespace.