cesium-native  0.41.0
ScopeGuard.h
1 #pragma once
2 
3 #include <type_traits>
4 #include <utility>
5 
6 namespace CesiumUtility {
14 template <typename ExitFunction> class ScopeGuard {
15 public:
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 
77 private:
78  bool _callExitFuncOnDestruct;
79  ExitFunction _exitFunc;
80 };
81 
82 template <typename ExistFunction>
83 ScopeGuard(ExistFunction) -> ScopeGuard<ExistFunction>;
84 } // 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(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
ScopeGuard(ExitFunctionArg &&_exitFunc)
Constructor.
Definition: ScopeGuard.h:29
Utility classes for Cesium.