diff --git a/lib/include/srsran/adt/detail/type_storage.h b/lib/include/srsran/adt/detail/type_storage.h index 5e7ba2803..d52ee97a5 100644 --- a/lib/include/srsran/adt/detail/type_storage.h +++ b/lib/include/srsran/adt/detail/type_storage.h @@ -70,11 +70,9 @@ void copy_if_present_helper(type_storage& lhs, { if (lhs_present and rhs_present) { lhs.get() = rhs.get(); - } - if (lhs_present) { + } else if (lhs_present) { lhs.destroy(); - } - if (rhs_present) { + } else if (rhs_present) { lhs.copy_ctor(rhs); } } @@ -87,11 +85,9 @@ void move_if_present_helper(type_storage& lhs, { if (lhs_present and rhs_present) { lhs.move_assign(std::move(rhs)); - } - if (lhs_present) { + } else if (lhs_present) { lhs.destroy(); - } - if (rhs_present) { + } else if (rhs_present) { lhs.move_ctor(std::move(rhs)); } } diff --git a/lib/test/adt/optional_test.cc b/lib/test/adt/optional_test.cc index bcfe19063..ea8eb388b 100644 --- a/lib/test/adt/optional_test.cc +++ b/lib/test/adt/optional_test.cc @@ -29,7 +29,26 @@ void test_optional_int() TESTASSERT(opt == opt2); } +struct C { + std::unique_ptr val; + + C(int val = 0) : val(std::make_unique(val)) {} +}; + +void test_optional_move_only() +{ + optional a, b; + a.emplace(C{}); + TESTASSERT(a.has_value()); + TESTASSERT_EQ(0, *a.value().val); + TESTASSERT(not b.has_value()); + b.emplace(C{5}); + a = std::move(b); + TESTASSERT_EQ(5, *a.value().val); +} + int main() { test_optional_int(); + test_optional_move_only(); } \ No newline at end of file