Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't `auto&` bind to a volatile rvalue expression?

Consider the below code:

int main()
{
  int i{};
  auto& c = static_cast<const int&&>(i);    // (1)
  auto& v = static_cast<volatile int&&>(i); // (2)
}

While (1) compiles successfully, (2) is not accepted:

error: volatile lvalue reference to type 'volatile int' cannot bind to a temporary of type 'volatile int'

Why can't auto become a volatile int?

Why can auto& become a const int and bind to const int&&? Is it because auto& actually binds to a temporary object that is created on the right hand side of assignment? But then, why auto& p = 1; doesn't work?

like image 845
Marc Andreson Avatar asked Mar 14 '23 12:03

Marc Andreson


1 Answers

This is not about auto, but about binding temporaries to a non-const reference.

In the first case you get a const int&, which is ok. I the second case, a volatile int& will not bind to the temporary.

like image 123
Bo Persson Avatar answered Mar 23 '23 17:03

Bo Persson