From deee3c62b254483474b2e3b3d64e6be376121bef Mon Sep 17 00:00:00 2001 From: "A. Jiang" Date: Thu, 18 Jan 2024 21:48:26 +0800 Subject: [PATCH] Fix self-move-assignment for `proxy` (#59) * Fix self-move-assignment for `proxy` * Fix test --- proxy.h | 12 +++++++----- tests/proxy_lifetime_tests.cpp | 6 ++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/proxy.h b/proxy.h index e6bb23d..12246fc 100644 --- a/proxy.h +++ b/proxy.h @@ -419,12 +419,14 @@ class proxy { proxy& operator=(const proxy&) requires(!HasCopyAssignment) = delete; proxy& operator=(proxy&& rhs) noexcept(HasNothrowMoveAssignment) requires(HasMoveAssignment) { - if constexpr (HasNothrowMoveAssignment) { - this->~proxy(); - } else { - reset(); // For weak exception safety + if (this != &rhs) { + if constexpr (HasNothrowMoveAssignment) { + this->~proxy(); + } else { + reset(); // For weak exception safety + } + new(this) proxy(std::move(rhs)); } - new(this) proxy(std::move(rhs)); return *this; } proxy& operator=(proxy&&) requires(!HasMoveAssignment) = delete; diff --git a/tests/proxy_lifetime_tests.cpp b/tests/proxy_lifetime_tests.cpp index 429c741..47f8a2f 100644 --- a/tests/proxy_lifetime_tests.cpp +++ b/tests/proxy_lifetime_tests.cpp @@ -649,12 +649,10 @@ TEST(ProxyLifetimeTests, TestMoveAssignment_FromValue_ToSelf) { #elif defined(__GNUC__) && __GNUC__ >= 13 #pragma GCC diagnostic pop #endif // __clang__ - ASSERT_FALSE(p.has_value()); - expected_ops.emplace_back(1, utils::LifetimeOperationType::kDestruction); - expected_ops.emplace_back(2, utils::LifetimeOperationType::kMoveConstruction); - expected_ops.emplace_back(2, utils::LifetimeOperationType::kDestruction); + ASSERT_TRUE(p.has_value()); ASSERT_TRUE(tracker.GetOperations() == expected_ops); } + expected_ops.emplace_back(1, utils::LifetimeOperationType::kDestruction); ASSERT_TRUE(tracker.GetOperations() == expected_ops); }