Commit a1dd1ce6 authored by Yedidya Feldblum's avatar Yedidya Feldblum Committed by Facebook Github Bot

Support self-copy in small_vector

Summary:
[Folly] Support self-copy in `small_vector`.

And refactor move-assignment to look like the fixed copy-assignment for symmetry.

Reviewed By: Ahmed-Salama

Differential Revision: D8321122

fbshipit-source-id: 2c8b26ad6c4e538266082df29276b827cf4505fc
parent e1df88af
...@@ -46,6 +46,7 @@ ...@@ -46,6 +46,7 @@
#include <folly/ConstexprMath.h> #include <folly/ConstexprMath.h>
#include <folly/FormatTraits.h> #include <folly/FormatTraits.h>
#include <folly/Likely.h>
#include <folly/Portability.h> #include <folly/Portability.h>
#include <folly/Traits.h> #include <folly/Traits.h>
#include <folly/lang/Assume.h> #include <folly/lang/Assume.h>
...@@ -489,18 +490,19 @@ class small_vector : public detail::small_vector_base< ...@@ -489,18 +490,19 @@ class small_vector : public detail::small_vector_base<
} }
small_vector& operator=(small_vector const& o) { small_vector& operator=(small_vector const& o) {
if (FOLLY_LIKELY(this != &o)) {
assign(o.begin(), o.end()); assign(o.begin(), o.end());
}
return *this; return *this;
} }
small_vector& operator=(small_vector&& o) { small_vector& operator=(small_vector&& o) {
// TODO: optimization: // TODO: optimization:
// if both are internal, use move assignment where possible // if both are internal, use move assignment where possible
if (this == &o) { if (FOLLY_LIKELY(this != &o)) {
return *this;
}
clear(); clear();
swap(o); swap(o);
}
return *this; return *this;
} }
......
...@@ -1099,3 +1099,23 @@ TEST(small_vector, NoHeapStorageForSortedVectorSet) { ...@@ -1099,3 +1099,23 @@ TEST(small_vector, NoHeapStorageForSortedVectorSet) {
EXPECT_THROW(test.insert(30), std::length_error); EXPECT_THROW(test.insert(30), std::length_error);
EXPECT_EQ(test.size(), 2); EXPECT_EQ(test.size(), 2);
} }
TEST(small_vector, SelfMoveAssignmentForVectorOfPair) {
folly::small_vector<std::pair<int, int>, 2> test;
test.emplace_back(13, 2);
EXPECT_EQ(test.size(), 1);
EXPECT_EQ(test[0].first, 13);
test = static_cast<decltype(test)&&>(test); // trick clang -Wself-move
EXPECT_EQ(test.size(), 1);
EXPECT_EQ(test[0].first, 13);
}
TEST(small_vector, SelfCopyAssignmentForVectorOfPair) {
folly::small_vector<std::pair<int, int>, 2> test;
test.emplace_back(13, 2);
EXPECT_EQ(test.size(), 1);
EXPECT_EQ(test[0].first, 13);
test = test;
EXPECT_EQ(test.size(), 1);
EXPECT_EQ(test[0].first, 13);
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment