This is the code from C++11 Notes Sample by Scott Meyers,
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&&.
I have some understanding of auto, from which I would say that auto& a1 = x should make type of a1 as int&
Which from Quoted code, seems wrong.
I wrote this small code, and ran under 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
Then I modified line 8 as auto&& a1 = x;, and ran. Same output.
My question : Is auto& equal to auto&&?
If they are different what does auto&& do?
The code is right.
auto&& p = exprmeans the type ofpisT&&whereTwill be inferred fromexpr. The&&here indicates a rvalue reference, so e.g.will infer
T == intand thus the type ofpisint&&.However, references can be collapsed according to the rule:
(This feature is used to implement perfect forwarding in C++11.)
In the case
as
xis an lvalue, an rvalue reference cannot be bound to it, but if we inferT = int&then the type ofpwill becomeint& && = int&, which is an lvalue reference, which can be bound tox. Only in this caseauto&&andauto&give the same result. These two are different though, e.g.is incorrect because
std::move(x)is an rvalue, and the lvalue reference cannot be bound to it.Please read C++ Rvalue References Explained for a walk through.