删除指针也会删除它指向的内存吗? [英] Does deleting a pointer delete the memory it's pointing too?

查看:230
本文介绍了删除指针也会删除它指向的内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的指针:

int *test = new int;

然后我创建另一个指向test的指针,如下所示:

And I create another pointer that points to test like so:

int *test2 = test;

然后我删除test2:

delete test2;

这是否意味着它也会删除test的内存,还是我也必须调用delete test?

Does that mean that it will delete the memory of test as well, or would I have to call delete test also?

推荐答案

是的,由于两个指针都指向同一个内存,因此将删除该内存.

Yes, the memory will be deleted freed as both pointers point to the same memory.

此外,test现在将成为悬挂指针(test2也会如此),对其取消引用将导致不确定的行为.

Furthermore, test will now be a dangling pointer(as will test2) and dereferencing it will result in undefined behaviour.

这篇关于删除指针也会删除它指向的内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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