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

守給你的承諾、 提交于 2019-12-04 20:51:29
  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.

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