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

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

    Explicitly nulling after delete strongly suggests to a reader that the pointer represents something which is conceptually optional. If I saw that being done, I'd start worrying that everywhere in the source the pointer gets used that it should be first tested against NULL.

    If that's what you actually mean, it's better to make that explicit in the source using something like boost::optional

    optional p (new Foo);
    // (use p.get(), but must test p for truth first!...)
    delete p.get();
    p = optional();
    

    But if you really wanted people to know the pointer has "gone bad", I'll pitch in 100% agreement with those who say the best thing to do is make it go out of scope. Then you're using the compiler to prevent the possibility of bad dereferences at runtime.

    That's the baby in all the C++ bathwater, shouldn't throw it out. :)

提交回复
热议问题