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?
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.
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