scope_exit.h 1006 B

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