Skip to content

Commit e384ca3

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

File tree

1 file changed

+33
-20
lines changed

1 file changed

+33
-20
lines changed

src/runtime/optional.h

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -64,41 +64,54 @@ class optional {
6464
void emplace(Args&&... args) {
6565
if (m_some)
6666
m_value.~T();
67-
m_some = true;
6867
new (&m_value) T(args...);
68+
m_some = true;
6969
}
7070

7171
optional& operator=(optional const & other) {
72-
if (this == &other)
73-
return *this;
74-
if (m_some)
72+
if (other.m_some) {
73+
if (m_some) {
74+
m_value = other.value;
75+
} else {
76+
new (&m_value) T(other.m_value);
77+
m_some = true;
78+
}
79+
} else if (m_some) {
7580
m_value.~T();
76-
m_some = other.m_some;
77-
if (m_some)
78-
new (&m_value) T(other.m_value);
81+
m_some = false;
82+
}
7983
return *this;
8084
}
8185
optional& operator=(optional && other) {
82-
lean_assert(this != &other);
83-
if (m_some)
86+
if (other.m_some) {
87+
if (m_some) {
88+
m_value = std::move(other.value);
89+
} else {
90+
new (&m_value) T(std::move(other.m_value));
91+
m_some = true;
92+
}
93+
} else if (m_some) {
8494
m_value.~T();
85-
m_some = other.m_some;
86-
if (m_some)
87-
new (&m_value) T(std::move(other.m_value));
95+
m_some = false;
96+
}
8897
return *this;
8998
}
9099
optional& operator=(T const & other) {
91-
if (m_some)
92-
m_value.~T();
93-
m_some = true;
94-
new (&m_value) T(other);
100+
if (m_some) {
101+
m_value = other;
102+
} else {
103+
new (&m_value) T(other);
104+
m_some = true;
105+
}
95106
return *this;
96107
}
97108
optional& operator=(T && other) {
98-
if (m_some)
99-
m_value.~T();
100-
m_some = true;
101-
new (&m_value) T(std::move(other));
109+
if (m_some) {
110+
m_value = std::move(other);
111+
} else {
112+
new (&m_value) T(std::move(other));
113+
m_some = true;
114+
}
102115
return *this;
103116
}
104117

0 commit comments

Comments
 (0)