Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I replace all calls to push_back with emplace_back?

In my C++ application I heavily use STL containers like vector. There are a lot of calls to push_back, and I have been concerned about unnecessary constructions and copy operations.

My application is pretty low-level and I am very concerned about CPU and memory usage. Should I replace all calls to push_back with calls to emplace_back?

I am using Visual Studio 2013.

like image 447
Helge Klein Avatar asked Mar 18 '14 01:03

Helge Klein


2 Answers

I replaced all calls to push_back with calls to emplace_back and noticed the following:

  • RAM usage is reduced by approximately 20% (update: this may have been due to other effects)
  • CPU usage is unchanged
  • The binary is slightly smaller (x64)
  • There were no compatibility problems

Based on these experiences I can highly recommend to make the move from push_back to emplace_back if your project does not need to be backwards-compatible with older compilers.

like image 101
Helge Klein Avatar answered Nov 10 '22 05:11

Helge Klein


It is an almost always rule. You cannot rely on side effect of copy constructors so it should means that skipping it explicitly is the right thing to do, but there is one case.

std::vector<std::unique_ptr<A>> foo;
foo.emplace_back( new A );

If at some time a throw is triggered, like when the vector resize, you end with a leak. So emplace_back is not possible.

If A constructors and the parameter you sent are exception safe, then there is no reason to not use an emplace_back.

like image 26
galop1n Avatar answered Nov 10 '22 04:11

galop1n