Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference type and pointer in disassembly

Why reference types and pointers are same in compiled code?(You can see in third and fourth line). I tried to figure it out but apparently I could not achieve.

If a reference type variable must be initialized at declaration and can not be changed so is there any need to do indirection as in pointers?

int x = 10;

mov dword ptr [x],0Ah

int y = x;

mov eax,dword ptr [x]

mov dword ptr [y],eax

int &i = y;

lea eax,[y]

mov dword ptr [i],eax

int *p = &x;

lea eax,[x]

mov dword ptr [p],eax

p = &i;

mov eax,dword ptr [i]

mov dword ptr [p],eax

x = i;

mov eax,dword ptr [i]

mov ecx,dword ptr [eax]

mov dword ptr [x],ecx

like image 482
zaptir Avatar asked Feb 05 '26 13:02

zaptir


1 Answers

If the referece is known by the compiler to always refer to a single particular object/item, then the compiler could certainly optimize away the indirection.

However, most references are in fact bound at runtime. Even if a particular instance of a reference can't be rebound, different executions of a particular scope or different instances of an object that contains reference members may run with the reference bound to a different object for each of those instances. Using indirection is a conventient way for the compiler to deal with this.

The situation where a reference is only ever bound to a single thing might be relatively infrequent enough that compilers might not look for the optimization - especially since it may be that the optimization wouldn't be a noticable gain in most cases.

Also, I suspect you're not turning on compiler optimizations - using your code and calling various functions with y and i and their addresses, a quick test in VC++ 2005 with optimizations on shows that the compiler is not implementing i as a pointer, but as a true alias for y (ie., whenever passing i or &i, the compiler uses the address of y directly).

If you're looking at the debug output of a compiler, it shouldn't surprise you that it always treats a reference as a pointer behind the scenes.

like image 87
Michael Burr Avatar answered Feb 07 '26 03:02

Michael Burr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!