scope_guard.hpp 878 B

1234567891011121314151617181920212223242526272829303132333435
  1. //
  2. // scope_guard.hpp
  3. // memory
  4. //
  5. // Created by Sam Jaffe on 9/24/15.
  6. //
  7. //
  8. #pragma once
  9. #include <functional>
  10. struct scope_exit {
  11. template <typename F> scope_exit(F f) : _f(f) {}
  12. ~scope_exit() noexcept { _f(); }
  13. std::function<void()> _f;
  14. };
  15. #if __cplusplus > 201402L
  16. template <bool B>
  17. struct scope_exception {
  18. template <typename F> scope_exception(F f) : _f(f), _except(std::uncaught_exceptions()) {}
  19. ~scope_exception() noexcept(B) { if (B == (std::uncaught_exceptions() > _except)) _f(); }
  20. std::function<void()> _f;
  21. int const _except;
  22. };
  23. using scope_failure = scope_exception<true>;
  24. using scope_success = scope_exception<false>;
  25. #endif
  26. #define CONCAT2(A, B) A##B
  27. #define CONCAT(A, B) CONCAT2(A, B)
  28. #define scope(t) scope_##t CONCAT(inline_scope_guard_##t##_,__LINE__) = [&]()
  29. #define scope_guard(t, f) scope_##t CONCAT(scope_guard_##t##_,__LINE__){f};