简体   繁体   English

C ++ 11 - 右值引用变量

[英]C++ 11 - rvalue reference variables

What is the difference between 有什么区别

int a = 42;

and

int&& rvr = 42;

?

a is obviously an lvalue , but rvr is also an lvalue since it is a named variable, so can these expressions be considered exactly equivalent, and if not, in which scenarios the int&& declaration is preferred? a显然是一个lvalue ,但是rvr也是一个lvalue因为它是一个命名变量,所以这些表达式可以被认为是完全等价的,如果不是,在哪种情况下int&&声明是首选的?

They're not exactly equivalent. 它们并不完全等同。 You're right that both variables are lvalues, but for most types, initialisation of the form 你是对的,两个变量都是左值,但对于大多数类型,都是表格的初始化

T a = b;

creates a temporary T object, and then constructs a from that temporary object. 创建一个临时T对象,然后从该临时对象构造a That temporary object may be elided, but it still requires the appropriate constructors to be available. 可以省略该临时对象,但仍需要适当的构造函数。

T &&a = b;

on the other hand, binds a directly to b , but requires b to be an rvalue. 在另一方面,结合a直接到b ,但需要b是一个rvalue。 So: 所以:

int a = 3;
// int&&b = a; // error: && cannot bind to lvalues
int b = a; // okay

struct S { S(const S &) = delete; };
S f();
// S s = f(); // error: no copy or move constructor available
S&&s = f(); // okay

And more simply, decltype will also give different results for references. 更简单地说, decltype也会为引用提供不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM