From 2fb61e7c71b7fcd7b60c64de44bbb4e6dca79b7d Mon Sep 17 00:00:00 2001 From: Sebastian Messmer Date: Mon, 3 Apr 2017 15:43:27 +0100 Subject: [PATCH] Further improve unique_ref --- src/cpp-utils/pointer/unique_ref.h | 12 +++++----- test/cpp-utils/pointer/unique_ref_test.cpp | 26 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/cpp-utils/pointer/unique_ref.h b/src/cpp-utils/pointer/unique_ref.h index 55b6b6e7..0ec70955 100644 --- a/src/cpp-utils/pointer/unique_ref.h +++ b/src/cpp-utils/pointer/unique_ref.h @@ -45,7 +45,7 @@ public: from._target = nullptr; return *this; } - + template unique_ref& operator=(unique_ref&& from) noexcept { _target = std::move(from._target); from._target = nullptr; @@ -70,12 +70,14 @@ public: return _target.get(); } - operator std::unique_ptr() && noexcept { - return std::move(_target); + template + operator std::unique_ptr() && noexcept { + return std::move(_target); } - operator std::shared_ptr() && noexcept { - return std::move(_target); + template + operator std::shared_ptr() && noexcept { + return std::move(_target); } void swap(unique_ref& rhs) noexcept { diff --git a/test/cpp-utils/pointer/unique_ref_test.cpp b/test/cpp-utils/pointer/unique_ref_test.cpp index cbdb9109..d04bcc4e 100644 --- a/test/cpp-utils/pointer/unique_ref_test.cpp +++ b/test/cpp-utils/pointer/unique_ref_test.cpp @@ -79,6 +79,16 @@ TEST(MakeUniqueRefTest, CanAssignToSharedPtr) { EXPECT_EQ(3, var->v); } +TEST(MakeUniqueRefTest, CanAssignToBaseClassUniquePtr) { + std::unique_ptr var = make_unique_ref(3); + EXPECT_EQ(3, var->v); +} + +TEST(MakeUniqueRefTest, CanAssignToBaseClassSharedPtr) { + std::shared_ptr var = make_unique_ref(3); + EXPECT_EQ(3, var->v); +} + TEST(NullcheckTest, PrimitiveNullptr) { boost::optional> var = nullcheck(std::unique_ptr(nullptr)); EXPECT_FALSE((bool)var); @@ -579,3 +589,19 @@ TEST_F(UniqueRefTest, givenUniqueRefToChildClass_whenMoveAssignedToBaseClass_the base = std::move(child); EXPECT_EQ(3, base->v); } + +TEST_F(UniqueRefTest, givenUniqueRefToChildClass_whenCastedToBaseClassUniquePtr_thenWorksAsExpected) { + unique_ref child = make_unique_ref(3); + std::unique_ptr base = std::make_unique(10); + base = std::move(child); + EXPECT_FALSE(child.isValid()); + EXPECT_EQ(3, base->v); +} + +TEST_F(UniqueRefTest, givenUniqueRefToChildClass_whenCastedToBaseClassSharedPtr_thenWorksAsExpected) { + unique_ref child = make_unique_ref(3); + std::shared_ptr base = std::make_unique(10); + base = std::move(child); + EXPECT_FALSE(child.isValid()); + EXPECT_EQ(3, base->v); +}