Skip to content

Commit

Permalink
Add missing assignment operator from 'nullopt_t'
Browse files Browse the repository at this point in the history
  • Loading branch information
jiixyj committed Dec 31, 2024
1 parent f4cd4b7 commit 216542b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions include/beman/optional26/optional.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,8 @@ class optional {
requires(!std::is_trivially_destructible_v<T>);

// \ref{optional.assign}, assignment
constexpr optional& operator=(nullopt_t) noexcept;

constexpr optional& operator=(const optional& rhs)
requires std::is_copy_constructible_v<T> && std::is_copy_assignable_v<T> &&
(!std::is_trivially_copy_assignable_v<T>);
Expand Down Expand Up @@ -514,6 +516,12 @@ inline constexpr optional<T>::~optional()

// 22.5.3.4 Assignment[optional.assign]

template <class T>
inline constexpr optional<T>& optional<T>::operator=(nullopt_t) noexcept {
reset();
return *this;
}

template <class T>
inline constexpr optional<T>& optional<T>::operator=(const optional<T>& rhs)
requires std::is_copy_constructible_v<T> && std::is_copy_assignable_v<T> &&
Expand Down
20 changes: 20 additions & 0 deletions src/beman/optional26/tests/optional.t.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -868,3 +868,23 @@ TEST(OptionalTest, HashTest) {
EXPECT_EQ(h1, h2);
}
}

TEST(OptionalTest, CanHoldValueOfImmovableType) {
struct immovable {
explicit immovable() = default;
immovable(const immovable&) = delete;
immovable& operator=(const immovable&) = delete;
};

beman::optional26::optional<immovable> o1(beman::optional26::in_place);
EXPECT_TRUE(o1);

// ...and can reset it with `nullopt`.
static_assert(noexcept(o1 = beman::optional26::nullopt));
o1 = beman::optional26::nullopt;
EXPECT_FALSE(o1);

// Also, can construct with `nullopt`.
beman::optional26::optional<immovable> o2 = beman::optional26::nullopt;
EXPECT_FALSE(o2);
}

0 comments on commit 216542b

Please sign in to comment.