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

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

    Setting a pointer to 0 (which is "null" in standard C++, the NULL define from C is somewhat different) avoids crashes on double deletes.

    Consider the following:

    Foo* foo = 0; // Sets the pointer to 0 (C++ NULL)
    delete foo; // Won't do anything
    

    Whereas:

    Foo* foo = new Foo();
    delete foo; // Deletes the object
    delete foo; // Undefined behavior 
    

    In other words, if you don't set deleted pointers to 0, you will get into trouble if you're doing double deletes. An argument against setting pointers to 0 after delete would be that doing so just masks double delete bugs and leaves them unhandled.

    It's best to not have double delete bugs, obviously, but depending on ownership semantics and object lifecycles, this can be hard to achieve in practice. I prefer a masked double delete bug over UB.

    Finally, a sidenote regarding managing object allocation, I suggest you take a look at std::unique_ptr for strict/singular ownership, std::shared_ptr for shared ownership, or another smart pointer implementation, depending on your needs.

提交回复
热议问题