ScopeGuard.h 773 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright 2015 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <optional>
  5. namespace Common
  6. {
  7. template <typename Callable>
  8. class ScopeGuard final
  9. {
  10. public:
  11. ScopeGuard(Callable&& finalizer) : m_finalizer(std::forward<Callable>(finalizer)) {}
  12. ScopeGuard(ScopeGuard&& other) : m_finalizer(std::move(other.m_finalizer))
  13. {
  14. other.m_finalizer = nullptr;
  15. }
  16. ~ScopeGuard() { Exit(); }
  17. void Dismiss() { m_finalizer.reset(); }
  18. void Exit()
  19. {
  20. if (m_finalizer)
  21. {
  22. (*m_finalizer)(); // must not throw
  23. m_finalizer.reset();
  24. }
  25. }
  26. ScopeGuard(const ScopeGuard&) = delete;
  27. void operator=(const ScopeGuard&) = delete;
  28. private:
  29. std::optional<Callable> m_finalizer;
  30. };
  31. } // Namespace Common