-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharedPtr.cpp
More file actions
105 lines (88 loc) · 2.12 KB
/
SharedPtr.cpp
File metadata and controls
105 lines (88 loc) · 2.12 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
#include <algorithm>
#include <memory>
#include <utility>
#include <iostream>
template<typename T>
class SharedPtr {
private:
T *ptr;
size_t *count;
void increase() {
if (ptr != nullptr) {
if (count == nullptr)
count = new size_t(0);
++(*count);
}
}
void decrease() noexcept {
if (ptr == nullptr)
return;
if (*count == 1) {
delete count;
delete ptr;
return;
}
--(*count);
}
public:
SharedPtr() : ptr(nullptr), count(nullptr) {}
SharedPtr(T *ptr) : ptr(ptr), count(nullptr) {
increase();
}
SharedPtr(const SharedPtr &other) : ptr(other.ptr), count(other.count) {
increase();
}
SharedPtr(SharedPtr &&other) : ptr(other.ptr), count(other.count) {
other.ptr = nullptr;
other.count = nullptr;
}
SharedPtr &operator=(const SharedPtr &other) {
if (ptr != other.ptr) {
decrease();
ptr = other.ptr;
count = other.count;
increase();
}
return *this;
}
SharedPtr &operator=(SharedPtr &&other) {
if (ptr != other.ptr) {
decrease();
ptr = other.ptr;
count = other.count;
other.ptr = nullptr;
other.count = nullptr;
}
return *this;
}
T &operator*() {
return *ptr;
}
const T &operator*() const {
return *ptr;
}
const T *operator->() const {
return ptr;
}
void reset(T *ptr_) {
if (ptr != ptr_) {
decrease();
ptr = ptr_;
count = nullptr;
increase();
}
}
void swap(SharedPtr &other) noexcept {
std::swap(ptr, other.ptr);
std::swap(count, other.count);
}
T *get() const {
return ptr;
}
explicit operator bool() const noexcept {
return ptr != nullptr;
}
~SharedPtr() {
decrease();
}
};