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