C ++引用如何看,内存方面? [英] How does a C++ reference look, memory-wise?

查看:83
本文介绍了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 采用 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 时,会替换为我的地址。因此,基本上,引用内容地址在编译时被解析,并且不需要像在运行时指针那样去引用它。

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.

意味着地址i:

Just to clarify what I mean by the address of i :

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

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

    function(j);
}

在上述代码中, j < 参数将在其堆栈上占用一个位置。也就是说,以 j 作为参数调用 function 时,函数强>。编译器可以且不应该为 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.

say ::


C ++标准8.3.2 / 4:

没有对引用的引用,没有引用数组,
和没有指向引用的指针。

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

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

这篇关于C ++引用如何看,内存方面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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