When to use emplace* and when to use push/insert [duplicate]

浪子不回头ぞ 提交于 2019-12-23 02:56:36

问题


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

What are good rules for deciding when to use (for eg when it comes to std::vector) emplace_back() and when to use push_back() and in general emplace* vs "old" insert functions?


回答1:


emplace_back() only really makes sense when you have to construct the object from scratch just before you put it into the container. If you hand it a pre-constructed object it basically degrades into push_back(). You'll mostly see a difference if the object is expensive to copy or you have to create a lot of them in a tight loop.

I tend to replace the following code:

myvector.push_back(ContainedObject(hrmpf));

with

myvector.emplace_back(hrmpf);

if the former shows up on the profiler output. For new code, I'll probably use emplace_back if I can (we still mainly us VS2010 at work and its implementation of emplace_back() is a bit hobbled).



来源:https://stackoverflow.com/questions/17893000/when-to-use-emplace-and-when-to-use-push-insert

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!