Skip to content

Commit 4c9dbed

Browse files
committed
perf: use assignment to implement optional<> move assignment
1 parent 4077bf2 commit 4c9dbed

File tree

1 file changed

+36
-21
lines changed

1 file changed

+36
-21
lines changed

src/runtime/optional.h

Lines changed: 36 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -62,43 +62,58 @@ class optional {
6262

6363
template<typename... Args>
6464
void emplace(Args&&... args) {
65-
if (m_some)
65+
if (m_some) {
6666
m_value.~T();
67-
m_some = true;
67+
m_some = false;
68+
}
6869
new (&m_value) T(args...);
70+
m_some = true;
6971
}
7072

7173
optional& operator=(optional const & other) {
72-
if (this == &other)
73-
return *this;
74-
if (m_some)
74+
if (other.m_some) {
75+
if (m_some) {
76+
m_value = other.value;
77+
} else {
78+
new (&m_value) T(other.m_value);
79+
m_some = true;
80+
}
81+
} else if (m_some) {
7582
m_value.~T();
76-
m_some = other.m_some;
77-
if (m_some)
78-
new (&m_value) T(other.m_value);
83+
m_some = false;
84+
}
7985
return *this;
8086
}
8187
optional& operator=(optional && other) {
82-
lean_assert(this != &other);
83-
if (m_some)
88+
if (other.m_some) {
89+
if (m_some) {
90+
m_value = std::move(other.value);
91+
} else {
92+
new (&m_value) T(std::move(other.m_value));
93+
m_some = true;
94+
}
95+
} else if (m_some) {
8496
m_value.~T();
85-
m_some = other.m_some;
86-
if (m_some)
87-
new (&m_value) T(std::move(other.m_value));
97+
m_some = false;
98+
}
8899
return *this;
89100
}
90101
optional& operator=(T const & other) {
91-
if (m_some)
92-
m_value.~T();
93-
m_some = true;
94-
new (&m_value) T(other);
102+
if (m_some) {
103+
m_value = other;
104+
} else {
105+
new (&m_value) T(other);
106+
m_some = true;
107+
}
95108
return *this;
96109
}
97110
optional& operator=(T && other) {
98-
if (m_some)
99-
m_value.~T();
100-
m_some = true;
101-
new (&m_value) T(std::move(other));
111+
if (m_some) {
112+
m_value = std::move(other);
113+
} else {
114+
new (&m_value) T(std::move(other));
115+
m_some = true;
116+
}
102117
return *this;
103118
}
104119

0 commit comments

Comments
 (0)