C ++删除指针(可用内存) [英] C++ delete a pointer (free memory)

查看:81
本文介绍了C ++删除指针(可用内存)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

int a = 10;
int * b = &a;
int * c = b;
delete b; // equivalent to delete c;

我想在最后一行理解是正确的吗,delete bdelete c是等效的,并且两者都将释放保存a的内存空间,因此a不再可访问?

Am I correct to understand in the last line, delete b and delete c are equivalent, and that both will free the memory space holding a, thus a is no longer accessible?

推荐答案

程序的行为为未定义.您只能在指向使用new分配的内存的指针上使用 .如果您写过

The behaviour of your program is undefined. You can only use delete on a pointer to memory that you have allocated using new. If you had written

int* b = new int;
*b = 10;
int* c = b;

然后您可以编写 delete b; delete c;释放内存.尽管在delete调用之后不要尝试 derefererence bc,这样做的行为也是未定义.

then you could write either delete b; or delete c; to free your memory. Don't attempt to derefererence either b or c after the delete call though, the behaviour on doing that is also undefined.

这篇关于C ++删除指针(可用内存)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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