This question already has an answer here:
- Why doesn't delete set the pointer to NULL? 12 answers
- Why doesn't free(p) set p to NULL? 9 answers
I have small piece of code:
#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;
}
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.
It could hide away bugs.
delete p;
would be syntactically idiosyncratic if it modified its argument.
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.
Because it is extra work (= more clock cycles, less performance), that is usually not needed.
If your design calls for NULLing a pointer to indicate that it no longer points at something useful, you can add code to do that. But that should not be the default, because it can be insufficient and pointless.
NULL pointers don't solve every possible problem:
int *ip = new int;
int *ip1 = ip;
delete ip;
if (ip1)
*ip1 = 3; // BOOM!
And they are often pointless:
struct s {
int *ip;
s() : ip(new int) {}
~s() { delete ip; } // nobody cares if ip is NULL, 'cause you can't see it
};
They are allowed to do so, but it isnt mandatory. I think the reason they dont do it consitently is because anyhow you cant rely on it. For example consider this:
int* a = new int(3);
int* b = a;
delete a;
/// ....
if (b != 0) { /// assume b is either null or points to something valid
std::cout << *b; /// ups
}
来源:https://stackoverflow.com/questions/45142895/why-compilers-do-not-assign-null-to-pointer-variable-automatically-after-deletin