Search code examples
c++referenceconstantsconst-reference

Const reference to a casted int from unsigned int


I am having some trouble understanding the behaviour in this snippet:

unsigned int i = 2;
const int &r = i;
std::cout << r << "\n";
i = 100;
std::cout << r << "\n";

The first print statement gives 2 as I expect, but when I change the value of the referenced variable, it is not reflected in the reference. The second print statement also gives 2, but I think it should give 100?

If I make variable i into type int instead of unsigned int, it works as I expect. What is going on here?

Live example


Solution

  • You can only have a reference to an object of the same type.

    You cannot have an int reference to an unsigned int.

    What is happening here is, essentially:

    const int &r = (int)i;
    

    A new int temporary gets constructed, a new temporary object, and a const reference is bound to it.

    Using your debugger, you should be able to observe the fact that the reference is referring to a completely different object:

    (gdb) n
    6   const int &r = i;
    (gdb) 
    7   std::cout << r << "\n";
    (gdb) p i
    $1 = 2
    (gdb) p &i
    $2 = (unsigned int *) 0x7fffffffea0c
    (gdb) p &r
    $3 = (const int *) 0x7fffffffe9fc
    (gdb) q