将左值绑定到右值引用,移动变量和函数返回
binding of lvalue into rvalue reference move ctor and return of function
据我所知,将左值绑定到右值引用是无效的。其次,左值表达式可以通过以下事实来识别:它可以以地址操作符(&)
作为前缀如果这两个句子用下面的代码是正确的,我就有点麻烦了:
#include<iostream>
struct Foo
{
Foo(Foo&& other)
{
std::cout << "move ctor called";
}
Foo(const Foo& other)
{
std::cout << "copy ctor called";
}
Foo(){}
};
Foo return_foo()
{
Foo f;
return f;
}
void main()
{
Foo f = return_foo(); // Move ctor is called, but return_foo() is a lvalue ??
std::cin.ignore();
}
我哪里错了
return_foo()
返回一个右值(因为它返回未命名的临时对象)。引用自§3.10/1,强调我的:
一个右值("纯"右值)是一个非xvalue的右值。(示例:调用返回类型不是a的函数的结果Reference是一个右值。字面量的值,如12、7.3e5或True也是一个右值。-end example]
有一个特殊的规则允许将临时值作为右值返回,也就是说,以下是等效的-显式的"我不再需要这个"版本:
T foo()
{
T t(a, b, ...); // constructed somehow
/* ... */
return std::move(t);
}
int main()
{
T t = foo(); // we can move-construct this
}
…隐式版本:
T foo()
{
T t(a, b, ...);
/* ... */
return t; // implicitly allow moving
}
所有这些都发生在返回值优化之后。这意味着按值返回在很多情况下实际上是非常有效的。
相关文章:
- 我应该使我的局部变量常量还是可移动的
- 为什么 std::move 不将默认移动构造函数中的源变量更改为默认值?
- 当变量和参数名称匹配时,移动语义构造失败
- 右值引用和局部变量的移动
- 是否可以通过使用移动/交换 c++11 来延长返回的临时变量的生命周期
- 是否可以将移动的变量标记为不再可用,并在使用它时收到编译器警告?
- 如何初始化非静态模板成员变量从临时工开始,即而无需复制或移动
- 从已移动捕获的 lambda 中重复移动变量
- 变量可以通过C / C 的左或右移动操作变为null
- 如何有效地将底层数据从 std::string 移动到其他类型的变量?
- 移动变量是否有效,可以在 std::move 之后使用
- C++11 是否保证 return 语句中的局部变量将被移动而不是复制?
- 如何在 c++ pytorch 前端 API 中将变量从 GPU 移动到 CPU
- 从类返回可移动成员变量
- 如何将变量移动到 lambda 表达式中
- 用向量替换类新的[]变量-移动、复制运算符
- 使用 c++ 中的 __asm 将 short 类型的变量移动到 EAX 中 (VS 2010)
- 将动态分配的变量移动到向量中
- 如何将' std::vector '成员变量移动到方法的调用方
- 将变量移动到头文件时出现运行时错误