据我所知,对于 int a;
编译器将在堆栈中分配一个内存段,对于 int *p;
编译器也会在堆栈中分配一个内存段,但这里p
只能指向integer
变量的地址。
在 C++ 中,我们有一个名为 alias
(又名“引用”)的概念,例如 int &x=a;
,这意味着 x
将开始工作就像a
。
我的问题是编译器是否也为 x
分配任何单独的内存段,或者编译器只会将 x
视为 a
;我的意思是编译器会为两者分配相同的地址吗?
最佳答案
我正在对我的问题进行一些研究,我得到了答案,但它让我感到惊讶。
别名.cpp
int main()
{
int a=5;
int &x=a;
int y=a+x;
}
使用g++ -S alias.cpp生成的部分汇编代码
alisa.s
subl $16, %esp
movl $5, -12(%ebp) //moving 5 to a
leal -12(%ebp), %eax // loading address of a to eax register
movl %eax, -4(%ebp) // moving address of a to -4(%ebp) this for x
movl -4(%ebp), %eax // moving the value of x that is address of a to eax
movl (%eax), %edx // moving the value of the address pointed by eax to edx
movl -12(%ebp), %eax // moving the value of a to eax
addl %edx, %eax // adding edx and eax
另一个文件alias2.cpp,这里我使用指针而不是别名。
int main()
{
int a=5;
int *x=&a;
int y=a+*x;
}
对应的汇编代码,alias2.s
subl $16, %esp
movl $5, -12(%ebp)
leal -12(%ebp), %eax
movl %eax, -4(%ebp)
movl -4(%ebp), %eax
movl (%eax), %edx
movl -12(%ebp), %eax
addl %edx, %eax
我们可以看到,两个不同的代码块生成的两个汇编文件是相同的。这意味着编译器内部使用与指针变量相同的引用变量,唯一的区别是管理/编写代码的方式。
关于c++ - C++ 中变量的别名如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22110678/