Initialization of a constant reference with a number

C++ReferenceConstantsRvalue Reference

C++ Problem Overview


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;

C++ Solutions


Solution 1 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3112666View Question on Stackoverflow
Solution 1 - C++user3112666View Answer on Stackoverflow