-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweak.h
131 lines (99 loc) · 3 KB
/
weak.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
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
122
123
124
125
126
127
128
129
130
131
#pragma once
#include "../shared/shared.h"
// https://en.cppreference.com/w/cpp/memory/weak_ptr
template <typename T>
class WeakPtr {
private:
T* ptr_ = nullptr;
IBlock* ctrl_block_ = nullptr;
template <typename Y>
friend class SharedPtr;
public:
////////////////////////////////////////////////////////////////////////////////////////////////
// Constructors
WeakPtr() : ptr_{nullptr}, ctrl_block_{nullptr} {};
WeakPtr(const WeakPtr& other) {
ptr_ = other.ptr_;
ctrl_block_ = other.ctrl_block_;
if (ctrl_block_ != nullptr) {
ctrl_block_->IncWeak();
}
}
WeakPtr(WeakPtr&& other) {
ptr_ = other.ptr_;
ctrl_block_ = other.ctrl_block_;
other.ptr_ = nullptr;
other.ctrl_block_ = nullptr;
};
// Demote `SharedPtr`
// #2 from https://en.cppreference.com/w/cpp/memory/weak_ptr/weak_ptr
WeakPtr(const SharedPtr<T>& other) {
ptr_ = other.ptr_;
ctrl_block_ = other.ctrl_block_;
if (ctrl_block_ != nullptr) {
ctrl_block_->IncWeak();
}
};
////////////////////////////////////////////////////////////////////////////////////////////////
// `operator=`-s
WeakPtr& operator=(const WeakPtr& other) {
if (other.ptr_ == ptr_) {
return *this;
}
if (ctrl_block_ != nullptr) {
ctrl_block_->DecWeak();
}
ptr_ = other.ptr_;
ctrl_block_ = other.ctrl_block_;
if (ctrl_block_ != nullptr) {
ctrl_block_->IncWeak();
}
return *this;
};
WeakPtr& operator=(WeakPtr&& other) {
if (other.ptr_ == ptr_) {
return *this;
}
if (ctrl_block_ != nullptr) {
ctrl_block_->DecWeak();
}
ptr_ = other.ptr_;
ctrl_block_ = other.ctrl_block_;
other.ptr_ = nullptr;
other.ctrl_block_ = nullptr;
return *this;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Destructor
~WeakPtr() {
Reset();
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Modifiers
void Reset() {
if (ctrl_block_ != nullptr) {
ctrl_block_->DecWeak();
}
ptr_ = nullptr;
ctrl_block_ = nullptr;
};
template <typename Y>
void Swap(WeakPtr<Y>& other) {
std::swap(ctrl_block_, other.ctrl_block_);
std::swap(ptr_, other.ptr_);
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Observers
size_t UseCount() const {
if (ctrl_block_ != nullptr) {
return ctrl_block_->SharedCount();
}
return 0;
};
bool Expired() const {
return ctrl_block_ == nullptr || UseCount() == 0;
};
SharedPtr<T> Lock() const {
return Expired() ? SharedPtr<T>() : SharedPtr<T>(*this);
};
};