如果 += 在 return 语句中,为什么不移动对象
Why is an object not moved if += is in the return statement
我从Visual Studio模仿了std::vector::operator+()
。它看起来类似于:
A operator+(const int diff) const {
A temp = *this;
return temp += diff;
}
虽然我有一个移动构造函数,它使用复制构造函数,但是当我使用这个时:
A operator+(const int diff) const {
A temp = *this;
temp += diff;
return temp;
}
它确实移动了。这是为什么?
下面的文章对此进行了解释,但简而言之:
-
- 示例:returns 一个引用,编译器无法确信该值未在别处使用。
-
- 示例:returns 本地创建的值并且可以安全移动。
您也可以通过返回 std::move(temp += diff)
来修复它,但这通常不是首选,因为它会阻止编译器使用 Return 值优化 (RVO).
https://web.mst.edu/~nmjxv3/articles/move-gotchas.html
为什么Visual Studio没有考虑到这一点,我不知道。
我从Visual Studio模仿了std::vector::operator+()
。它看起来类似于:
A operator+(const int diff) const {
A temp = *this;
return temp += diff;
}
虽然我有一个移动构造函数,它使用复制构造函数,但是当我使用这个时:
A operator+(const int diff) const {
A temp = *this;
temp += diff;
return temp;
}
它确实移动了。这是为什么?
下面的文章对此进行了解释,但简而言之:
-
- 示例:returns 一个引用,编译器无法确信该值未在别处使用。
-
- 示例:returns 本地创建的值并且可以安全移动。
您也可以通过返回 std::move(temp += diff)
来修复它,但这通常不是首选,因为它会阻止编译器使用 Return 值优化 (RVO).
https://web.mst.edu/~nmjxv3/articles/move-gotchas.html
为什么Visual Studio没有考虑到这一点,我不知道。