为什么在删除动态分配的内存后,编译器没有自动将NULL分配给指针变量? [英] Why compilers do not assign NULL to pointer variable automatically after deleting dynamic allocated memory?
本文介绍了为什么在删除动态分配的内存后,编译器没有自动将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.
这篇关于为什么在删除动态分配的内存后,编译器没有自动将NULL分配给指针变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文