智能指针

文章目录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
template<class T>
class SharedPointer
{
public:
SharedPointer():m_refCount(nullptr), m_pointer(nullptr) {}

SharedPointer(T* adoptTarget):m_refCount(nullptr), m_pointer(adoptTarget) {
addReference();
}

SharedPointer(const SharedPointer<T>& copy):m_refCount(copy.m_refCount), m_pointer(copy.m_pointer) {
addReference();
}

virtual ~SharedPointer() {
removeReference();
}

//赋值操作
//当左值被赋值时,表明它不再指向所指的资源,故引用计数减一
//之后,它指向了新的资源,所以对应这个资源的引用计数加一
SharedPointer<T>& operator=(const SharedPointer<T>& that) {
if (this != &that) {
removeReference();
this->m_pointer = that.m_pointer;
this->m_refCount = that.m_refCount;
addReference();
}
return *this;
}


//判断是否指向同一个资源
bool operator==(const SharedPointer<T>& other) {
return m_pointer == other.m_pointer;
}
bool operator!=(const SharedPointer<T>& other) {
return !operator==(other);
}

//指针解引用
T& operator*() const {
return *m_pointer;
}
//调用所知对象的公共成员
T* operator->() const {
return m_pointer;
}

//获取引用计数个数
int GetReferenceCount() const {
if (m_refCount) {
return *m_refCount;
} else {
return -1;
}
}
protected:

//当为nullpter时,创建引用计数资源,并初始化为1
//否则,引用计数加1。
void addReference() {
if (m_refCount) {
(*m_refCount)++;
} else {
m_refCount = new int(0);
*m_refCount = 1;
}
}

void removeReference() {
if(m_refCount) {
(*m_refCount)--;
if(*m_refCount == 0) {
delete m_refCount;
delete m_pointer;
m_refCount = 0;
m_pointer = 0;
}
}
}
private:
int *m_refCount;
T *m_pointer;
};