I wanted to see how calling by-reference differs from by-pointer in C++.
However, the g++ compiler (using -O0 -S) produces identical code.
I tried 'tricking' the compiler in producing some sort of difference using all sorts of contrived constructs, but it seems more clever than I am.
Is there a way into turning off all cleverness in gcc so I can understand the implementation of references in assembly?
[Edit]
/* Testing assembly representation of ref/pointer/by-value parameters */
int byRef(int &value, int value2) {
value = value2;
return value;
}
int byPtr(int * value, int value2) {
*value = value2;
return *value;
}
int main(int argc, char * argv[]) {
int value = 5;
byRef(value, value);
byPtr(&value, value);
}
call ___main
movl $5, -4(%ebp)
movl -4(%ebp), %eax
movl %eax, 4(%esp)
leal -4(%ebp), %eax
movl %eax, (%esp)
call __Z5byRefRii
movl -4(%ebp), %eax
movl %eax, 4(%esp)
leal -4(%ebp), %eax
movl %eax, (%esp)
call __Z5byPtrPii
movl $0, %eax
No difference here either.. is there an easy way to trigger the semantic reuse?
There is not much more to understand, really.
Reference are pointers, and references are not pointers.
More correctly, references are of course not pointers at all, they are aliases. Which means that semantically, they are the same variable, just under a different name. This means that the compiler can often do clever renaming tricks to entirely optimize passing the references at all.
Sometimes, it still has to pass the reference somehow, and then that usually happens via a pointer (this is not a requirement, but happens to be the one technique that fits). The only observable difference to a pointer, under the hood, will be that a reference can't be null, and the compiler knows that (though, if you are malicious enough, you can create a null reference).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With