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;
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;
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.
© 2022 - 2024 — McMap. All rights reserved.
x
is pointing to some area in the data segment. Similar how string literals work. Ifx
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 useconst
. I thinkconst
is necessary because the memory area is reused between function calls. – Henleyonthames