Is it good practice to NULL a pointer after deleting it?

后端 未结 18 876
猫巷女王i
猫巷女王i 2020-11-22 11:28

I\'ll start out by saying, use smart pointers and you\'ll never have to worry about this.

What are the problems with the following code?

<         


        
18条回答
  •  心在旅途
    2020-11-22 11:51

    Let me expand what you've already put into your question.

    Here's what you've put into your question, in bullet-point form:


    Setting pointers to NULL following delete is not universal good practice in C++. There are times when:

    • it is a good thing to do
    • and times when it is pointless and can hide errors.

    However, there is no times when this is bad! You will not introduce more bugs by explicitly nulling it, you will not leak memory, you will not cause undefined behaviour to happen.

    So, if in doubt, just null it.

    Having said that, if you feel that you have to explicitly null some pointer, then to me this sounds like you haven't split up a method enough, and should look at the refactoring approach called "Extract method" to split up the method into separate parts.

提交回复
热议问题