引用是否占用C ++的内存? [英] Do references take memory in C++?

查看:130
本文介绍了引用是否占用C ++的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读过很多关于这个问题的文章,从中我得到的引用只是别名,它们不占用任何内存.编译器将引用替换为指向变量的地址.

I have read many articles on this question, from which I get that references are only aliases and they don't consume any memory. Compiler replace the reference with the address of pointing variable.

任何人都可以解释下面的示例将发生什么情况.编译器如何与参考ri一起使用?

Can any one explain what will happen for below example. How compiler work with reference ri?

int main()
{  
    int *pi = new int(50);
    int &ri = *pi;
    ri = 30;
    cout << "val = " << ri << " , " << *pi << endl;
}

它给了我输出:

val = 30  ,   30

推荐答案

int *pi = new int(50);

       +----+
pi --> | 50 |
       +----+


int &ri = *pi;

        +----+
pi  --> | 50 |    ri = 50, same as *pi, which is 50
        +----+

ri = 30;      now the contents of what pi points to i.e. *pi is replaced with 30

        +----+
pi  --> | 30 |
        +----+

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

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