NULL check before deleting an object with an overloaded delete

前端 未结 11 1797
野性不改
野性不改 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:32

    No need to check for NULL prior to deleting. If someone has overloading delete with something that does not behave in a standard way then that's the real problem. No-one should take lightly the task of overloading delete and should always support expected behaviour such as checking for NULL and taking no action.

    However, for what it's worth, you should always remember to assign zero to any pointer that you've just deleted, unless for example you are about to delete the pointer as well:

    void MyObj::reset()
    {
        delete impl_;
        impl_ = 0;    // Needed here - impl_ may be reused / referenced.
    }
    
    MyObj::~MyObj()
    {
        delete impl_; // No need to assign here as impl_ is going out of scope.
    }
    

提交回复
热议问题