理由:有可能这段代码会在其他地方使用,这样可以防止“野指针”的出现。 [解决办法] At least your func() doesn't need to test p before deleting it. If p is wild pointer, you will still have undefined behavior anyway. The correct way is:
You have one extra step to compare the pointer, how can you be faster than saving that step?
我这个 p 是全局,因为它是一个单例模块的指针,整个应用在各个地方需要用到模块的函数. You don't need to delete p as it's static. Just make sure in its destructor it cleans up resources. p pointer will deleted after main, if you delete it before main, you may have double delete.
另外你给出的修改后的代码. 既然你的 p 为局部形参那么delete之后再设置为NULL是否更没意义? 因为函数结束以后 p 就在栈里消除了...对么?[疑问二] From C++ standard, delete on null pointer is perfect safe and has defined behavior. That's why you don't need to test p but just delete it and set to null. [解决办法] 不是所有的os都是完美的进程模型。 你的代码,以后会被反复使用。 所以,如果可能,务必完美回收资源。 [解决办法] 好习惯是必须的 ------解决方案--------------------