删除指针后将指针设为 NULL 是一种好习惯吗?

时间:2023-03-22
本文介绍了删除指针后将指针设为 NULL 是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先要说的是,使用智能指针,您永远不必担心这一点.

以下代码有什么问题?

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

这是由 对另一个问题的回答和评论.Neil Butterworth 的一条评论引起了一些赞许:

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

在删除后将指针设置为 NULL 在 C++ 中并不是普遍的好习惯.有时这样做是件好事,有时却毫无意义并且可以隐藏错误.

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.

推荐答案

将指针设置为 0(在标准 C++ 中为null",与 C 中的 NULL 定义有些不同)可避免双重删除时崩溃.

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

考虑以下事项:

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

鉴于:

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

换句话说,如果您不将已删除的指针设置为 0,那么您在进行双重删除时就会遇到麻烦.反对在删除后将指针设置为 0 的一个论点是,这样做只会掩盖双重删除错误,并使它们无法处理.

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.

显然最好没有双重删除错误,但是根据所有权语义和对象生命周期,这在实践中很难实现.与 UB 相比,我更喜欢隐藏的双重删除错误.

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.

最后,关于管理对象分配的旁注,我建议您查看 std::unique_ptr 用于严格/单一所有权,std::shared_ptr 用于共享所有权,或其他智能指针实现,具体取决于您的需要.

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.

这篇关于删除指针后将指针设为 NULL 是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:指针与引用 下一篇:我应该在将 void* 转换为任何内容时使用 static_c

相关文章

最新文章