Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ temporary objects and constant reference

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.

like image 415
mindentropy Avatar asked Mar 15 '26 22:03

mindentropy


1 Answers

Wouldn't this cause a lot of subtle bugs

It can cause bugs, but there are probably not a lot of them in the wild.

and why such a thing is allowed as it is not intuitive as a reference?

To allow for binding references to prvalues to not have to copy them.

Take john's example in the comments:

void foo(const int& ri);

foo(3.14159);

In practice, there's little risk here. You call the function and in most scenarios, the value ri references is not expected to change during the call.

If you actually do have a situation where another function may change the referenced value, you can constrain your function to not allow for anything but the exact type you want to bind a reference to to avoid the temporary being created:

void foo(std::same_as<int> auto const& ri);

In reality, most compilers (MSVC with /W2 or higher and icx, clang and gcc with -Wfloat-conversion) are able to warn for this kind of mistake, further minimizing the risk for bugs.

like image 138
Ted Lyngmo Avatar answered Mar 17 '26 12:03

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!