删除它后,是否一个指针是NULL的好习惯? [英] Is it good practice to NULL a pointer after deleting it?

查看:157
本文介绍了删除它后,是否一个指针是NULL的好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将首先说,使用智能指针,您永远不必担心这个问题。

问题与下面的代码?

Foo * p = new Foo;
// (use p)
delete p;
p = NULL;

这是由对另一个问题回答和评论。来自 Neil Butterworth 的一条评论产生了几个upvote:

This was sparked by an answer and comments to another question. One comment from Neil Butterworth generated a few upvotes:


在C ++中删除后将指针设置为NULL不是普遍的好习惯。

Setting pointers to NULL following delete is not universal good practice in C++. There are times when it is a good thing to do, and times when it is pointless and can hide errors.

有很多的时间,这是一件好事,有时是无意义的,情况,它不会帮助。但在我的经验,它不能伤害。有人告诉我。

There are plenty of circumstances where it wouldn't help. But in my experience, it can't hurt. Somebody enlighten me.

推荐答案

将指针设为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?

这篇关于删除它后,是否一个指针是NULL的好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆