何时使用emplace *和何时使用推/插入 [英] When to use emplace* and when to use push/insert

查看:212
本文介绍了何时使用emplace *和何时使用推/插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道对容器上的emplace函数的一般想法(构建新元素inplace)。

我的问题不是它的作用,
,但更像是Effective C ++ 11一个。

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.

什么是决定什么时候使用的好规则(例如,当它涉及 std :: vector
emplace_back()以及何时使用 push_back()插入函数?

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?

推荐答案

emplace_back()该对象从头开始,在它把它放入容器。如果你给它一个预构造的对象,它基本上降级为 push_back()。如果对象复制起来很贵,或者你必须在一个严格的循环中创建很多对象,那么你通常会看到一个区别。

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));

myvector.emplace_back(hrmpf);

对于新代码,我可能会使用 emplace_back 如果我可以(我们仍然主要是我们VS2010在工作,其实现 emplace_back()是一个有点hobbled)。

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).

这篇关于何时使用emplace *和何时使用推/插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆