为什么在删除动态分配的内存后,编译器没有自动将NULL分配给指针变量?
问题描述:
我有一小段代码:
#include <iostream>
using namespace std;
int main()
{
int *p = new int(10);
if(p != NULL)
{
cout<<"Deleted dynamic allocated memory"<<endl;
delete p;
}
if(p == NULL)
{
cout<<"NULL"<<endl;
}
else
{
cout<<"Not NULL"<<endl;
}
return 0;
}
使用delete
运算符删除动态分配的内存后,为什么编译器没有自动将NULL分配给指针(如p = NULL)?
After deleting dynamic allocated memory using delete
operator, Why compilers do not assigned NULL to pointer(like p = NULL) automatically?
答
-
这通常是不必要的,尤其是在编写良好的代码中.
It would often be unnecessary, particularly in well-written code.
它可以隐藏错误.
delete p;
修改其自变量,则在语法上是特质的.
delete p;
would be syntactically idiosyncratic if it modified its argument.
在(1)中,std::unique_ptr
尤其浪费.
On (1) it would be particularly wasteful with std::unique_ptr
.
换句话说,在必要时让程序员负担这项工作是正确的事情.
In other words, burdening the programmer with this job if necessary is the right thing to do.