In C++11, if I try to do this:
int x = 5;
int && y = x;
It will fail to compile, with an error telling that an r-value reference cannot bind to an lvalue.
However if I do:
int x = 5;
auto && y = x;
It compiles with no errors. Why is it happening? I tried to get the type of y
but typeid()
takes away the reference attributes. Does auto &&
automatically collapses to a &
or &&
depending on what is being assigned?
In the first case int && y
, the variable y
can bind to only rvalue which x
is not.
In the second case auto && y
however, the variable y
can bind to anything, as the type of y
would be deduced anyway — and reference-collapsing will be applied accordingly — which is why your code compiles:
auto && y = x;
Since x
is an lvalue, auto
is deduced to be int&
, hence it becomes:
int& && y = x;
and after reference-collapsing, it becomes:
int & y = x;
which is fine.
To understand it in more detail, read about:
Universal Reference (or Forwarding Reference, as it has been proposed to improve the terminology)
Reference Collapsing
Hope that helps.
int&&
is an r-value reference to int
.
Whereas auto&&
is a universal reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With