🛰️航天仿真算法库 SpaceAST 0.0.1
载入中...
搜索中...
未找到
WeakPtr.hpp
浏览该文件的文档.
1
20
21#pragma once
22
23#include "AstGlobal.h"
24
25AST_NAMESPACE_BEGIN
26
27
32template<typename _Object>
34{
35public:
36 WeakPtr()
37 :m_object{ nullptr }
38 {
39 }
40 WeakPtr(std::nullptr_t)
41 :m_object{ nullptr }
42 {
43 }
44 WeakPtr(_Object* obj)
45 :m_object{ obj }
46 {
47 _incWeakRef();
48 }
49 WeakPtr(const WeakPtr& ptr)
50 :WeakPtr{ ptr.m_object }
51 {
52 }
53 ~WeakPtr()
54 {
55 _decWeakRef();
56 }
57 WeakPtr& operator=(_Object* obj)
58 {
59 if (obj != m_object) {
60 _decWeakRef();
61 m_object = obj;
62 _incWeakRef();
63 }
64 return *this;
65 }
66 WeakPtr& operator=(std::nullptr_t)
67 {
68 reset();
69 return *this;
70 }
71 WeakPtr& operator=(const WeakPtr& ptr)
72 {
73 if (this != &ptr) {
74 this->operator=(ptr.m_object);
75 }
76 return *this;
77 }
78 _Object* lock() const
79 {
80 return get();
81 }
82 _Object* get() const
83 {
84 if (expired()) {
85 return nullptr;
86 }
87 return m_object;
88 }
89 bool expired() const
90 {
91 return !m_object || m_object->isDestructed();
92 }
93 void reset()
94 {
95 _decWeakRef();
96 m_object = nullptr;
97 }
98private:
99 void _incWeakRef()
100 {
101 if(m_object)
102 m_object->incWeakRef();
103 }
104 void _decWeakRef()
105 {
106 if(m_object)
107 m_object->decWeakRef();
108 }
109protected:
110 _Object* m_object{nullptr};
111};
112
113
114
115AST_NAMESPACE_END
116
117
118
119
弱引用指针
定义 WeakPtr.hpp:34