cesium-native 0.43.0
Loading...
Searching...
No Matches
ScopeGuard.h
1#pragma once
2
3#include <type_traits>
4#include <utility>
5
6namespace CesiumUtility {
14template <typename ExitFunction> class ScopeGuard {
15public:
22 template <
23 typename ExitFunctionArg,
24 typename std::enable_if_t<
25 !std::is_same_v<
26 std::remove_reference_t<std::remove_const_t<ExitFunctionArg>>,
28 int> = 0>
29 explicit ScopeGuard(ExitFunctionArg&& exitFunc)
30 : _callExitFuncOnDestruct{true},
31 _exitFunc{std::forward<ExitFunctionArg>(exitFunc)} {}
32
33 ScopeGuard(const ScopeGuard& rhs) = delete;
34
39 ScopeGuard(ScopeGuard&& rhs) noexcept
40 : _callExitFuncOnDestruct{rhs._callExitFuncOnDestruct},
41 _exitFunc{std::move(rhs._exitFunc)} {
42 rhs.release();
43 }
44
45 ScopeGuard& operator=(const ScopeGuard& rhs) = delete;
46
51 ScopeGuard& operator=(ScopeGuard&& rhs) noexcept {
52 if (&rhs != this) {
53 _callExitFuncOnDestruct = rhs._callExitFuncOnDestruct;
54 _exitFunc = std::move(rhs._exitFunc);
55 rhs.release();
56 }
57
58 return *this;
59 }
60
65 ~ScopeGuard() noexcept {
66 if (_callExitFuncOnDestruct) {
67 _exitFunc();
68 }
69 }
70
75 void release() noexcept { _callExitFuncOnDestruct = false; }
76
77private:
78 bool _callExitFuncOnDestruct;
79 ExitFunction _exitFunc;
80};
81
85template <typename ExitFunction>
87} // namespace CesiumUtility
A utility that will automatically call the lambda function when exiting a scope.
Definition ScopeGuard.h:14
~ScopeGuard() noexcept
Destructor. The guard will execute the lambda function when exiting a scope if it's not released.
Definition ScopeGuard.h:65
void release() noexcept
Upon calling ScopeGuard::release(), the guard will not execute the lambda function when exiting a sco...
Definition ScopeGuard.h:75
ScopeGuard(ExitFunctionArg &&exitFunc)
Constructor.
Definition ScopeGuard.h:29
ScopeGuard(ScopeGuard &&rhs) noexcept
Move constructor. The rhs will move its lambda to the lhs, and the rhs will not call its lambda upon ...
Definition ScopeGuard.h:39
ScopeGuard & operator=(ScopeGuard &&rhs) noexcept
Move assignment operator. The rhs will move its lambda to the lhs, and the rhs will not call its lamb...
Definition ScopeGuard.h:51
Utility classes for Cesium.
ScopeGuard(ExitFunction) -> ScopeGuard< ExitFunction >
Template deduction guide for ScopeGuard to help the compiler figure out that the type of ExitFunction...
STL namespace.