0

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?

Cedric Martens
  • 1,139
  • 10
  • 23
  • Can you explain, in detail, what you meant by "prevented to assign a non-const lvalue reference to an rvalue why"? Nothing in the code attempts to do that. – Sam Varshavchik Jul 15 '22 at 23:54
  • you can't do `int& val_ref = compute();` `cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’ 11 | int& val_ref = compute();` – Cedric Martens Jul 16 '22 at 00:08
  • my understanding is `const int& val_ref` creates a temporary variable, but it cannot be modified. my understanding is also that the rvalue reference creates a temporary variable that can be modified. – Cedric Martens Jul 16 '22 at 00:10
  • References don't "point". They refer to. But `value_copy` cannot be incremented because the `const` in its definition means it is a reference to to a `const int` (i.e. the `const` applies to the `int` itself). A little more formally [going more formal makes my teeth itch, in this case] you have converted the `prvalue` (which refers to the temporary holding the return value from `compute()`) into `lvalue` that refers to a `const int`. – Peter Jul 16 '22 at 00:19

0 Answers0