문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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

The check is not necessary.

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

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top