简体   繁体   中英

c++ vector emplace_back is faster?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM