🛰️航天仿真算法库 SpaceAST 0.0.1
载入中...
搜索中...
未找到
SharedPtr.hpp
浏览该文件的文档.
1
20
21#pragma once
22
23#include "AstGlobal.h"
24
25AST_NAMESPACE_BEGIN
26
31template<typename _Object>
33{
34public:
35 SharedPtr()
36 :m_object{ nullptr }
37 {}
38 SharedPtr(std::nullptr_t)
39 :m_object{ nullptr }
40 {
41 }
42 SharedPtr(_Object* obj)
43 :m_object{ obj }
44 {
45 _incRef();
46 }
47 SharedPtr(const SharedPtr& ptr)
48 :SharedPtr{ptr.get()}
49 {
50
51 }
53 {
54 _decRef();
55 }
56 SharedPtr& operator=(const SharedPtr& ptr)
57 {
58 return this->operator=(ptr.get());
59 }
60
61 SharedPtr& operator=(_Object* obj)
62 {
63 if(obj != m_object){
64 if(obj)
65 obj->incRef();
66 _decRef();
67 m_object = obj;
68 }
69 return *this;
70 }
71 SharedPtr& operator=(std::nullptr_t)
72 {
73 reset();
74 return *this;
75 }
76 // 这里还是设置为支持隐式转换,因为在很多情况下,我们需要将SharedPtr转换为_Object*
77 // explicit
78 operator _Object*() const
79 {
80 return m_object;
81 }
82 explicit operator bool() const
83 {
84 return m_object != nullptr;
85 }
86 _Object* operator->() const
87 {
88 return m_object;
89 }
90 _Object* get() const
91 {
92 return m_object;
93 }
94 _Object* take()
95 {
96 _Object* obj = m_object;
97 if(obj){
98 obj->decRefNoDelete();
99 m_object = nullptr;
100 }
101 return obj;
102 }
103 void reset()
104 {
105 _decRef();
106 m_object = nullptr;
107 }
108protected:
109 void _incRef()
110 {
111 if(m_object)
112 m_object->incRef();
113 }
114 void _decRef()
115 {
116 if(m_object)
117 m_object->decRef();
118 }
119protected:
120 _Object* m_object{nullptr};
121};
122
123
124
125AST_NAMESPACE_END
126
共享指针
定义 SharedPtr.hpp:33