5

If I have a class

class foo {
 public:
  foo() { // spend some time and do something. }
 private:
   // some data here
}

Now I have a vector of foo, I want to put this vector into another vector

vector<foo> input; // assume it has 5 elements
vector<foo> output;

Is there ANY performance difference with these two lines?

output.push_back(input[0])
output.emplace_back(input[0])
WhatABeautifulWorld
  • 3,198
  • 3
  • 22
  • 30

1 Answers1

12

Is there ANY performance difference with these two lines?

No, both will initialise the new element using the copy constructor.

emplace_back can potentially give a benefit when constructing with more (or less) than one argument:

output.push_back(foo{bar, wibble}); // Constructs and moves a temporary
output.emplace_back(bar, wibble);   // Initialises directly

The true benefit of emplace is not so much in performance, but in allowing non-copyable (and in some cases non-movable) elements to be created in the container.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • "any decent compiler will elide the move and produce the same code in both cases" - I don't think this move is eligible for elision. `push_back(T&&)` will move from a temporary to which a reference has been taken. – Steve Jessop Dec 14 '12 at 17:40