Commit bbe656da authored by Giuseppe Ottaviano's avatar Giuseppe Ottaviano Committed by Facebook Github Bot

Return reference in small_vector::emplace_back

Summary: Since C++17 `vector::emplace_back()` returns a reference to the new element, support that in `small_vector` too.

Reviewed By: terrelln, luciang

Differential Revision: D15007059

fbshipit-source-id: 3873fd0097e3d50f7967f47fbecfa6ab20cc72c5
parent 2bd32e7b
...@@ -779,7 +779,7 @@ class small_vector : public detail::small_vector_base< ...@@ -779,7 +779,7 @@ class small_vector : public detail::small_vector_base<
} }
template <class... Args> template <class... Args>
void emplace_back(Args&&... args) { reference emplace_back(Args&&... args) {
if (capacity() == size()) { if (capacity() == size()) {
// Any of args may be references into the vector. // Any of args may be references into the vector.
// When we are reallocating, we have to be careful to construct the new // When we are reallocating, we have to be careful to construct the new
...@@ -792,10 +792,11 @@ class small_vector : public detail::small_vector_base< ...@@ -792,10 +792,11 @@ class small_vector : public detail::small_vector_base<
new (end()) value_type(std::forward<Args>(args)...); new (end()) value_type(std::forward<Args>(args)...);
} }
this->setSize(size() + 1); this->setSize(size() + 1);
return back();
} }
void push_back(value_type&& t) { void push_back(value_type&& t) {
return emplace_back(std::move(t)); emplace_back(std::move(t));
} }
void push_back(value_type const& t) { void push_back(value_type const& t) {
......
...@@ -435,17 +435,24 @@ TEST(small_vector, Emplace) { ...@@ -435,17 +435,24 @@ TEST(small_vector, Emplace) {
folly::small_vector<NontrivialType> vec; folly::small_vector<NontrivialType> vec;
vec.reserve(1024); vec.reserve(1024);
vec.emplace_back(12); {
auto& emplaced = vec.emplace_back(12);
EXPECT_EQ(NontrivialType::ctored, 1); EXPECT_EQ(NontrivialType::ctored, 1);
EXPECT_EQ(vec.front().a, 12); EXPECT_EQ(vec.front().a, 12);
vec.emplace_back(13); EXPECT_TRUE(std::addressof(emplaced) == std::addressof(vec.back()));
}
{
auto& emplaced = vec.emplace_back(13);
EXPECT_EQ(vec.front().a, 12); EXPECT_EQ(vec.front().a, 12);
EXPECT_EQ(vec.back().a, 13); EXPECT_EQ(vec.back().a, 13);
EXPECT_EQ(NontrivialType::ctored, 2); EXPECT_EQ(NontrivialType::ctored, 2);
EXPECT_TRUE(std::addressof(emplaced) == std::addressof(vec.back()));
}
NontrivialType::ctored = 0; NontrivialType::ctored = 0;
for (int i = 0; i < 120; ++i) { for (int i = 0; i < 120; ++i) {
vec.emplace_back(i); auto& emplaced = vec.emplace_back(i);
EXPECT_TRUE(std::addressof(emplaced) == std::addressof(vec.back()));
} }
EXPECT_EQ(NontrivialType::ctored, 120); EXPECT_EQ(NontrivialType::ctored, 120);
EXPECT_EQ(vec[0].a, 12); EXPECT_EQ(vec[0].a, 12);
......
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