ScopeExit.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2024 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Core/NonCopyable.h>
  6. JPH_NAMESPACE_BEGIN
  7. /// Class that calls a function when it goes out of scope
  8. template <class F>
  9. class ScopeExit : public NonCopyable
  10. {
  11. public:
  12. /// Constructor specifies the exit function
  13. JPH_INLINE explicit ScopeExit(F &&inFunction) : mFunction(std::move(inFunction)) { }
  14. /// Destructor calls the exit function
  15. JPH_INLINE ~ScopeExit() { if (!mInvoked) mFunction(); }
  16. /// Call the exit function now instead of when going out of scope
  17. JPH_INLINE void Invoke()
  18. {
  19. if (!mInvoked)
  20. {
  21. mFunction();
  22. mInvoked = true;
  23. }
  24. }
  25. /// No longer call the exit function when going out of scope
  26. JPH_INLINE void Release()
  27. {
  28. mInvoked = true;
  29. }
  30. private:
  31. F mFunction;
  32. bool mInvoked = false;
  33. };
  34. #define JPH_SCOPE_EXIT_TAG2(line) scope_exit##line
  35. #define JPH_SCOPE_EXIT_TAG(line) JPH_SCOPE_EXIT_TAG2(line)
  36. /// Usage: JPH_SCOPE_EXIT([]{ code to call on scope exit });
  37. #define JPH_SCOPE_EXIT(...) ScopeExit JPH_SCOPE_EXIT_TAG(__LINE__)(__VA_ARGS__)
  38. JPH_NAMESPACE_END