diff options
Diffstat (limited to 'src/common/scope_exit.h')
| -rw-r--r-- | src/common/scope_exit.h | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/common/scope_exit.h b/src/common/scope_exit.h new file mode 100644 index 000000000..263beaf0e --- /dev/null +++ b/src/common/scope_exit.h | |||
| @@ -0,0 +1,37 @@ | |||
| 1 | // Copyright 2014 Citra Emulator Project | ||
| 2 | // Licensed under GPLv2 or any later version | ||
| 3 | // Refer to the license.txt file included. | ||
| 4 | |||
| 5 | #pragma once | ||
| 6 | |||
| 7 | namespace detail { | ||
| 8 | template <typename Func> | ||
| 9 | struct ScopeExitHelper { | ||
| 10 | explicit ScopeExitHelper(Func&& func) : func(std::move(func)) {} | ||
| 11 | ~ScopeExitHelper() { func(); } | ||
| 12 | |||
| 13 | Func func; | ||
| 14 | }; | ||
| 15 | |||
| 16 | template <typename Func> | ||
| 17 | ScopeExitHelper<Func> ScopeExit(Func&& func) { return ScopeExitHelper<Func>(std::move(func)); } | ||
| 18 | } | ||
| 19 | |||
| 20 | /** | ||
| 21 | * This macro allows you to conveniently specify a block of code that will run on scope exit. Handy | ||
| 22 | * for doing ad-hoc clean-up tasks in a function with multiple returns. | ||
| 23 | * | ||
| 24 | * Example usage: | ||
| 25 | * \code | ||
| 26 | * const int saved_val = g_foo; | ||
| 27 | * g_foo = 55; | ||
| 28 | * SCOPE_EXIT({ g_foo = saved_val; }); | ||
| 29 | * | ||
| 30 | * if (Bar()) { | ||
| 31 | * return 0; | ||
| 32 | * } else { | ||
| 33 | * return 20; | ||
| 34 | * } | ||
| 35 | * \endcode | ||
| 36 | */ | ||
| 37 | #define SCOPE_EXIT(body) auto scope_exit_helper_##__LINE__ = detail::ScopeExit([&]() body) | ||