From cb2dc2c8e4fefcc3dd38ed90e2aca02bc1e82e2c Mon Sep 17 00:00:00 2001 From: Zejun Wu Date: Thu, 17 Jul 2014 09:49:39 -0700 Subject: [PATCH] Check for self-assignment in move assignment Summary: Check for self-assignment in move assignment. Otherwise Optional cat = whatever; cat = std::move(cat); cat.hasValue(); // always returns false Test Plan: fbmake runtests Reviewed By: tjackson@fb.com FB internal diff: D1440633 --- folly/Optional.h | 12 +++++++----- folly/test/OptionalTest.cpp | 10 ++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/folly/Optional.h b/folly/Optional.h index 701d744e..eb8de160 100644 --- a/folly/Optional.h +++ b/folly/Optional.h @@ -136,11 +136,13 @@ class Optional { } void assign(Optional&& src) { - if (src.hasValue()) { - assign(std::move(src.value())); - src.clear(); - } else { - clear(); + if (this != &src) { + if (src.hasValue()) { + assign(std::move(src.value())); + src.clear(); + } else { + clear(); + } } } diff --git a/folly/test/OptionalTest.cpp b/folly/test/OptionalTest.cpp index ff82abdc..79968d01 100644 --- a/folly/test/OptionalTest.cpp +++ b/folly/test/OptionalTest.cpp @@ -379,6 +379,16 @@ TEST(Optional, MakeOptional) { EXPECT_EQ(**optIntPtr, 3); } +TEST(Optional, SelfAssignment) { + Optional a = 42; + a = a; + ASSERT_TRUE(a.hasValue() && a.value() == 42); + + Optional b = 23333333; + b = std::move(b); + ASSERT_TRUE(b.hasValue() && b.value() == 23333333); +} + class ContainsOptional { public: ContainsOptional() { } -- 2.34.1