0

In C++ Primer 5th Edition 2.4.1 Reference to const, there's a code example that I can't quite understand:

int i = 42;
const int &r1 = i; // we can bind a const int& to a plain int object
const int &r2 = 42; // ok: r1 is a reference to const
const int &r3 = r1 * 2; // ok: r3 is a reference to const
int &r4 = r * 2; // error: r4 is a plain, nonconst reference

On the 3rd line, isn't reference supposed to refer to a variable not a number? If that's the case, why can r2 refer to 42? I also can't understand the comment on the 3rd line.

  • A const lvalue reference(`const int&`) can bind to a *prvalue* `42`. Temporary materialization happens and also lifetime extension. See duplicate: [How references can bind to prvalues?](https://stackoverflow.com/questions/71119987/how-references-can-bind-to-prvalues) – Jason Sep 05 '22 at 08:14
  • A reference refers to an *object*, not to a variable. – molbdnilo Sep 05 '22 at 08:16
  • The comment on the third line has a typo and should say "r2" rather than "r1". – molbdnilo Sep 05 '22 at 08:17
  • Note also that in the comment on line 3, `r1` should be `r2`. That is a **typo** there. – Jason Sep 05 '22 at 08:17

0 Answers0