How are references encoded in C++? [duplicate]

核能气质少年 提交于 2019-12-23 06:59:10

问题


int x = 10;
int& y = x;

For this, x is allocated as 2/4/8 bytes on the stack and 00...1010 is written to those bytes. What would the memory layout and its contents look like for y?


回答1:


From the C++11 standard 8.3.2.4 [dcl.ref]

It is unspecified whether or not a reference requires storage

So it may or may not need any storage.




回答2:


Let me quote http://en.cppreference.com/w/cpp/language/reference:

References are not objects; they do not necessarily occupy storage, although the compiler may allocate storage if it is necessary to implement the desired semantics (e.g. a non-static data member of reference type usually increases the size of the class by the amount necessary to store a memory address)




回答3:


From the perspective of C++ languange, it is not defined.

In practice, compilers usually treat references in absolutely the same way as pointers, even though they have many different properties in C++. It means that the address of the referenced variable is physically stored. Perhaps the only assumption that the compiler can make is that the reference is not null. Despite that, I think that you cannot access the address stored in the reference variable in C++ code without taking a pointer first.

Note that the compiler can often optimize reference variable so that you cannot even say where it is in the assembly. And it can do the same to pointer variables.



来源:https://stackoverflow.com/questions/31521116/how-are-references-encoded-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!