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 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Scope Guard
  3. * Copyright (C) 2017 offa
  4. *
  5. * This file is part of Scope Guard.
  6. *
  7. * Scope Guard is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * Scope Guard is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with Scope Guard. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #pragma once
  21. #include <utility>
  22. namespace sr
  23. {
  24. template<class Deleter>
  25. class scope_guard_t
  26. {
  27. public:
  28. explicit scope_guard_t(Deleter&& deleter) noexcept : m_deleter(std::move(deleter)),
  29. m_execute_on_destruction(true)
  30. {
  31. }
  32. scope_guard_t(const scope_guard_t&) = delete;
  33. scope_guard_t(scope_guard_t&& other) noexcept : m_deleter(std::move(other.m_deleter)),
  34. m_execute_on_destruction(other.m_execute_on_destruction)
  35. {
  36. other.release();
  37. }
  38. ~scope_guard_t()
  39. {
  40. if( m_execute_on_destruction == true )
  41. {
  42. callDeleterSafe();
  43. }
  44. }
  45. void release() noexcept
  46. {
  47. m_execute_on_destruction = false;
  48. }
  49. scope_guard_t& operator=(const scope_guard_t&) = delete;
  50. scope_guard_t& operator=(scope_guard_t&&) = delete;
  51. private:
  52. void callDeleterSafe() noexcept
  53. {
  54. try
  55. {
  56. m_deleter();
  57. }
  58. catch( ... ) { /* Empty */ }
  59. }
  60. Deleter m_deleter;
  61. bool m_execute_on_destruction;
  62. };
  63. template<class Deleter>
  64. scope_guard_t<Deleter> scope_guard(Deleter&& deleter) noexcept
  65. {
  66. return scope_guard_t<Deleter>{std::move(deleter)};
  67. }
  68. }