Initialization of a constant reference with a number [duplicate]
Asked Answered
C

1

78

What is the meaning of the following line? Why is this allowed as 0 is an r-value and not a variable name? What is the significance of const in this statement?

const int &x = 0;
Copperplate answered 15/5, 2018 at 21:35 Comment(0)
C
73

A non-const reference cannot point to a literal. You cannot bind a literal to a reference to non-const (because modifying the value of a literal is not an operation that makes sense) and only l-values can be bound to references to non-const. You can however bind a literal to a reference to const.

The "const" is important. In this case, a temporary variable is created for this purpose and it's usually created on stack.

Copperplate answered 15/5, 2018 at 22:5 Comment(1)
Are you sure that the “temporary variable” is created on the stack? I would have expected that x is pointing to some area in the data segment. Similar how string literals work. If x points onto the stack, the reference could become invalid too early. For example, if you pass the reference as a pointer to some static variable and leave the method. Besides that, if every call of the method would create a new “temporary variable”, I think we wouldn't need to use const. I think const is necessary because the memory area is reused between function calls.Henleyonthames

© 2022 - 2024 — McMap. All rights reserved.