问题
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