返回值是否将通过 c++0x 中的右值引用传递?
假设我有一个函数:
typedef std::vector<int> VecType;
VecType randomVector();
int processing()
{
VecType v = randomVector();
return std::accumulate(v.begin(), v.end(), 0);
}
C++0x 是否明确表示将从 randomVector 的返回值中避免虚假副本?或者编译器是否需要实现 RVO?在我看来,值 randomVector()
应该被视为右值,因此应该调用 v 的移动构造函数,但我不完全确定这是真的。
Let's say I have a function:
typedef std::vector<int> VecType;
VecType randomVector();
int processing()
{
VecType v = randomVector();
return std::accumulate(v.begin(), v.end(), 0);
}
Does C++0x specifically say the spurious copy will be averted from the return value of randomVector? Or would a compiler need to implement the RVO? It seems to me like the value randomVector()
should be treated as an rvalue, and thus v's move constructor should be called, but I'm not completely sure this is true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
规则如下:
就像你说的,临时是一个右值,因此选择移动构造函数,因为
13.3.3.2/3
中的规则表明右值引用比左值更好地绑定到右值参考。因此,在决定使用移动构造函数还是复制构造函数时,重载决策将优先选择移动构造函数。允许编译器执行RVO的规则写在
12.8/15
处。The rule is the following
Like you say, the temporary is an rvalue, and thus the move constructor is selected, because of a rule in
13.3.3.2/3
, which says that a rvalue reference binds to an rvalue better than an lvalue reference. In deciding whether to use the move or the copy constructor, overload resolution will therefor prefer the move constructor.The rule that the compiler is allowed to perform RVO is written at
12.8/15
.所有返回值都被视为右值,因此如果编译器在这种情况下没有实现 RVO,则必须使用移动构造函数而不是复制构造函数。
All return values are considered to be
rvalues
so if the compiler doesn't implement RVO on this case it must use the move constructor rather than the copy constructor.