CC

自然万物都趋向从有序变得无序

0%

c++ 智能指针shared_ptr实现

智能指针为一个带有指针和计数器的类

  • 计数器使用指针实现,可以实现多个智能指针的计数器指向同一地址,方便计数

代码

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
#include "algorithm"
#include "iostream"
using namespace std;

template<typename T>
class shared_p{
private:
unsigned int *count;
T* ptr;
public:
shared_p(T* p):ptr(p), count(new unsigned int(1)){}
shared_p(const shared_p<T> &p):ptr(p.ptr), count(p.count){
(*count)++;
}
shared_p(const T *p):ptr(p), count(new unsigned int(1)){}
~shared_p(){
if(count != nullptr &&--(*count) == 0){
delete count;
delete ptr;
}
}
unsigned int getCount(){
return *(this->count);
}
shared_p<T>& operator= (const shared_p &p){
if(this == &p)
return *this;
if(count != nullptr &&--(*count) == 0){
delete count;
delete ptr;
}
(*p.count)++;

ptr = p.ptr;
count = p.count;
return *this;
}

T &operator*(){
return *(this->ptr);
}
T *operator->(){
return this->ptr;
}
};

int main(){
shared_p<string> p1(new string("hellow shared_ptr"));
cout<<p1.getCount()<<endl;
shared_p<string> p2(p1);
cout<<p1.getCount()<<" "<<p2.getCount()<<endl;
return 0;
}