通过右值引用返回更有效率? [英] Is returning by rvalue reference more efficient?

查看:177
本文介绍了通过右值引用返回更有效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

Beta_ab&&
Beta::toAB() const {
    return move(Beta_ab(1, 1));
}


推荐答案

Beta_ab&&
Beta::toAB() const {
    return move(Beta_ab(1, 1));
}

这将返回一个悬挂引用,就像Lvalue引用的情况一样。函数返回后,临时对象将被销毁。您应该按值返回 Beta_ab ,如下所示

This returns a dangling reference, just like with the lvalue reference case. After the function returns, the temporary object will get destructed. You should return Beta_ab by value, like the following

Beta_ab
Beta::toAB() const {
    return Beta_ab(1, 1);
}

现在,正确移动一个临时 Beta_ab object放入函数的返回值。如果编译器可以,它将通过使用RVO(返回值优化)完全避免移动。现在,您可以执行以下操作:

Now, it's properly moving a temporary Beta_ab object into the return value of the function. If the compiler can, it will avoid the move altogether, by using RVO (return value optimization). Now, you can do the following

Beta_ab ab = others.toAB();

它会将构造临时变量移动到 ab ,或者做RVO以省略做移动或复制。建议您阅读解释此问题的 BoostCon09 Rvalue参考101 ,以及如何(N)RVO发生

And it will move construct the temporary into ab, or do RVO to omit doing a move or copy altogether. I recommend you to read BoostCon09 Rvalue References 101 which explains the matter, and how (N)RVO happens to interact with this.

返回右值引用的情况将是一个好主意在其他场合。假设你有一个 getAB()函数,你经常在一个临时函数上调用它。使它返回一个对于右值临时值的常量左值引用不是最佳的。您可以像这样实现

Your case of returning an rvalue reference would be a good idea in other occasions. Imagine you have a getAB() function which you often invoke on a temporary. It's not optimal to make it return a const lvalue reference for rvalue temporaries. You may implement it like this

struct Beta {
  Beta_ab ab;
  Beta_ab const& getAB() const& { return ab; }
  Beta_ab && getAB() && { return move(ab); }
};

请注意,在这种情况下 move 可选,因为 ab 既不是本地自动也不是临时右值。现在, ref-qualifier && 表示第二个函数在右值临时值上被调用,进行以下移动, / p>

Note that move in this case is not optional, because ab is neither a local automatic nor a temporary rvalue. Now, the ref-qualifier && says that the second function is invoked on rvalue temporaries, making the following move, instead of copy

Beta_ab ab = Beta().getAB();

这篇关于通过右值引用返回更有效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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