19

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

KKOrange
  • 590
  • 4
  • 14

2 Answers2

33

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
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
9

The second print statement also gives 2, but I think it should give 100?

Because a temporary int is created here.

For const int &r = i;, i (unsigned int) needs to be converted to int at first, means a temporary int will be created and then be bound to r (temporary could be bound to lvalue reference to const), it has nothing to do with the original variable i any more.

If I make variable i into type int instead of unsigned int, it works as I expect.

Because no conversion and temporary is needed, i could be bound to r directly.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405