scope_exit.h 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include "common/common_funcs.h"
  6. #include <utility>
  7. namespace detail {
  8. template <typename Func>
  9. struct ScopeExitHelper {
  10. explicit ScopeExitHelper(Func&& func) : func(std::move(func)) {}
  11. ~ScopeExitHelper() { func(); }
  12. Func func;
  13. };
  14. template <typename Func>
  15. ScopeExitHelper<Func> ScopeExit(Func&& func) { return ScopeExitHelper<Func>(std::move(func)); }
  16. }
  17. /**
  18. * This macro allows you to conveniently specify a block of code that will run on scope exit. Handy
  19. * for doing ad-hoc clean-up tasks in a function with multiple returns.
  20. *
  21. * Example usage:
  22. * \code
  23. * const int saved_val = g_foo;
  24. * g_foo = 55;
  25. * SCOPE_EXIT({ g_foo = saved_val; });
  26. *
  27. * if (Bar()) {
  28. * return 0;
  29. * } else {
  30. * return 20;
  31. * }
  32. * \endcode
  33. */
  34. #define SCOPE_EXIT(body) auto CONCAT2(scope_exit_helper_, __LINE__) = detail::ScopeExit([&]() body)