scope_exit.h 1009 B

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