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

后端 未结 18 840
猫巷女王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:41

    Firstly, there are a lot of existing questions on this and closely related topics, for example Why doesn't delete set the pointer to NULL?.

    In your code, the issue what goes on in (use p). For example, if somewhere you have code like this:

    Foo * p2 = p;
    

    then setting p to NULL accomplishes very little, as you still have the pointer p2 to worry about.

    This is not to say that setting a pointer to NULL is always pointless. For example, if p were a member variable pointing to a resource who's lifetime was not exactly the same as the class containing p, then setting p to NULL could be a useful way of indicating the presence or absence of the resource.

提交回复
热议问题