-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshare_ptr.h
90 lines (89 loc) · 1.38 KB
/
share_ptr.h
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
#ifndef SHARE_PTR_H
#define SHARE_PTR_H
#include<algorithm>
template<typename T>
class share_ptr{
private:
T* data;
int* num;
public:
//构造函数
share_ptr(T* ptr=nullptr):data(ptr){
if(ptr==nullptr){
num=nullptr;
return;
}
num=new int;
*num=1;
}
//析构函数
~share_ptr(){
if(num==nullptr)return;
--(*num);
if(*num==0){
delete num;
delete data;
}
}
void swap(share_ptr<T> &rhs){
std::swap(rhs.data,data);
std::swap(rhs.num,num);
}
//引用构造函数
share_ptr(share_ptr<T> &rhs){
data=rhs.data;
num=rhs.num;
if(num!=nullptr)
++(*num);
}
//移动构造函数
share_ptr(share_ptr<T> &&rhs){
this->swap(rhs);
}
share_ptr<T>& operator=(share_ptr<T> rhs)noexcept{
this->swap(rhs);
return *this;
}
// share_ptr<T>& operator=(share_ptr<T>&& rhs)noexcept{
// this->release();
// data=rhs.data;
// num=rhs.num;
// rhs.data=nullptr;
// rhs.num=nullptr;
// return *this;
// }
T& operator*(){
return *data;
}
T* operator->(){
return data;
}
T* get(){
return data;
}
void reset(T* ptr=nullptr)noexcept{
this->release();
if(ptr==nullptr){
return;
}
data=ptr;
num=new int;
*num=1;
}
int use_count(){
if(num==nullptr)return 0;
return *num;
}
void release()noexcept{
if(num!=nullptr){
--(*num);
if(*num==0){
delete num;
delete data;
}
num=nullptr;
data=nullptr;
}
}
};
#endif