-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUniquePtr.cpp
74 lines (72 loc) · 1.97 KB
/
UniquePtr.cpp
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
#include <memory>
#include <tuple>
template <class T, class D = std::default_delete<T>>
class UniquePtr {
private:
std::tuple<T*, D> ptr;
public:
explicit UniquePtr(T* other = nullptr) {
std::get<0>(ptr) = other;
}
UniquePtr(T* other, const D& deleter) {
std::get<0>(ptr) = other;
std::get<1>(ptr) = deleter;
}
UniquePtr(UniquePtr&& other) noexcept {
this -> swap(other);
}
UniquePtr(const UniquePtr& other) = delete;
UniquePtr& operator= (const UniquePtr& other) = delete;
UniquePtr& operator= (std::nullptr_t) {
std::get<1>(ptr)(std::get<0>(ptr));
std::get<0>(ptr) = nullptr;
return *this;
}
UniquePtr& operator= (UniquePtr&& other) noexcept {
this -> swap(other);
return *this;
}
~UniquePtr() {
std::get<1>(ptr)(std::get<0>(ptr));
}
const T* operator-> () const {
return std::get<0>(ptr);
}
const T& operator* () const {
return *std::get<0>(ptr);
}
T* release() {
T* tmp = std::get<0>(ptr);
std::get<0>(ptr) = nullptr;
return tmp;
}
void reset(T* other) {
if (std::get<0>(ptr) != other) {
std::get<1>(ptr)(std::get<0>(ptr));
std::get<0>(ptr) = other;
}
}
void swap(UniquePtr& other) {
if (this == &other) {
return;
}
T* tmp = std::get<0>(ptr);
std::get<0>(ptr) = std::get<0>(other.ptr);
std::get<0>(other.ptr) = tmp;
D tmp2 = std::get<1>(ptr);
std::get<1>(ptr) = std::get<1>(other.ptr);
std::get<1>(other.ptr) = tmp2;
}
T* get() const {
return std::get<0>(ptr);
}
explicit operator bool() const {
return std::get<0>(ptr) != nullptr;
}
const D& get_deleter() const {
return std::get<1>(ptr);
}
D& get_deleter() {
return std::get<1>(ptr);
}
};