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