[英]What does auto&& do?
This is the code from C++11 Notes Sample by Scott Meyers, 这是Scott Meyers撰写的C ++ 11 Notes Sample中的代码,
int x;
auto&& a1 = x; // x is lvalue, so type of a1 is int&
auto&& a2 = std::move(x); // std::move(x) is rvalue, so type of a2 is int&&
I am having trouble understanding auto&&
. 我在理解auto&&
时遇到了麻烦。
I have some understanding of auto
, from which I would say that auto& a1 = x
should make type of a1
as int&
我对auto
有一些了解,从中我可以说auto& a1 = x
应该将a1
类型设为int&
Which from Quoted code, seems wrong. 从引用的代码来看,似乎是错误的。
I wrote this small code, and ran under gcc. 我写了这个小代码,并在gcc下运行。
#include <iostream>
using namespace std;
int main()
{
int x = 4;
auto& a1 = x; //line 8
cout << a1 << endl;
++a1;
cout << x;
return 0;
}
Output = 4 (newline) 5
输出= 4 (newline) 5
Then I modified line 8 as auto&& a1 = x;
然后我将第8行修改为auto&& a1 = x;
, and ran. ,然后跑了。 Same output. 输出相同。
My question : Is auto&
equal to auto&&
? 我的问题: auto&
等于auto&&
吗?
If they are different what does auto&&
do? 如果它们不同, auto&&
做什么?
The code is right. 该代码是正确的。 auto&& p = expr
means the type of p
is T&&
where T
will be inferred from expr
. auto&& p = expr
装置的类型p
是T&&
其中T
将从推断expr
。 The &&
here indicates a rvalue reference, so eg 此处的&&
表示右值引用,例如
auto&& p = 1;
will infer T == int
and thus the type of p
is int&&
. 将推断T == int
,因此p
的类型为int&&
。
However, references can be collapsed according to the rule: 但是,可以根据以下规则折叠引用:
T& & == T&
T& && == T&
T&& & == T&
T&& && == T&&
(This feature is used to implement perfect forwarding in C++11.) (此功能用于在C ++ 11中实现完美的转发。)
In the case 在这种情况下
auto&& p = x;
as x
is an lvalue, an rvalue reference cannot be bound to it, but if we infer T = int&
then the type of p
will become int& && = int&
, which is an lvalue reference, which can be bound to x
. 因为x
是左值,所以不能将右值引用绑定到它,但是如果我们推断T = int&
则p
的类型将成为int& && = int&
,这是一个左值引用,可以绑定到x
。 Only in this case auto&&
and auto&
give the same result. 仅在这种情况下, auto&&
和auto&
给出相同的结果。 These two are different though, eg 但这两个是不同的,例如
auto& p = std::move(x);
is incorrect because std::move(x)
is an rvalue, and the lvalue reference cannot be bound to it. 是不正确的,因为std::move(x)
是一个右值,并且左值引用无法绑定到它。
Please read C++ Rvalue References Explained for a walk through. 请阅读解释的C ++ Rvalue参考 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.