删除时将指针设置为null? [英] Set a pointer to null when deleting?

查看:99
本文介绍了删除时将指针设置为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

删除指针时,应将其设置为NULL,对吧?


Joe

解决方案

< blockquote> Joe Van Dyk写道:

删除指针时,应将其设置为NULL,对吗?




不。你的指针应该总是超出范围,所以不要打扰

将它弄为空。


如果必须,请使用std :: auto_ptr或boost :: shared_ptr,并重置(NULL)

(如果我没记错的话)。


然后他们的秘密内部指针将只删除在他们离开

范围之前,他们将处理它的NULL。


-

Phlip http://www.greencheese.org/ZeekLand < - NOT a博客!!!


Joe Van Dyk写道:

当你删除指针时,你应该把它设置为NULL,对吧?




不会。如果你删除一个指针,它可能是一个类成员,而且你是从b
中删除它析构函数。在这种情况下,你不要把它设置为0,

因为

没人会注意到。另一个常见的情况是在作业中,但是在这种情况下,你需要新的替换对象。 (你首先要做新b / b
,所以如果你的内存不足,分配失败,但

旧值不会丢失)。


当然,如果你使用智能指针,这都是自动的。


HTH,

Michiel Salters


Phlip写道:

Joe Van Dyk写道:

删除指针时,应将其设置为NULL,对吗?
不。你的指针应该总是超出范围,所以不要打扰它。




胡说八道。如果我的指针是数据成员并且我正在管理自己的内存,那么在某些情况下我应该将它设置为空指针。删除后没有
必然超出范围。

如果必须,请使用std :: auto_ptr或boost :: shared_ptr,并重置(NULL)
那(如果我没记错的话)。


''提升''是非标准的。 ''std :: auto_ptr''由于其特定的复制语义而不适合某些

的情况。

[..]




V

-

请在通过电子邮件回复时删除资金''A'

我请不要回复最热门的回复,请不要问


When you delete a pointer, you should set it to NULL, right?

Joe

解决方案

Joe Van Dyk wrote:

When you delete a pointer, you should set it to NULL, right?



No. Your pointer should always be about to go out of scope, so don''t bother
to NULL it.

If you must, use std::auto_ptr or boost::shared_ptr, and reset(NULL) that
(if I recall correctly).

Then their secret internal pointer will delete just before they go out of
scope, and they will take care of its NULL.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


Joe Van Dyk wrote:

When you delete a pointer, you should set it to NULL, right?



No. If you delete a pointer, it''s probably a class member, and you''re
deleting it from a destructor. In that case, you don''t set it to 0,
because
noone will ever notice. The other common case is in assignments, but
in that case you will have new''ed a replacement object before. (You do
the new first, so if you run out of memory the assignment fails but the
old value is not lost).

Of course, if you use a smart pointer this is all automatic.

HTH,
Michiel Salters


Phlip wrote:

Joe Van Dyk wrote:

When you delete a pointer, you should set it to NULL, right?
No. Your pointer should always be about to go out of scope, so don''t
bother to NULL it.



Nonsense. If my pointer is a data member and I am managing my own
memory, I should set it to null pointer in some cases. It doesn''t
necessarily go out of scope right after deletion.
If you must, use std::auto_ptr or boost::shared_ptr, and reset(NULL)
that (if I recall correctly).
''boost'' is non-standard. ''std::auto_ptr'' is not suitable for some
cases due to its particular copy semantics.
[..]



V
--
Please remove capital ''A''s when replying by e-mail
I do not respond to top-posted replies, please don''t ask


这篇关于删除时将指针设置为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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