c++ - 为什么自动移动不能与从右值引用输入返回值的函数一起使用?

标签 c++ copy-elision

我已经知道自动移动不会与从右值引用输入返回值的函数一起工作。但是为什么?

以下是自动移动无法使用的示例代码。

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)

LIVE

关于c++ - 为什么自动移动不能与从右值引用输入返回值的函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70276951/

相关文章:

c++ - OpenGL 天空盒不显示

c++ - 使用 CodeBlocks 忽略在 C++ 中调用 main 函数

c++ - 中级 C++ 开发人员的棘手面试问题

C++ OpenGL Cube 没有出现在屏幕上

c++ - 复制省略导致不同的结果

c++ - 在 C/C++ 中将 int* 转换为 int(*)[n]

C++ 优化 : avoid a copy operation

c++ - gcc 和 clang 都省略了下面代码段中对移动构造函数的调用。这个对吗?

c++ - 什么是复制省略和返回值优化?

c++ - 保证复制省略和返回类型的前向声明