scope_exit.h 963 B

12345678910111213141516171819202122232425262728293031323334353637
  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. namespace detail {
  6. template <typename Func>
  7. struct ScopeExitHelper {
  8. explicit ScopeExitHelper(Func&& func) : func(std::move(func)) {}
  9. ~ScopeExitHelper() { func(); }
  10. Func func;
  11. };
  12. template <typename Func>
  13. ScopeExitHelper<Func> ScopeExit(Func&& func) { return ScopeExitHelper<Func>(std::move(func)); }
  14. }
  15. /**
  16. * This macro allows you to conveniently specify a block of code that will run on scope exit. Handy
  17. * for doing ad-hoc clean-up tasks in a function with multiple returns.
  18. *
  19. * Example usage:
  20. * \code
  21. * const int saved_val = g_foo;
  22. * g_foo = 55;
  23. * SCOPE_EXIT({ g_foo = saved_val; });
  24. *
  25. * if (Bar()) {
  26. * return 0;
  27. * } else {
  28. * return 20;
  29. * }
  30. * \endcode
  31. */
  32. #define SCOPE_EXIT(body) auto scope_exit_helper_##__LINE__ = detail::ScopeExit([&]() body)