Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviour between "int &&" and "auto &&"

Tags:

c++

c++11

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?

like image 424
Jorge González Lorenzo Avatar asked Dec 10 '22 19:12

Jorge González Lorenzo


2 Answers

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.

like image 56
Nawaz Avatar answered Dec 13 '22 10:12

Nawaz


int&& is an r-value reference to int. Whereas auto&& is a universal reference.

like image 23
Maxim Egorushkin Avatar answered Dec 13 '22 09:12

Maxim Egorushkin