Deleting a null pointer [duplicate]

放肆的年华 提交于 2019-12-08 20:38:11

问题


Possible Duplicate:
Is there any reason to check for a NULL pointer before deleting?

I often see the following in code:

if(pointer)
    delete pointer;

To my understanding it is safe to delete a null pointer, so what is the point of this check?


回答1:


delete will check if the pointer is NULL for you, so you're right that the check isn't needed.

You might also see that some people set the pointer to NULL after it's deleted so that you don't do anything stupid like try and use memory that is no longer yours or stop you from deleting the pointer twice, which will cause an error.




回答2:


While it is safe now, it wasn't always :-) so it's likely habitual. Also there are other consequences to delete. 1) if you are using a specialized memory manager and overriding new and delete operators, then you may very well have to do a check Operator Delete for more details




回答3:


The check is not necessary.

The documentation states that delete will "deallocate the memory block pointed by ptr (if not-null)"




回答4:


Most people do this because they usually have error handling otherwise (other than that I don't really see the point of doing the check). In some instances they do it to check that they are freeing something and not accidentally changing a pointer somewhere and causing a memory leak by not freeing it. free(NULL); should work in all cases and not error out so unless there's error handling involved you can remove the if statement and just do the free.



来源:https://stackoverflow.com/questions/8004495/deleting-a-null-pointer

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