简体   繁体   English

指针和引用如何保存在内存中

[英]How pointers and references are held in memory

Consider these 2 files: 考虑以下两个文件:

//main1.cpp

int main()
{
    int a = 0;
    int &b = a;
}

//main2.cpp

int main()
{
    int a = 0;
    int *b = &a;
}

And when I compile it with gcc -S option and compare 2 assembler outputs, they were exactly same outputs. 当我用gcc -S选项编译它并比较2个汇编器输出时,它们是完全相同的输出。 So why do some books say that reference variables does not use extra memory? 那么,为什么有些书说引用变量不使用额外的内存呢?

It's unspecified whether or not a reference takes up memory. 引用是否占用内存是不确定的。 If the compiler can determine which object it refers to, then it can simply use the reference as an alternative "name" for that object, with no need for any run-time information. 如果编译器可以确定所引用的对象,则只需将该引用用作该对象的替代“名称”,而无需任何运行时信息。 If it can't, then the reference will need to hold its target's address, just like a pointer. 如果不能,则引用将需要保留其目标的地址,就像指针一样。

Pointers are objects, and so take up memory like any other object. 指针是对象,因此像其他任何对象一样占用内存。 However, optimisations under the "as if" rule mean that objects only have to take up memory if the program's behaviour depends on them doing so; 但是,“好像”规则下的优化意味着对象仅在程序的行为取决于它们这样做时才需要占用内存。 for example, if you print its address. 例如,如果您打印其地址。 So if the compiler can determine which object the pointer points to, then it can replace indirect accesses through the pointer with direct accesses to that object, and perhaps remove the pointer altogether. 因此,如果编译器可以确定指针所指向的对象,那么它可以将对指针的间接访问替换为对该对象的直接访问,甚至可以完全删除指针。

The same optimisation rule means that, in both your examples, all the variables can be removed since they have no effect. 相同的优化规则意味着,在您的两个示例中,所有变量均无效,因此可以将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM