我在以下情况中读过:
int i = 12;
int &a = i;
a不会占用堆栈上的空间,因为它是i的别名;
我的问题是假设它是一个参数
void funct(foo& a , int b)
{
}
创建函数时会占用堆栈空间吗?
答案 0 :(得分:4)
引用或多或少类似于此级别的指针和以下
#include <stdio.h>
#include <stdlib.h>
struct foo{
int val;
};
int funct(foo& a, int b)
{
return a.val;
}
int main(void) {
foo obj;
obj.val = 92;
funct(obj, 22); // 22 is passed by value, obj is passed by reference
return EXIT_SUCCESS;
}
被翻译为:
.Ltext0:
.globl _Z5functR3fooi // funct()
_Z5functR3fooi:
.LFB2:
.cfi_startproc
0000 55 pushq %rbp // some stack bookkeeping
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
0001 4889E5 movq %rsp, %rbp
.cfi_def_cfa_register 6
0004 48897DF8 movq %rdi, -8(%rbp) <-- move the address on the stack frame
0008 8975F4 movl %esi, -12(%rbp) <-- move the value on the stack frame
000b 488B45F8 movq -8(%rbp), %rax <-- get the address from the stack frame
000f 8B00 movl (%rax), %eax <-- use it
0011 5D popq %rbp
.cfi_def_cfa 7, 8
0012 C3 ret
.cfi_endproc
.LFE2:
.globl main
main:
.LFB3:
.cfi_startproc // Main
0013 55 pushq %rbp // Stack bookkeeping
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
0014 4889E5 movq %rsp, %rbp
.cfi_def_cfa_register 6
0017 4883EC10 subq $16, %rsp
.LBB2:
001b C745F05C movl $92, -16(%rbp) <-- save 92 (the entire POD struct) on the stack frame
000000
0022 488D45F0 leaq -16(%rbp), %rax <-- get the pointer to the stack frame where the obj is
0026 BE160000 movl $22, %esi <-- save the value in a register
00
002b 4889C7 movq %rax, %rdi <-- address of the stack frame to the object
002e E8000000 call _Z5functR3fooi // funct() call
00
0033 B8000000 movl $0, %eax
00
.LBE2:
0038 C9 leave
.cfi_def_cfa 7, 8
0039 C3 ret
.cfi_endproc
.LFE3:
.Letext0:
当然要记住,这只是一个实现(gcc是准确的),没有任何优化。 这取决于编译器如何真正起作用。
(由http://assembly.ynh.io/生成的asm)
答案 1 :(得分:2)
根据标准,未指明参考是否需要存储。所以这取决于实施。
引用通常作为汇编中的地址实现。但是,引用既不是指向对象的指针,也不是对象的副本。参考是对象。