ScopeGuard.h 832 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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::forward<Func>(f))
  31. {}
  32. ~ScopeGuard()
  33. {
  34. f();
  35. }
  36. };
  37. template <typename Func>
  38. ScopeGuard<Func> makeScopeGuard(Func&& exitScope)
  39. {
  40. return ScopeGuard<Func>(std::forward<Func>(exitScope));
  41. }
  42. }
  43. VCMI_LIB_NAMESPACE_END