You can have an lvalue reference on an rvalue, but the lvalue must be const. Look at this simple program:
#include <iostream>
int compute()
{
return 7*4;
}
int main(int a, char**b)
{
int val_copy = compute();
const int& val_ref = compute();
int&& val_rval_ref = compute();
std::cout << val_copy << " " << val_ref << " " << val_rval_ref << std::endl;
val_copy++;
//val_ref++ error because it's const
val_rval_ref++;
std::cout << val_copy << " " << val_ref << " " << val_rval_ref << std::endl;
return 0;
}
Output (C++17):
28 28 28
29 28 29
both the const&
and the rvalue ref point to an rvalue created by the function compute()
. Although, we are prevented to assign a non-const lvalue reference to an rvalue why? It doesn't really make sense to me to have an lvalue reference to an rvalue unless a temporary storage is created, but if a temporary storage is created, why can't we just change it like we do with a regular r-value reference?