为什么编译器不会“p = NULL”程序后自动执行“删除p”? [英] Why compilers do not "p = NULL" automatically after programs do "delete p"?
问题描述
我们都知道以下代码是危险的:
{
int * p = new int;
删除p;
删除p;
}
我们也知道如果p == NULL,编译器不会删除p 。
那么为什么编译器不会p = NULL程序后自动删除p?
Hi,
We all know the below codes are dangerous:
{
int *p = new int;
delete p;
delete p;
}
And we also know the compilers do not delete p if p==NULL.
So why compilers do not "p = NULL" automatically after programs do "delete p"?
推荐答案
>那么为什么编译器不会p = NULL在>程序之后自动执行删除p?
因为他们不能。您将不得不以某种方式将p的地址传递给
将p设置为NULL。当然这只是它的一个方面。
>So why compilers do not "p = NULL" automatically after >programs do "delete p"?
Because they can''t. You will have to pass somehow the address of p to
set p to NULL. Of course this is just one aspect of it.
gary写道:
gary wrote:
我们都知道下面的代码是危险的:
{
int * p = new int;
删除p;
删除p;
}
那么为什么编译器不会p = NULL。程序后自动执行删除p?
Hi,
We all know the below codes are dangerous:
{
int *p = new int;
delete p;
delete p;
}
And we also know the compilers do not delete p if p==NULL.
So why compilers do not "p = NULL" automatically after programs do "delete p"?
一个问题就是效率。 ''p = NULL''至少需要一条指令
才能完成。如果你在一个非常深的循环中删除一个点,那么成本可能会很大。
南
One problem is efficiency. ''p = NULL'' at least takes one instruction
to complete. If you delete a point in a very deep loop, the cost could
be huge.
Nan
gary< zw ** @ gawab.com>写道:
gary <zw**@gawab.com> wrote:
我们都知道下面的代码是危险的:
{* / int int * p = new int;
delete p;
delete p;
}
我们也知道如果p == NULL,编译器不会删除p。
那么为什么编译器不会p = NULL程序后自动执行删除p?
Hi,
We all know the below codes are dangerous:
{
int *p = new int;
delete p;
delete p;
}
And we also know the compilers do not delete p if p==NULL.
So why compilers do not "p = NULL" automatically after programs do "delete p"?
Stroustrup在他的FAQ中回答这个问题:
http://www.research.att.com/~bs/bs_f...ml#delete-zero
-
Marcus Kwok
Stroustrup answers this in his FAQ:
http://www.research.att.com/~bs/bs_f...ml#delete-zero
--
Marcus Kwok
这篇关于为什么编译器不会“p = NULL”程序后自动执行“删除p”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!