From: Zejun Wu Date: Thu, 17 Jul 2014 16:49:39 +0000 (-0700) Subject: Check for self-assignment in move assignment X-Git-Tag: v0.22.0~448 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=cb2dc2c8e4fefcc3dd38ed90e2aca02bc1e82e2c;p=folly.git 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 --- 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() { }