OXYGENHUB
◆ main openmsx / src / utils / scope_exit.hh
988 B · C++ · last changed chore(): initial commit 1 month ago source blame history raw
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
25
template<std::invocable FUNC>
26
class scope_exit
27
{
28
public:
29
    explicit scope_exit(FUNC&& action_)
30
        : action(std::forward<FUNC>(action_))
31
    {
32
    }
33
34
    ~scope_exit()
35
    {
36
        action();
37
    }
38
39
private:
40
    [[no_unique_address]] FUNC action;
41
};
42
43
#endif