-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharedPtr.cpp
More file actions
159 lines (138 loc) · 2.24 KB
/
SharedPtr.cpp
File metadata and controls
159 lines (138 loc) · 2.24 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//
// Created by rjd67 on 2021/2/28.
//
#ifndef BASE_MEMORY_H
#define BASE_MEMORY_H
template<class T>
class Counter
{
public:
explicit Counter(T* ptr);
~Counter();
void Destroy();
void Dispose();
void Release();
Counter* AddRefCopy();
T* Get();
private:
T* ptr_;
int shared_count_;
};
template<class T>
Counter<T>::Counter(T* ptr)
:
ptr_(ptr),
shared_count_(1)
{
}
template<class T>
Counter<T>::~Counter()
= default;
template<class T>
void Counter<T>::Destroy()
{
delete this;
}
template<class T>
void Counter<T>::Release()
{
shared_count_--;
if (shared_count_ == 0)
{
Dispose();
Destroy();
}
}
template<class T>
Counter<T>* Counter<T>::AddRefCopy()
{
shared_count_++;
return this;
}
template<class T>
void Counter<T>::Dispose()
{
delete ptr_;
}
template<class T>
T* Counter<T>::Get()
{
return ptr_;
}
template<class T>
class SharedPtr
{
public:
SharedPtr();
explicit SharedPtr(T* ptr);
~SharedPtr();
T* Get();
void Reset(T* ptr);
SharedPtr(const SharedPtr&);
SharedPtr<T>& operator=(const SharedPtr&);
T& operator*();
void Swap(SharedPtr& shared_ptr);
private:
T* ptr_;
Counter<T>* counter_;
};
template<class T>
SharedPtr<T>::SharedPtr()
:
ptr_(nullptr),
counter_(new Counter<T>(nullptr))
{
}
template<class T>
SharedPtr<T>::SharedPtr(T* ptr)
:
ptr_(ptr),
counter_(new Counter<T>(ptr))
{
}
template<class T>
SharedPtr<T>::~SharedPtr()
{
counter_->Release();
}
template<class T>
T* SharedPtr<T>::Get()
{
return ptr_;
}
template<class T>
void SharedPtr<T>::Reset(T* ptr)
{
SharedPtr<T>(ptr).Swap(*this);
}
template<class T>
void SharedPtr<T>::Swap(SharedPtr& shared_ptr)
{
std::swap(ptr_, shared_ptr.ptr_);
std::swap(counter_, shared_ptr.counter_);
}
template<class T>
SharedPtr<T>::SharedPtr(const SharedPtr& shared_ptr)
{
Counter<T>* other_counter = shared_ptr.counter_;
counter_ = other_counter->AddRefCopy();
ptr_ = other_counter->Get();
}
template<class T>
SharedPtr<T>& SharedPtr<T>::operator=(const SharedPtr& shared_ptr)
{
Counter<T>* other_counter = shared_ptr.counter_;
if (counter_ != other_counter)
{
counter_->Release();
counter_ = other_counter->AddRefCopy();
ptr_ = other_counter->Get();
}
return *this;
}
template<class T>
T& SharedPtr<T>::operator*()
{
return *ptr_;
}
#endif //BASE_MEMORY_H