Is it safe to delete a NULL pointer?

前端 未结 7 1539
忘掉有多难
忘掉有多难 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.

提交回复
热议问题