c++ - C++ 中变量的别名如何工作

标签 c++

据我所知,对于 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/

相关文章:

c++ - 如何从 if 语句 C++ 中获取值?

C++:简单节点/链表

C++:检查字符串是否是有效的 MD5 十六进制哈希

c++ - 测试Windows应用程序的运行状况

c++ - 使用 xcode 的 ncurses.h 库中的 initscr() 函数错误

c++ - 我可以用 Cython 覆盖 Python 中的 C++ 虚函数吗?

c++ - C i2c芯片读取MCP9800突然开始失败

c++ - C 代码转换为 C++ sha1 问题

c++ - OLE 日期时间到 Posix_time

c++ - 来自第三类对象 C++ 的垃圾值