0

I have not deeply understood the reference type in c++. So I wrote a tiny piece of code:

int a = 10;
int& b = a;

cout << "a: " << a << endl;
cout << "b: " << b << endl;

cout << "&a: " << &a << endl;
cout << "&b: " << &b << endl;

the output is:

a: 10
b: 10
&a: 0x7ffebd76ac6c
&b: 0x7ffebd76ac6c

And I noticed, without surprise, that a's and b's addresses are the same. Then I disassembled to find out how actually the reference is considered for the compiler. Here the code:

 40096e:    c7 45 dc 0a 00 00 00    mov    DWORD PTR [rbp-0x24],0xa
 400975:    48 8d 45 dc             lea    rax,[rbp-0x24]
 400979:    48 89 45 e0             mov    QWORD PTR [rbp-0x20],rax

If I'm correct, rbp-0x24 refers to the variable a, whereas rbp-0x20 refers to the variable b. But my doubt is: if after this three lines (and if I haven't done mistakes)

[rbp-0x20] = rbp-0x24

how could it be possible that both the variables' addresses are the same?

Marco Luzzara
  • 5,540
  • 3
  • 16
  • 42
  • 6
    A compiler can implement references in any way it sees fit. The C++ standard has no say on how references are implemented. The only thing that the compiler must do is make references *behave* according to the standard. – PaulMcKenzie Jan 03 '17 at 17:48
  • I think you've believed that references are something "concrete" and have an address, just as other variables do. That isn't the case with references -- what you outputted is the address of what the reference is referring to. – PaulMcKenzie Jan 03 '17 at 17:55
  • Now it's clear, thank you. – Marco Luzzara Jan 03 '17 at 18:10
  • Once you run code through an optimizing compiler, all assumptions you might make become invalid. It should not be at all surprising that it collapses these two identical things into the same representation. Looking at the disassembly is not a good way to understand how the *C++ language* works. The high-level constructs don't make it down this far. – Cody Gray - on strike Jan 03 '17 at 19:01

0 Answers0