🛰️航天仿真算法库 SpaceAST 0.0.1
载入中...
搜索中...
未找到
WeakPtr.hpp
浏览该文件的文档.
1
20
21#pragma once
22
23#include "AstGlobal.h"
24#include "AstUtil/Object.hpp"
25
26AST_NAMESPACE_BEGIN
27
28
33template<typename _Object>
35{
36public:
37 WeakPtr()
38 :m_object{ nullptr }
39 {
40 }
41 WeakPtr(std::nullptr_t)
42 :m_object{ nullptr }
43 {
44 }
45 WeakPtr(_Object* obj)
46 :m_object{ obj }
47 {
48 _incWeakRef();
49 }
50 WeakPtr(const WeakPtr& ptr)
51 :WeakPtr{ ptr.m_object }
52 {
53 }
54 ~WeakPtr()
55 {
56 _decWeakRef();
57 }
58 WeakPtr& operator=(_Object* obj)
59 {
60 if (obj != m_object) {
61 _decWeakRef();
62 m_object = obj;
63 _incWeakRef();
64 }
65 return *this;
66 }
67 WeakPtr& operator=(std::nullptr_t)
68 {
69 reset();
70 return *this;
71 }
72 WeakPtr& operator=(const WeakPtr& ptr)
73 {
74 if (this != &ptr) {
75 this->operator=(ptr.m_object);
76 }
77 return *this;
78 }
79 _Object* lock() const
80 {
81 return get();
82 }
83 _Object* get() const
84 {
85 if (expired()) {
86 return nullptr;
87 }
88 return m_object;
89 }
90 bool expired() const
91 {
92 return !m_object || aObject_IsDestructed(m_object);
93 }
94 void reset()
95 {
96 _decWeakRef();
97 m_object = nullptr;
98 }
99 _Object* operator->() const
100 {
101 return m_object;
102 }
103 // operator _Object*() const
104 // {
105 // return get();
106 // }
107 explicit operator bool() const
108 {
109 return !expired();
110 }
111 bool operator==(const WeakPtr& other) const
112 {
113 return m_object == other.m_object;
114 }
115 bool operator!=(const WeakPtr& other) const
116 {
117 return m_object != other.m_object;
118 }
119 bool operator<(const WeakPtr& other) const
120 {
121 return m_object < other.m_object;
122 }
123private:
124 void _incWeakRef()
125 {
126 if(m_object)
127 aObject_IncWeakRef(m_object);
128 }
129 void _decWeakRef()
130 {
131 if(m_object)
132 aObject_DecWeakRef(m_object);
133 }
134protected:
135 _Object* m_object{nullptr};
136};
137
138
139
140AST_NAMESPACE_END
141
142namespace std
143{
144 template<typename _Object>
145 struct hash<ast::WeakPtr<_Object>>
146 {
147 size_t operator()(const ast::WeakPtr<_Object>& ptr) const
148 {
149 return hash<_Object*>()(ptr.get());
150 }
151 };
152}
弱引用指针
定义 WeakPtr.hpp:35
@fixme 头文件依赖倒置
定义 AgentInit.hpp:26