-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharedPtr.cpp
More file actions
121 lines (102 loc) · 2.43 KB
/
Copy pathSharedPtr.cpp
File metadata and controls
121 lines (102 loc) · 2.43 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
#include <atomic>
#include <iostream>
#include <utility>
template<typename T>
class SharedPtr {
public:
explicit SharedPtr(T* data = nullptr) : _data(data), _ref(nullptr) {
if (_data) {
try {
_ref = new std::atomic<int>(1);
} catch (...) {
delete _data;
throw;
}
}
}
~SharedPtr() {
release();
}
// 这里不需要考虑 this
SharedPtr(const SharedPtr& other) : _data(other._data), _ref(other._ref) {
if (_ref) {
_ref->fetch_add(1);
}
}
SharedPtr(SharedPtr&& other) noexcept : _data(other._data), _ref(other._ref) {
other._data = nullptr;
other._ref = nullptr;
}
SharedPtr& operator=(const SharedPtr& other) {
if (this != &other) {
release();
_data = other._data;
_ref = other._ref;
if (_ref) {
_ref->fetch_add(1);
}
}
return *this;
}
SharedPtr& operator=(SharedPtr&& other) noexcept {
if (this != &other) {
release();
_data = other._data;
_ref = other._ref;
other._data = nullptr;
other._ref = nullptr;
}
return *this;
}
// const
T* operator->() const {
return _data;
}
// operator*
T& operator*() const {
return *_data;
}
T* get() const {
return _data;
}
//explicit
explicit operator bool() const {
return _data != nullptr;
}
void reset(T* data = nullptr) {
SharedPtr temp(data);
swap(temp);
}
int count() const {
return _ref ? _ref->load() : 0;
}
void swap(SharedPtr& other) noexcept {
std::swap(_data, other._data);
std::swap(_ref, other._ref);
}
friend void swap(SharedPtr& lhs, SharedPtr& rhs) noexcept {
lhs.swap(rhs);
}
private:
void release() {
if (!_ref) {
_data = nullptr;
return;
}
if (_ref->fetch_sub(1) == 1) {
delete _data;
delete _ref;
}
_data = nullptr;
_ref = nullptr;
}
T* _data = nullptr;
std::atomic<int>* _ref = nullptr;
};
int main () {
auto p1 = SharedPtr<int>(new int(11));
auto p2 = p1;
std::cout << p2.count() << std::endl;
std::cout << *p2 << std::endl;
return 0;
}