When to use emplace * and when to use push / insert

I know a general idea of ​​emplace functions on containers ("create a new inplace element").
My question is not what it does, but more like efficient C ++ 11.

What are good rules for deciding when to use (for example, when it comes to std::vector ) emplace_back() and when to use push_back() and generally insert the ems * vs "old" insertion functions?

+1
source share
1 answer

emplace_back() really makes sense when you need to build an object from scratch before you put it in a container. If you pass it a pre-constructed object, it basically degrades into push_back() . Basically you will see the difference if the object is expensive to copy, or you need to create a lot of them in a narrow loop.

I want to replace the following code:

 myvector.push_back(ContainedObject(hrmpf)); 

with

 myvector.emplace_back(hrmpf); 

if the first is displayed at the output of the profiler. For the new code, I will probably use emplace_back if I can (we still mostly use VS2010 at work, and its implementation of emplace_back() bit hobbled).

+2
source

Source: https://habr.com/ru/post/972520/


All Articles