C++0x T 运算符+(const T&, T&&) 模式,还需要移动吗?
不久前我被告知,实现二元运算符的通常模式需要在返回中进行最后的移动
。
Matrix operator+(const Matrix &a, Matrix &&b) {
b += a;
return std::move(b);
}
但现在有一个特殊的规则,在 return
中,编译器可能会将返回值视为临时值,这样就没有必要了 - 一个简单的 return b
就可以了够了。
但话又说回来,b
在这个函数中有一个名称,因此,它是一个LValue——这会阻碍编译器将其视为一个temp,并且需要 move
。
最新版本的 C++0x 标准中是否仍然存在这种情况? 我们需要move
来实现上述模式?
Some time ago I was told, that the usual pattern to implement two-ary operators needs a final move
in the return.
Matrix operator+(const Matrix &a, Matrix &&b) {
b += a;
return std::move(b);
}
But now there is the special rule that in a return
the compiler may treat the return value as a temporary, and then this would not be necessary -- a simple return b
would suffice.
But then again, b
has a name in this function, therefore, its an LValue -- which hinders the compiler to m consider it being a temp, and the move
is required.
Is this still the case in the most recent version of the C++0x Standard? We need the move
to implement the above pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在此示例中,您需要显式
std::move
,因为b
不是非易失性自动对象的名称。参考12.8【class.copy】/p31/b1:You need the explicit
std::move
in this example becauseb
is not the name of a non-volatile automatic object. Reference 12.8 [class.copy] /p31/b1:我不确定为什么这个函数按值返回。该函数不应该返回如下所示的 Matrix&& 吗?
这还有一个额外的优点,即 x1 + x2 + x3 + ... + xn 最多创建一个临时值,如果 Matrix 碰巧是堆栈分配的,这一点很重要(因为它不会从移动中获得任何收益)。
我认为签名应该如下所示:
I'm not sure why this function returns by value. Shouldn't this function return a
Matrix&&
like the following?This has the added advantage that
x1 + x2 + x3 + ... + xn
creates at most one temporary, which is important if Matrix happens to be stack allocated (as it then gains nothing from moves).I think the signatures should be like the following: