Why, as soon as I declare a link as a constant, can it accept different types of data?

Hi, I'm trying to figure this thing out.

Say I have this code.

int a = 5; double& b = a; //Error. 

Then, as soon as I declare the second line as const, the compiler no longer complains.

 const double& b = a; //Correct. 

what really happens behind the scenes, why const solves the problem.

+6
source share
2 answers

What happens behind the scenes is the implicit conversion of int to double. The result of an implicit conversion is not an lvalue, so it cannot be used to initialize a non-constant reference.

+6
source

And int must first be converted to double . This conversion gives a temporary prvalue, and they cannot bind to non-const references.

A reference to const will extend the lifetime of a temporary object that would otherwise be destroyed at the end of the expression in which it was created.

 { int a = 0; float f = a; // a temporary float is created here, its value is copied to // f and then it dies const double& d = a; // a temporary double is created here and is bound to // the const-ref } // and here it dies together with d 

If you're interested in what prvalue is, here is a good SO thread on value categories.

+7
source

Source: https://habr.com/ru/post/951906/


All Articles