-
Notifications
You must be signed in to change notification settings - Fork 0
/
container.hpp
132 lines (105 loc) · 2.57 KB
/
container.hpp
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
132
#pragma once
#include <cassert>
#include <utility>
// The difference between Opt and Box is that Opt can be initialized or
// assigned to nullptr, while Box can only be null after being moved.
// Besides, the data in const Opt can still be modified, while the data
// in const Box cannot be modified.
// Both Opt and Box can be copied and moved. The data in them will also
// be copied when they are copied.
template<typename T>
class Opt {
T *data;
Opt(T *data)
: data(data) {}
public:
Opt(std::nullptr_t)
: data(nullptr) {}
Opt(Opt const &other)
: data(other.data ? new T(*other.data) : nullptr) {}
Opt(Opt &&other)
: data(other.data) {
other.data = nullptr;
}
Opt &operator=(std::nullptr_t) {
delete data;
data = nullptr;
return *this;
}
Opt &operator=(Opt const &other) {
if (this != &other) {
delete data;
data = other.data ? new T(*other.data) : nullptr;
}
return *this;
}
Opt &operator=(Opt &&other) {
assert(this != &other); // self-assignment is not allowed
delete data;
data = other.data;
other.data = nullptr;
return *this;
}
~Opt() {
delete data;
}
template<typename... Args>
static Opt make(Args &&...args) {
return Opt(new T(std::forward<Args>(args)...));
}
T &operator*() const & {
return *data;
}
T *operator->() const & {
return data;
}
operator bool() const {
return data;
}
};
template<typename T>
class Box {
T *data;
Box(T *data)
: data(data) {}
public:
Box(Box const &other)
: data(new T(*other.data)) {}
Box(Box &&other)
: data(other.data) {
other.data = nullptr;
}
Box &operator=(Box const &other) {
if (this != &other) {
delete data;
data = new T(*other.data);
}
return *this;
}
Box &operator=(Box &&other) {
assert(this != &other); // self-assignment is not allowed
delete data;
data = other.data;
other.data = nullptr;
return *this;
}
~Box() {
delete data;
}
template<typename... Args>
static Box make(Args &&...args) {
return Box(new T(std::forward<Args>(args)...));
}
T const &operator*() const & {
return *data;
}
T const *operator->() const & {
return data;
}
T &operator*() & {
return *data;
}
T *operator->() & {
return data;
}
};