From 6442512877f0f6942e1b40c56131041f3faf9216 Mon Sep 17 00:00:00 2001 From: Sebastian Messmer Date: Sun, 28 Jun 2015 17:34:23 +0200 Subject: [PATCH] Allow dereferencing rvalues in unique_ref --- pointer/unique_ref.h | 5 ++++- test/pointer/unique_ref_test.cpp | 25 +++++++++++++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/pointer/unique_ref.h b/pointer/unique_ref.h index 16a622a2..ef08bdb2 100644 --- a/pointer/unique_ref.h +++ b/pointer/unique_ref.h @@ -36,9 +36,12 @@ public: return *this; } - typename std::add_lvalue_reference::type operator*() const { + typename std::add_lvalue_reference::type operator*() const& { return *_target; } + typename std::add_rvalue_reference::type operator*() && { + return std::move(*_target); + } T* operator->() const { return get(); diff --git a/test/pointer/unique_ref_test.cpp b/test/pointer/unique_ref_test.cpp index b30b30b7..15672f64 100644 --- a/test/pointer/unique_ref_test.cpp +++ b/test/pointer/unique_ref_test.cpp @@ -89,22 +89,22 @@ TEST(NullcheckTest, ClassWith2Parameters) { TEST(NullcheckTest, OptionIsResolvable_Primitive) { boost::optional> var = nullcheck(std::make_unique(3)); - unique_ref resolved = std::move(*var); + unique_ref resolved = std::move(var).value(); } TEST(NullcheckTest, OptionIsResolvable_Object) { boost::optional> var = nullcheck(std::make_unique()); - unique_ref resolved = std::move(*var); + unique_ref resolved = std::move(var).value(); } TEST(NullcheckTest, OptionIsAutoResolvable_Primitive) { auto var = nullcheck(std::make_unique(3)); - auto resolved = std::move(*var); + auto resolved = std::move(var).value(); } TEST(NullcheckTest, OptionIsAutoResolvable_Object) { auto var = nullcheck(std::make_unique()); - auto resolved = std::move(*var); + auto resolved = std::move(var).value(); } class UniqueRefTest: public ::testing::Test { @@ -400,3 +400,20 @@ TEST_F(UniqueRefTest, NullptrIsNotLessThanNullptr) { makeInvalid(std::move(var2)); EXPECT_FALSE(std::less>()(var1, var2)); } + +class OnlyMoveable { +public: + OnlyMoveable(int value_): value(value_) {} + OnlyMoveable(OnlyMoveable &&source): value(source.value) {source.value = -1;} + bool operator==(const OnlyMoveable &rhs) const { + return value == rhs.value; + } + int value; +private: + DISALLOW_COPY_AND_ASSIGN(OnlyMoveable); +}; + +TEST_F(UniqueRefTest, AllowsDerefOnRvalue) { + OnlyMoveable val = *make_unique_ref(5); + EXPECT_EQ(OnlyMoveable(5), val); +} \ No newline at end of file