且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除它后,是否一个指针是NULL的好习惯?

更新时间:2023-12-01 07:50:21

将指针设为NULL后,删除它所指向的内容肯定不会伤害,但它通常对一个更根本的问题一个band-aid:为什么你使用指针在第一位?我可以看到两个典型的原因:

Setting pointers to NULL after you've deleted what it pointed to certainly can't hurt, but it's often a bit of a band-aid over a more fundamental problem: Why are you using a pointer in the first place? I can see two typical reasons:


  • 你只是想在堆上分配一些东西。在这种情况下,将其包装在RAII对象中将更安全和更清洁。当不再需要对象时,结束RAII对象的作用域。这就是 std :: vector 的工作原理,它解决了意外留下指针到释放内存的问题。没有指针。

  • 或者你想要一些复杂的共享所有权语义。从 new 返回的指针可能与调用 delete 的指针不同。多个对象可能同时使用该对象。在这种情况下,共享指针或类似的东西会更好。

  • You simply wanted something allocated on the heap. In which case wrapping it in a RAII object would have been much safer and cleaner. End the RAII object's scope when you no longer need the object. That's how std::vector works, and it solves the problem of accidentally leaving pointers to deallocated memory around. There are no pointers.
  • Or perhaps you wanted some complex shared ownership semantics. The pointer returned from new might not be the same as the one that delete is called on. Multiple objects may have used the object simultaneously in the meantime. In that case, a shared pointer or something similar would have been preferable.

我的经验法则是,用户代码,你做错了。指针不应该在那里指向垃圾在第一位。为什么没有一个对象负责确保其有效性?为什么指针对象不会结束其作用域?

My rule of thumb is that if you leave pointers around in user code, you're Doing It Wrong. The pointer shouldn't be there to point to garbage in the first place. Why isn't there an object taking responsibility for ensuring its validity? Why doesn't its scope end when the pointed-to object does?