C++ note 4 - Shared Pointer

Shared pointer:

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
#include <iostream>
class RC
{
private:
int count;
public:
RC() : count(0) {}
int add() {
return ++count;
}
int remove() {
return --count;
}
int get() {
return count;
}
};
template <class T>
class SP
{
private:
T* data;
RC* rc;
public:
explicit SP(T* d) : data(d), rc(new RC()) {
rc->add();
}
SP(const SP<T>& sp) : data(sp.data), rc(sp.rc) {
rc->add();
}
~SP() {
if (rc->remove() == 0) {
delete data;
delete rc;
}
}
SP<T>& operator = (const SP<T>& sp) {
if (this == &sp) return *this;
if (rc->remove() == 0) {
delete data;
delete rc;
}
data = sp.data;
rc = sp.rc;
rc->add();
return *this;
}
void print() {
std::cout << "data: " << *data << std::endl;
std::cout << "count: " << rc->get() << std::endl;
}
};
int main()
{
SP<int> sp(new int(5));
sp.print();
SP<int> sp2 = sp;
sp2.print();
SP<int> sp3(new int(4));
sp3 = sp;
sp3.print();
return 0;
}