-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ex16_28_unique_ptr.h
72 lines (60 loc) · 1.74 KB
/
ex16_28_unique_ptr.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
#ifndef CP5_EX16_28_UNIQUE_PTR_H_
#define CP5_EX16_28_UNIQUE_PTR_H_
class Delete {
public:
template <typename T> void operator()(T* ptr) const { delete ptr; }
};
template <typename T, typename D = Delete> class UniquePtr {
public:
UniquePtr(T* ptr = nullptr, const D& d = D()) noexcept : ptr_(ptr), deleter_(d) {}
~UniquePtr() { deleter_(ptr_); }
UniquePtr(const UniquePtr&) = delete;
UniquePtr& operator=(const UniquePtr&) = delete;
UniquePtr(UniquePtr&& other) noexcept : ptr_(other.ptr_), deleter_(std::move(other.deleter_))
{
other.ptr_ = nullptr;
}
UniquePtr& operator=(UniquePtr&& other) noexcept
{
if (this != &other) {
reset();
ptr_ = other.ptr_;
deleter_ = std::move(other.deleter_);
other.ptr_ = nullptr;
}
return *this;
}
UniquePtr& operator=(std::nullptr_t) noexcept
{
reset();
return *this;
}
T* release() noexcept
{
T* ret = ptr_;
ptr_ = nullptr;
return ret;
}
void reset(T* q = nullptr) noexcept
{
deleter_(q);
ptr_ = q;
}
void swap(UniquePtr& other) noexcept
{
using std::swap;
swap(ptr_, other.ptr_);
swap(deleter_, other.deleter_);
}
T* get() const noexcept { return ptr_; }
D& get_deleter() noexcept { return deleter_; }
const D& get_deleter() const noexcept { return deleter_; }
explicit operator bool() const noexcept { return ptr_ != nullptr; }
T& operator*() const { return *ptr_; }
T* operator->() const noexcept { return ptr_; }
T& operator[](size_t i) const { return ptr_[i]; }
private:
T* ptr_ = nullptr;
D deleter_;
};
#endif // CP5_EX16_28_UNIQUE_PTR_H_