2
0

ScopeGuard.h 782 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. namespace vstd
  12. {
  13. template<typename Func>
  14. class ScopeGuard
  15. {
  16. bool fire;
  17. Func f;
  18. explicit ScopeGuard(ScopeGuard&);
  19. ScopeGuard& operator=(ScopeGuard&);
  20. public:
  21. ScopeGuard(ScopeGuard &&other):
  22. fire(false),
  23. f(other.f)
  24. {
  25. std::swap(fire, other.fire);
  26. }
  27. explicit ScopeGuard(Func && f):
  28. fire(true),
  29. f(std::forward<Func>(f))
  30. {}
  31. ~ScopeGuard()
  32. {
  33. f();
  34. }
  35. };
  36. template <typename Func>
  37. ScopeGuard<Func> makeScopeGuard(Func&& exitScope)
  38. {
  39. return ScopeGuard<Func>(std::forward<Func>(exitScope));
  40. }
  41. }