参考变量存储在哪里 [英] Where does the reference variable gets stored

查看:64
本文介绍了参考变量存储在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道引用不会占用任何内存,它将指向它所引用的相同内存位置.例如

I know that reference does not take any memory it will point to the same memory location which it is referencing. for eg

int i=10;
int &r = a;

假设 i 指向存储位置1000,因此在这种情况下, r 也将指向存储位置1000.但是在C ++中,每当我们声明一个变量时,它将被存储在内存中的某个位置.在这种情况下, r 指向某个位置,但应通过某种内部表示将其存储在内存中的某个位置.预先感谢.

suppose i points to the memory location 1000 so in this case r will also point to the memory location 1000. But in C++ whenever we are declaring a variable it will get stored in the memory at some location. In this case r is pointing to some location but it should be stored somewhere in memory via some internal representation. thanks in advance.

推荐答案

这是未指定的,这是有充分理由的.真正的答案是:它取决于参考.它可以表示为普通指针,也可以根本不存在.

That is left unspecified, and for good reason. The real answer is: it depends on the reference. It can be represented as a normal pointer, or it may not exist at all.

如果您具有自动存储持续时间的本地函数引用,例如 r :

If you have a function-local reference with automatic storage duration, such as this r:

void foo()
{
  int x[4] = {0, 1, 2, 3};
  int &r = x[1];
  // more code
}

那么它可能根本不会占用任何空间.编译器将简单地将 r 的所有使用作为 x [1] 的别名,然后直接访问该 int .请注意,此类别名样式引用也可以由函数内联产生.

then it will probably not take up any space at all. The compiler will simply treat all uses of r as an alias for x[1], and access that int directly. Notice that such alias-style references can also result from function inlining.

另一方面,如果引用是持久的"或对其他翻译单元(例如数据成员或全局变量)可见,则它必须占用一些空间并存储在某个地方.在这种情况下,它很可能会表示为指针,并且使用该代码的代码将被编译为取消对该指针的引用.

On the other hand, if the reference is "persistent" or visible to other translation units (such as a data member or a global variable), it has to occupy some space and be stored somewhere. In that case, it will most likely be represented as a pointer, and code using it will be compiled to dereference that pointer.

从理论上讲,也可以使用其他选项(例如查找表),但我认为这些选项都不会被任何现实世界的编译器使用.

Theoretically, other options would also be possible (such as a lookup table), but I don't think those are used by any real-world compiler.

这篇关于参考变量存储在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆