在内存方面,C++ 参考看起来如何?

2021-12-24 00:00:00 reference memory-management c++

给定:

int i = 42;
int j = 43;
int k = 44;

通过查看变量地址,我们知道每个地址占用 4 个字节(在大多数平台上).

By looking at the variables addresses we know that each one takes up 4 bytes (on most platforms).

但是,考虑到:

int i = 42;
int& j = i;
int k = 44;

我们会看到变量 i 确实占用了 4 个字节,但是 j 占用了 none 而 k 又占用了堆栈上有 4 个字节.

We will see that variable i indeed takes 4 bytes, but j takes none and k takes again 4 bytes on the stack.

这里发生了什么?看起来 j 在运行时根本不存在.我作为函数参数收到的引用呢?那必须在堆栈上占用一些空间...

What is happening here? It looks like j is simply non-existent in runtime. And what about a reference I receive as a function argument? That must take some space on the stack...

当我们在做的时候 - 为什么我不能定义一个数组或引用?

And while we're at it - why can't I define an array or references?

int&[] arr = new int&[SIZE]; // compiler error! array of references is illegal

推荐答案

凡是遇到引用 j 的地方,都会被替换为 i 的地址.所以基本上引用内容地址是在编译时解析的,不需要像运行时指针那样解引用.

everywhere the reference j is encountered, it is replaced with the address of i. So basically the reference content address is resolved at compile time, and there is not need to dereference it like a pointer at run time.

只是为了澄清我的地址是什么 :

void function(int& x)
{
    x = 10;
}

int main()
{
    int i = 5;
    int& j = i;

    function(j);
}

在上面的代码中,j不应该占用主栈的空间,而是引用x函数 将在其堆栈中占据一席之地.这意味着当使用 j 作为参数调用 function 时,i 的地址 将被压入函数的堆栈强>.编译器可以也不应该在主堆栈上为j保留空间.

In the above code, j should not take space on the main stack, but the reference x of function will take a place on its stack. That means when calling function with j as an argument, the address of i that will be pushed on the stack of function. The compiler can and should not reserve space on the main stack for j.

对于数组部分,标准说 ::

For the array part the standards say ::

C++ 标准 8.3.2/4:

不得有对引用的引用,不得有引用数组,并且没有指向引用的指针.

There shall be no references to references, no arrays of references, and no pointers to references.

为什么引用数组是非法的?

相关文章