Is it safe to delete a NULL pointer?

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

Is it safe to delete a NULL pointer?

And is it a good coding style?

7条回答
  •  [愿得一人]
    2020-11-22 07:11

    Yes it is safe.

    There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.


    Since the previous sentence has caused confusion, an example — which isn't exception safe — of what is being described:

    void somefunc(void)
    {
        SomeType *pst = 0;
        AnotherType *pat = 0;
    
        …
        pst = new SomeType;
        …
        if (…)
        {
            pat = new AnotherType[10];
            …
        }
        if (…)
        {
            …code using pat sometimes…
        }
    
        delete[] pat;
        delete pst;
    }
    

    There are all sorts of nits that can be picked with the sample code, but the concept is (I hope) clear. The pointer variables are initialized to zero so that the delete operations at the end of the function do not need to test whether they're non-null in the source code; the library code performs that check anyway.

提交回复
热议问题