#vector push_back vs emplace_back

16 messages · Page 1 of 1 (latest)

dull spindle
#

I already know that in push_back a temporary is created and copied after the last element of the vector and in emplace_back object is constructed in place by forwarding arguments.

But with emplace_back objects can also be passed which in turn copy constructs at the end of vector.

So what can be other use case of push_back which cannot be achieved by emplace_back ?

lost mulchBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

lucid notch
#

push_back is all-around simpler by virtue of not being a template, if you're uncomfortable with working with templates and reading the diagnostic errors it's just easier to use

compact copper
#

I personally use push_back when copying or moving, and emplace_back when forwarding args

fathom torrent
#

Given a std::vector<std::vector<int>> v; you can do v.push_back({1, 2, 3, 4, 5});. The emplace_back versions are more complicated because it lacks the type deduction.

dull spindle
fathom torrent
#

v.emplace_back(std::vector<int>{1, 2, 3, 4, 5}); 🤷

#

Actually anything with brace initialization sucks for emplace_back because it doesn't use brace initialization.

#
struct Point {
  int x;
  int y;
};

std::vector<Point> points;
points.push_back({1, 2}); //neat
points.emplace_back(Point{1, 2}); //less neat
dull spindle
fathom torrent
#

They both move.

#

Unnecessarily

#

But what can you do. It's not like the nanosecond matters.

dull spindle
#

I usually use emplace_back when I don't need a copy or more at all.
As per my understanding, normal tasks doesn't matter much if temporary is moved or copied, expect working in like embedded or mobile environment

lost mulchBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.