I am going through "C++ Primer", and it is mentioned that for the following code:
double dval = 3.14;
const int &ri = dval; //Bind a const int to a plain double object.
The transformation of the code will be:
const int temp = dval; //Create a temporary const int from the double
const int &ri = temp; //bind ri to that temporary
So, if I modify dval, say I set it to dval = 3.0, since ri will be bound to the temporary object, the changed value will not be reflected.
Wouldn't this cause a lot of subtle bugs? Why is such a thing allowed? It is not intuitive as a reference.
void f(const int& ri); f(3.14);because it bindsrito a temporary object. I guess the designers of C++ preferred to allow this construct rather than ban your potential 'subtle bugs'. References as function parameters are common, references as local variables are pretty rare.dval = 3.0would change nothing aboutrieven in the hypothetical case where it was updated. Settingdval = 4.0would be the interesting case as that would have a different corresponding integer conversion.