bob said:
How does passing by reference work behind the scenes?
Does the compiler secretly pass in a pointer to the object?
Yes. Have a look at the results of the compilation (without optimization) of
the two programs below see that there is no real difference between them:
// ref.cpp
void f(int& a) {
}
int main() {
int a;
f(a);
}
// ptr.cpp
void f(int* a) {
}
int main() {
int a;
f(&a);
}
$ gcc -O0 -S ref.cpp
$ gcc -O0 -S ptr.cpp
$ diff -u ref.s ptr.s
--- ref.s 2013-08-23 21:30:03.507175417 +0200
+++ ptr.s 2013-08-23 21:18:30.727740110 +0200
@@ -1,8 +1,8 @@
- .file "ref.cpp"
+ .file "ptr.cpp"
.text
- .globl _Z1fRi
- .type _Z1fRi, @function
-_Z1fRi:
+ .globl _Z1fPi
+ .type _Z1fPi, @function
+_Z1fPi:
.LFB0:
.cfi_startproc
pushq %rbp
@@ -16,7 +16,7 @@
ret
.cfi_endproc
.LFE0:
- .size _Z1fRi, .-_Z1fRi
+ .size _Z1fPi, .-_Z1fPi
.globl main
.type main, @function
main:
@@ -30,7 +30,7 @@
subq $16, %rsp
leaq -4(%rbp), %rax
movq %rax, %rdi
- call _Z1fRi
+ call _Z1fPi
movl $0, %eax
leave
.cfi_def_cfa 7, 8
$ cat ptr.s
.file "ptr.cpp"
.text
.globl _Z1fPi
.type _Z1fPi, @function
_Z1fPi:
..LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movq %rdi, -8(%rbp)
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
..LFE0:
.size _Z1fPi, .-_Z1fPi
.globl main
.type main, @function
main:
..LFB1:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
leaq -4(%rbp), %rax
movq %rax, %rdi
call _Z1fPi
movl $0, %eax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
..LFE1:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3"
.section .note.GNU-stack,"",@progbits