ScopeGuard.h 836 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * ScopeGuard.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. VCMI_LIB_NAMESPACE_BEGIN
  12. namespace vstd
  13. {
  14. template<typename Func>
  15. class ScopeGuard
  16. {
  17. bool fire;
  18. Func f;
  19. explicit ScopeGuard(ScopeGuard&);
  20. ScopeGuard& operator=(ScopeGuard&);
  21. public:
  22. ScopeGuard(ScopeGuard &&other):
  23. fire(false),
  24. f(other.f)
  25. {
  26. std::swap(fire, other.fire);
  27. }
  28. explicit ScopeGuard(Func && f):
  29. fire(true),
  30. f(std::move(f))
  31. {}
  32. ~ScopeGuard()
  33. {
  34. if(fire)
  35. f();
  36. }
  37. };
  38. template <typename Func>
  39. ScopeGuard<Func> makeScopeGuard(Func&& exitScope)
  40. {
  41. return ScopeGuard<Func>(std::forward<Func>(exitScope));
  42. }
  43. }
  44. VCMI_LIB_NAMESPACE_END