Is it safe to delete a NULL pointer?

前端 未结 7 1414
忘掉有多难
忘掉有多难 2020-11-22 06:51

Is it safe to delete a NULL pointer?

And is it a good coding style?

相关标签:
7条回答
  • 2020-11-22 06:55

    From the C++0x draft Standard.

    $5.3.5/2 - "[...]In either alternative, the value of the operand of delete may be a null pointer value.[...'"

    Of course, no one would ever do 'delete' of a pointer with NULL value, but it is safe to do. Ideally one should not have code that does deletion of a NULL pointer. But it is sometimes useful when deletion of pointers (e.g. in a container) happens in a loop. Since delete of a NULL pointer value is safe, one can really write the deletion logic without explicit checks for NULL operand to delete.

    As an aside, C Standard $7.20.3.2 also says that 'free' on a NULL pointer does no action.

    The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

    0 讨论(0)
  • 2020-11-22 06:55

    It is safe unless you overloaded the delete operator. if you overloaded the delete operator and not handling null condition then it is not safe at all.

    0 讨论(0)
  • 2020-11-22 07:01

    To complement ruslik's answer, in C++14 you can use this construction:

    delete std::exchange(heapObject, nullptr);
    
    0 讨论(0)
  • 2020-11-22 07:07

    I have experienced that it is not safe (VS2010) to delete[] NULL (i.e. array syntax). I'm not sure whether this is according to the C++ standard.

    It is safe to delete NULL (scalar syntax).

    0 讨论(0)
  • 2020-11-22 07:08

    delete performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete (helps avoiding double deletion and other similar memory corruption problems).

    I'd also love if delete by default was setting the parameter to NULL like in

    #define my_delete(x) {delete x; x = NULL;}
    

    (I know about R and L values, but wouldn't it be nice?)

    0 讨论(0)
  • 2020-11-22 07:09

    Deleting a null pointer has no effect. It's not good coding style necessarily because it's not needed, but it's not bad either.

    If you are searching for good coding practices consider using smart pointers instead so then you don't need to delete at all.

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