我已经知道自动移动不会与从右值引用输入返回值的函数一起工作。但是为什么?
以下是自动移动无法使用的示例代码。
Widget makeWidget(Widget&& w) {
....
return w; // Compiler copies w. not move it.
}
如果函数输入来自按值复制,则自动移动有效。
Widget makeWidget(Widget w) {
....
return w; // Compiler moves w. not copy it.
}
最佳答案
从 C++20 开始,代码应该可以像您预期的那样工作; returning时执行自动移动操作局部变量和参数,它也适用于右值引用(C++20 起)。
If expression is a (possibly parenthesized) id-expression that names a variable whose type is either
- a non-volatile object type or
- a non-volatile rvalue reference to object type (since C++20)
关于c++ - 为什么自动移动不能与从右值引用输入返回值的函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70276951/