6

Hello i'm trying to figure out this thing..

Say i have this code.

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

Then once I've declared the second line as a const the compiler doesn't complain anymore.

const double& b = a; //Correct.

what is really going on behind the scene, why const solves the problem.

vlad
  • 4,748
  • 2
  • 30
  • 36
Wagdi Kala
  • 63
  • 5

2 Answers2

7

An int needs to be converted to double first. That conversion yields a prvalue temporary and these can't bind to references to non-const.

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

{
    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 wondering what a prvalue is, here's a nice SO thread about value categories.

Community
  • 1
  • 1
jrok
  • 54,456
  • 9
  • 109
  • 141
6

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

James Kanze
  • 150,581
  • 18
  • 184
  • 329