You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

scope_guard.h 1.2KB

7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #pragma once
  2. #include <utility>
  3. namespace sg
  4. {
  5. template<class Deleter>
  6. class scope_guard_t
  7. {
  8. public:
  9. explicit scope_guard_t(Deleter&& deleter) noexcept : m_deleter(std::move(deleter)),
  10. m_execute_on_destruction(true)
  11. {
  12. }
  13. scope_guard_t(scope_guard_t&& other) noexcept : m_deleter(std::move(other.m_deleter)),
  14. m_execute_on_destruction(other.m_execute_on_destruction)
  15. {
  16. other.release();
  17. }
  18. scope_guard_t(const scope_guard_t&) = delete;
  19. ~scope_guard_t()
  20. {
  21. if( m_execute_on_destruction == true )
  22. {
  23. m_deleter();
  24. }
  25. }
  26. void release()
  27. {
  28. m_execute_on_destruction = false;
  29. }
  30. scope_guard_t& operator=(const scope_guard_t&) = delete;
  31. scope_guard_t& operator=(scope_guard_t&&) = delete;
  32. private:
  33. Deleter m_deleter;
  34. bool m_execute_on_destruction;
  35. };
  36. template<class Deleter>
  37. scope_guard_t<Deleter> scope_guard(Deleter&& deleter) noexcept
  38. {
  39. return scope_guard_t<Deleter>(std::move(deleter));
  40. }
  41. }