NULL check before deleting an object with an overloaded delete

前端 未结 11 1715
野性不改
野性不改 2020-12-18 18:24

This came up as one of the code review comments.

Is it a good idea to check for NULL before calling delete for any object?

I do understand delete operator c

相关标签:
11条回答
  • 2020-12-18 18:41

    I would say the questions contains incomplete information. My shop still has a check for NULL before delete in our coding standard, as we still have one compiler/platform configuration that we must support that goes into undefined behavior with the defualt delete operator if it is passed NULL. If the original poster has a simular situation then there is a point to the check for NULL, otherwise, change the coding standard!

    0 讨论(0)
  • 2020-12-18 18:47

    No need to check null. delete operator does chck for null so additional check is not required.

    0 讨论(0)
  • 2020-12-18 18:49

    I would say it is the responsibility of an overloaded delete to behave like you expect delete to behave. That is, it should handle NULL pointers as a no-op.

    And so, when calling an overloaded delete, you should not check for NULL. You should rely on the overloaded delete to be implemented correctly.

    0 讨论(0)
  • 2020-12-18 18:49

    A bit of C++ pedantry: NULL is not a built-in concept. Yes we all know what it means but in C++ before C++0X the null pointer concept is simply the value 0. NULL is usually a platform-specific macro that expands to 0.

    With C++0X we're getting nullptr which is clearer than a plain zero and is not convertible to any integral type except bool, and is a better concept than NULL (or perhaps a better implementation of the concept behind NULL).

    0 讨论(0)
  • 2020-12-18 18:51

    No, don't check for null. The standard says that delete (T*)0; is valid. It will just complicate your code for no benefits. If operator delete is overloaded it's better to check for null in the implementation of the operator. Just saves code lines and bugs.

    EDIT: This answer was accepted and upvoted, yet, in my opinion, it was not very informative. There is one missing piece in all answers here, and, for conscience sake, let me add this last piece here.

    The standard actually says in [basic.stc.dynamic], at least since C++03:

    Any allocation and/or deallocation functions defined in a C++ program, including the default versions in the library, shall conform to the semantics specified in 3.7.4.1 and 3.7.4.2.

    Where the referenced sections, as well as some other places in the standard listed in other answers, say that the semantics of passing a null pointer are a no-op.

    0 讨论(0)
提交回复
热议问题