了解引用与指针.为什么这样做? [英] Understanding references vs. pointers. Why does this work?

查看:83
本文介绍了了解引用与指针.为什么这样做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,通过一系列SO问题,我变得对我的理解只有很少的了解.指针,引用和值.

It has become apparent through a series of SO questions today that I have only a poor understanding of the true nature of pointers, references, and values.

考虑以下代码:

int* p = new int(3);
int& r = *p;

cout << " p = " << p << "\t*p = " << *p << endl;
cout << "&r = " << &r << "\t r = " << r << endl;

delete p;

cout << "&r = " << &r << "\t r = " << r << endl;

int v = 4;
r = v;

cout << "&r = " << &r << "\t r = " << r << endl;

此输出为

 p = 0x1001000b0    *p = 3
&r = 0x1001000b0     r = 3
&r = 0x1001000b0     r = 3
&r = 0x1001000b0     r = 4

我不明白的是为什么第二次打印引用的值时不会出错.与参考值对应的指针已被删除.在我的上一个问题中,我几乎使自己相信,任何r = x之类的陈述都会在中复制x r所引用的值的位置.但是,如果是这种情况,那么p&r将是不同的地址,对吗?如果我已经在0x100100b0上调用了delete,那么如何继续使用它?

The thing I don't understand is why the second time I print the value of the reference that I don't get an error. The pointer corresponding to the value of the reference has already been deleted. From my previous question, I had almost convinced myself that any statement such as r = x makes a copy of x in the place of the value that r refers to. However, if this was the case then the p and &r would be different addresses, right? If I've already called delete on 0x100100b0, then how can I keep using it?

是非题:引用与地址值的别名一样.

是非题:如果您删除一个指向与引用值相同的地址的指针(如上所述),则不会发生未定义的行为,并且只要有一个,就不会覆盖该地址.参考存在.

推荐答案

即使没有出现错误,结果仍然不确定.未定义的行为意味着任何事情都可能发生,包括您的程序似乎可以继续正常运行.

Even though you don't get an error, the results are still undefined. Undefined behavior means anything can happen, including your program appearing to continue to work correctly.

引用与地址中的值的别名一样.

A reference is the same thing as an alias to the value at an address.

这是正确的.说引用是对象的别名(而不是值)更正确.

This is effectively true. It would be more correct to say that a reference is an alias for an object (not a value).

如果您删除指向与引用值所在地址相同的地址的指针(如上所述),则不会发生未定义的行为,

If you delete a pointer to the same address as a referenced value resides, (as I do above), then no undefined behavior will occur,

这也是事实.在尝试使用引用之前,没有定义的行为.当您尝试使用引用时(例如,通过&r),您将获得未定义的行为.

This is also true. There is no defined behavior until you attempt to use the reference. When you attempt to use the reference (for example, via &r), you get undefined behavior.

如果在销毁对象后再也没有尝试使用引用,则不会有未定义的行为.

If you never attempt to use the reference after you destroy the object, there is no undefined behavior.

只要引用存在,没有人会覆盖该地址.

no one will ever overwrite that address as long as the reference exists.

否,这是不正确的.一旦对象被销毁,对其的任何引用或指针都是无效且不可用的.如果您尝试使用指针或对销毁对象的引用,则结果是不确定的.

No, this is not correct. As soon as the object is destroyed, any references or pointers to it are invalid and unusable. If you attempt to use a pointer or reference to a destroyed object, the results are undefined.

这篇关于了解引用与指针.为什么这样做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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