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.
I replaced all calls to push_back
with calls to emplace_back
and noticed the following:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With