[ox/std] Make Optional run destructor and constexpr friendly

This commit is contained in:
Gary Talent 2022-05-28 19:56:43 -05:00
parent 9c3a46d144
commit 885f4a8713

View File

@ -48,6 +48,12 @@ class Optional {
}
}
constexpr ~Optional() {
if (m_ptr) {
m_ptr->~T();
}
}
template<typename U = T>
constexpr U *get() noexcept {
return m_ptr;
@ -86,12 +92,13 @@ class Optional {
if (this == &other) {
return *this;
}
if (m_ptr) {
m_ptr->~T();
}
if (other.m_ptr) {
m_ptr = new(m_data) T(*other.m_ptr);
} else {
if (!m_ptr) {
emplace();
}
*m_ptr = *other.m_ptr;
} else if (m_ptr) {
m_ptr->~T();
m_ptr = nullptr;
}
return *this;
@ -101,12 +108,13 @@ class Optional {
if (this == &other) {
return *this;
}
if (m_ptr) {
m_ptr->~T();
}
if (other.m_ptr) {
m_ptr = new(m_data) T(std::move(*other.m_ptr));
} else {
if (!m_ptr) {
emplace();
}
*m_ptr = std::move(*other.m_ptr);
} else if (m_ptr) {
m_ptr->~T();
m_ptr = nullptr;
}
return *this;
@ -114,14 +122,14 @@ class Optional {
template<class... Args>
constexpr T &emplace(Args &&...args) {
m_ptr = new (m_data) T(ox::forward<Args>(args)...);
m_ptr = std::construct_at<T>(m_ptr, ox::forward<Args>(args)...);
return *m_ptr;
}
template<typename U, class... Args>
constexpr T &emplace_subclass(Args &&...args) {
static_assert(sizeof(U) <= buffSize, "Subclass is too large for this Optional");
m_ptr = new (m_data) U(ox::forward<Args>(args)...);
m_ptr = std::construct_at<U>(m_ptr, ox::forward<Args>(args)...);
return *m_ptr;
}