c++ vector emplace_back is faster?

2019-05-04 21:18发布

问题:

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])

回答1:

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.



标签: c++ vector