vector.push_back右值和复制删除 [英] vector.push_back rvalue and copy-elision

查看:333
本文介绍了vector.push_back右值和复制删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将这样的临时对象 push_back 转换成 vector

I push_back a temporary object into a vector like this,

vector<A> vec;
vec.push_back(A("abc"));

编译器将使用复制删除来构造临时 A( abc )直接放入 vector 中,这样 A 的副本ctor不会将临时对象推入 vec 时被触发。

will the compiler apply copy-elision to construct the temporary A("abc") directly into the vector, so that A's copy ctor won't be triggered when pushing the temporary object into vec.

推荐答案

如果有一个支持rvalue引用的编译器,它将被移到向量中,这有时很便宜。

If you have a compiler that supports rvalue references, it will be moved into the vector, which is sometimes quite cheap.

一种替代方法是直接在向量中构造对象,可以使用 vec.emplace_back( abc); 完成。

An alternative to that is to directly construct the object in the vector, which can be done with vec.emplace_back("abc");. This only invokes one constructor.

这两个都是C ++ 11特性。此处不允许进行复制省略,因此如果没有这些功能,仍将复制。

Both of these are C++11 features. Copy elision is not allowed here, so without those features the copy will still be made.

但是,如果复制构造函数没有明显的副作用(不应该这样做)。无论如何,智能编译器仍然可以执行这种优化,因为按原样规则允许进行任何优化,从而产生相同的可观察行为。不过,我不知道当前是否有编译器会这样做。如果不是这样,我怀疑有人会花精力添加这种优化,因为右值引用消除了这种需要。

However, if the copy constructor has no observable side-effects (which it shouldn't have anyway), a smart compiler may still perform that optimisation, because the "as-if" rule allows any optimisation that results in the same observable behaviour. I don't know if any current compiler does that, though. If not, I doubt anyone will spend the effort to add such an optimisation because rvalue references put an end to that need.

这篇关于vector.push_back右值和复制删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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