Skip to content

Commit 8fbb026

Browse files
committed
Added tests for bug when swapping value/null-value and null-value value
1 parent 53697d4 commit 8fbb026

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ if(OPTIONAL_ENABLE_TESTS)
2828
${CMAKE_CURRENT_SOURCE_DIR}/tests/assignment.cpp
2929
${CMAKE_CURRENT_SOURCE_DIR}/tests/issues.cpp
3030
${CMAKE_CURRENT_SOURCE_DIR}/tests/bases.cpp
31-
${CMAKE_CURRENT_SOURCE_DIR}/tests/nullopt.cpp)
31+
${CMAKE_CURRENT_SOURCE_DIR}/tests/nullopt.cpp
32+
${CMAKE_CURRENT_SOURCE_DIR}/tests/swap.cpp)
3233

3334
add_executable(tests ${TEST_SOURCES})
3435

tests/swap.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#include "catch.hpp"
2+
#include "optional.hpp"
3+
4+
TEST_CASE("Swap value", "[swap.value]") {
5+
tl::optional<int> o1 = 42;
6+
tl::optional<int> o2 = 12;
7+
o1.swap(o2);
8+
CHECK(o1.value() == 12);
9+
CHECK(o2.value() == 42);
10+
}
11+
12+
TEST_CASE("Swap value with null intialized", "[swap.value_nullopt]") {
13+
tl::optional<int> o1 = 42;
14+
tl::optional<int> o2 = tl::nullopt;
15+
o1.swap(o2);
16+
CHECK(!o1.has_value());
17+
CHECK(o2.value() == 42);
18+
}
19+
20+
TEST_CASE("Swap null intialized with value", "[swap.nullopt_value]") {
21+
tl::optional<int> o1 = tl::nullopt;
22+
tl::optional<int> o2 = 42;
23+
o1.swap(o2);
24+
CHECK(o1.value() == 42);
25+
CHECK(!o2.has_value());
26+
}

tl/optional.hpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1238,9 +1238,9 @@ class optional : private detail::optional_move_assign_base<T>,
12381238
void
12391239
swap(optional &rhs) noexcept(std::is_nothrow_move_constructible<T>::value
12401240
&&detail::is_nothrow_swappable<T>::value) {
1241+
using std::swap;
12411242
if (has_value()) {
12421243
if (rhs.has_value()) {
1243-
using std::swap;
12441244
swap(**this, *rhs);
12451245
} else {
12461246
new (std::addressof(rhs.m_value)) T(std::move(this->m_value));
@@ -1250,6 +1250,7 @@ class optional : private detail::optional_move_assign_base<T>,
12501250
new (std::addressof(this->m_value)) T(std::move(rhs.m_value));
12511251
rhs.m_value.T::~T();
12521252
}
1253+
swap(this->m_has_value, rhs.m_has_value);
12531254
}
12541255

12551256
/// Returns a pointer to the stored value

0 commit comments

Comments
 (0)