Why compilers do not assign NULL to pointer variable automatically after deleting dynamic allocated memory? [duplicate]

China☆狼群 提交于 2019-12-12 09:29:47

问题


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?


回答1:


  1. It would often be unnecessary, particularly in well-written code.

  2. It could hide away bugs.

  3. 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.




回答2:


Because it is extra work (= more clock cycles, less performance), that is usually not needed.




回答3:


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
};



回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!