I am trying to understand constant reference in C++ and I stumbled across this problem:
When I assign double to a const int& and then change the value of the referencing double, the value of my int reference stays constant.
double i = 10;
const int &ref = i;
i = 20;
cout << "i: " << i << endl; // i = 20
cout << "&ref: " << ref << endl; // ref = 10
Whereas while assigning int, the value gets changed.
int i = 10;
const int &ref = i;
i = 20;
cout << "i: " << i << endl; // i = 20
cout << "&ref: " << ref << endl; // ref = 20
What is the reason for this behaviour? My guess is that when assigning double, the implicit conversion to int creates a new object and its reference is then being assigned, however I can't find it written down anywhere.
On the other hand, going from a double to an int requires rounding off. C++ doesn't perform this operation automatically, in order to make sure that you, as the programmer, are aware of the loss of the fractional part of the number.
This can be used in several ways. Examples: Declaring a variable to be const means that its value cannot change; therefore it must be given a value in its declaration: const double TEMP = 98.6; // TEMP is a const double. ( Equivalent: double const TEMP = 98.6; )
But what is the difference between double const and const double ? There is no difference.
In C++, if a const variable is initialized with a pure constant expression, then its value cannot be modified through its pointer even after try to modify, otherwise a const variable can be modified through its pointer.
Even though it looks like, ref isn't a reference to i.
double i = 10;
const int &ref = i; // ***
i = 20;
A reference to an int cannot refer to a double. Therefore, in the marked line, a conversion from a double to an int takes place and the result of conversion is a temporary rvalue. Normaly, they are destroyed when the full expression they were created in ends. But there's a rule in C++ that allows extending the lifetime of a temporary when it is bound to a reference to const. It is extended until the reference dies. For that, the compiler actually allocates some memory for it behind the scenes.
The assignment modifies the original object i, the unnamed temporary stays intact.
When you convert the double to an int, the result is an rvalue of type int. This temporary value is bound to a constant reference variable, and thus the lifetime of the temporary value is extended to that of the reference variable. Changing the original double has no effect on that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With