After coming across something similar in a co-worker's code, I'm having trouble understanding why/how this code executes without compiler warnings or errors.
#include <iostream> int main (void) { unsigned int u = 42; const int& s = u; std::cout << "u=" << u << " s=" << s << "\n"; u = 6 * 9; std::cout << "u=" << u << " s=" << s << "\n"; } Output:
u=42 s=42 u=54 s=42 First, I expect the compiler to issue some kind of diagnostic when I mix signed/unsigned integers like this. Certainly it does if I attempt to compare with <. That's one thing that confuses me.
Second, I'm not sure how the second line of output is generated. I expected the value of s to be 54. How does this work? Is the compiler creating an anonymous, automatic signed integer variable, assigning the value of u, and pointing the reference s at that value? Or is it doing something else, like changing s from a reference to a plain integer variable?
const int& s = u;first creates a new temporaryintwhich is then assigned to theconst int&. That's why it won't work with a non-const referenceconstreference can, in some cases, extend the lifetime of a temporary that is assigned to it. Basically, if the temporary was created during the initialization of the reference, in most cases it will extend the lifetime of the temporary to that of the reference. A function local variable is one of those cases.