🛰️航天仿真算法库 SpaceAST 0.3.1
载入中...
搜索中...
未找到
ScopeExit.hpp
浏览该文件的文档.
1
20
21#pragma once
22
23#include "AstGlobal.h"
24#include "AstUtil/TypeTraits.hpp"
25#include <utility> // std::move, std::forward
26#include <type_traits> // std::decay, std::is_nothrow_move_constructible
27
28AST_NAMESPACE_BEGIN
29
48template <typename F>
50{
51 static_assert(is_callable<F&>::value, "type F must be callable with no arguments");
52public:
54 explicit ScopeExit(const F& fn)
55 : fn_(fn), active_(true)
56 {}
57
59 explicit ScopeExit(F&& fn)
60 : fn_(std::move(fn)), active_(true)
61 {}
62
64 ScopeExit(ScopeExit&& other) noexcept(std::is_nothrow_move_constructible<F>::value)
65 : fn_(std::move(other.fn_)), active_(other.active_)
66 {
67 other.active_ = false;
68 }
69
72 {
73 invoke();
74 }
75
76 A_DISABLE_COPY(ScopeExit);
77
80 void invoke()
81 {
82 if (active_) {
83 active_ = false;
84 fn_();
85 }
86 }
87
89 void release() noexcept
90 {
91 active_ = false;
92 }
93
95 bool isActive() const noexcept { return active_; }
96
98 operator bool() const noexcept { return isActive(); }
99
100protected:
101 F fn_;
102 bool active_{true};
103};
104
105
116template <typename F>
117A_NODISCARD A_ALWAYS_INLINE ScopeExit<typename std::decay<F>::type> aScopeExit(F&& fn)
118{
119 return ScopeExit<typename std::decay<F>::type>(std::forward<F>(fn));
120}
121
124AST_NAMESPACE_END
作用域退出守卫
定义 ScopeExit.hpp:50
F fn_
离开作用域时执行的动作
定义 ScopeExit.hpp:101
bool isActive() const noexcept
是否仍持有待执行的清理动作
定义 ScopeExit.hpp:95
~ScopeExit()
析构时执行清理动作
定义 ScopeExit.hpp:71
ScopeExit(ScopeExit &&other) noexcept(std::is_nothrow_move_constructible< F >::value)
移动构造:接管另一守卫的动作,被移动者不再执行
定义 ScopeExit.hpp:64
void invoke()
立即执行清理动作并解除守卫
定义 ScopeExit.hpp:80
ScopeExit(F &&fn)
以右值可调用对象构造(接管所有权)
定义 ScopeExit.hpp:59
ScopeExit(const F &fn)
以左值可调用对象构造(拷贝一份)
定义 ScopeExit.hpp:54
void release() noexcept
放弃清理动作,析构时不再执行
定义 ScopeExit.hpp:89
A_NODISCARD A_ALWAYS_INLINE ScopeExit< typename std::decay< F >::type > aScopeExit(F &&fn)
创建一个作用域退出守卫,在离开当前作用域时执行给定动作
定义 ScopeExit.hpp:117
判断类型是否可调用
定义 TypeTraits.hpp:31