Different behavior between "int &&" and "auto &&"

In C ++ 11, if I try to do this:

int x = 5;

int && y = x;

It will not be able to compile with an error indicating that the r-value reference cannot be bound to an lvalue.

However, if I do this:

int x = 5;

auto && y = x;

It compiles without errors. Why is this happening? I tried to get the type y, but typeid()removes the reference attributes. auto &&automatically collapses in &or &&depending on what is assigned?

+4
source share
3 answers

In the first case, the int && yvariable ycan only be associated with an rvalue, for which it xdoes not.

auto && y y , y — - — :

auto && y = x;

x lvalue, auto int&, :

int& && y = x;

:

int & y = x;

.


, :

  • ( , )

, .

+8

int&& r-value int. auto&& .

+2

In the second example auto(c auto&&) there will be everything that would make the code correct. In this case, it int& &&is correct, since it int& &&collapses into int&- thus, everything works well.

+2
source

Source: https://habr.com/ru/post/1619536/


All Articles