From bc1d058d2d37bc67e93e30080e8d4d4c2be38edd Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 1 Jul 2019 17:34:02 -0700 Subject: Add a helper to construct the optional value --- common/aloptional.h | 47 ++++++++++++++++++----------------------------- 1 file changed, 18 insertions(+), 29 deletions(-) diff --git a/common/aloptional.h b/common/aloptional.h index 8524a2e2..2ed882e4 100644 --- a/common/aloptional.h +++ b/common/aloptional.h @@ -17,23 +17,28 @@ constexpr in_place_t in_place{}; template class optional { + bool mHasValue{false}; + union { + char mDummy[sizeof(T)]{}; + T mValue; + }; + + template + void DoConstruct(Args&& ...args) + { + ::new (std::addressof(mValue)) T{std::forward(args)...}; + mHasValue = true; + } + public: using value_type = T; optional() noexcept = default; optional(nullopt_t) noexcept { } template::value)> - optional(const optional &rhs) : mHasValue{rhs.mHasValue} - { - if(mHasValue) - std::uninitialized_copy_n(std::addressof(*rhs), 1, std::addressof(mValue)); - } + optional(const optional &rhs) { if(rhs) DoConstruct(*rhs); } template::value)> - optional(optional&& rhs) : mHasValue{rhs.mHasValue} - { - if(mHasValue) - al::uninitialized_move_n(std::addressof(*rhs), 1, std::addressof(mValue)); - } + optional(optional&& rhs) { if(rhs) DoConstruct(std::move(*rhs)); } template::value)> explicit optional(in_place_t, Args&& ...args) : mHasValue{true} , mValue{std::forward(args)...} @@ -65,10 +70,7 @@ public: else if(*this) mValue = *rhs; else - { - std::uninitialized_copy_n(std::addressof(*rhs), 1, std::addressof(mValue)); - mHasValue = true; - } + DoConstruct(*rhs); return *this; } template::value && std::is_move_assignable::value)> @@ -79,10 +81,7 @@ public: else if(*this) mValue = std::move(*rhs); else - { - al::uninitialized_move_n(std::addressof(*rhs), 1, std::addressof(mValue)); - mHasValue = true; - } + DoConstruct(std::move(*rhs)); return *this; } template::value && @@ -95,10 +94,7 @@ public: if(*this) mValue = std::forward(rhs); else - { - ::new (std::addressof(mValue)) T{std::forward(rhs)}; - mHasValue = true; - } + DoConstruct(std::forward(rhs)); return *this; } @@ -130,13 +126,6 @@ public: al::destroy_at(std::addressof(mValue)); mHasValue = false; } - -private: - bool mHasValue{false}; - union { - char mDummy[sizeof(T)]{}; - T mValue; - }; }; template -- cgit v1.2.3