C ++删除指针(可用内存) [英] C++ delete a pointer (free memory)
问题描述
考虑以下代码:
int a = 10;
int * b = &a;
int * c = b;
delete b; // equivalent to delete c;
我想在最后一行理解是正确的吗,delete b
和delete 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 b
或c
,这样做的行为也是未定义.
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屋!