Creating lvalue reference to a non-modifiable lvalue is not allowed and raises compilation error, as following will not work.
const int value{1};
int &ref{value};We can achieve this by creating reference using const as shown below:
const int value{1};
const int &ref{value};This reference is called lvalue reference to a const value or const reference.
Const reference can be used to reference both const and non-const lvalues.
Tip
Favor using const references unless modification to object being referenced is required.
Also, this can be used to reference rvalues as shown below:
const int &ref2{5};In above example, compiler creates a temporary object for rvalue 5 and creates reference to that temporary object.
Const reference to different types
Lvalue reference to a const can be bound to an lvalue of another type only when it can be implicitly converted to reference type. If conversion is possible, compiler creates a temporary object with converted value and binds the references to that temporary object.
For example,
const double &ref5{5};This will compile successfully.
Now consider another example,
int value{5};
const double &ref{value};
value = value - 1;
std::cout << value << ref << "\n";What should be the expected output of this program, 44? It gives 45 as result. value is changed to 4 but ref is still referencing a temporary object with value 5.