是否值得在析构函数中将指针设置为NULL? [英] Is it worth setting pointers to NULL in a destructor?

查看:800
本文介绍了是否值得在析构函数中将指针设置为NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有一个分配内存的类(现在忘记了智能指针):

Imagine I have a class that allocates memory (forget about smart pointers for now):

class Foo
{
public:
  Foo() : bar(new Bar)
  {
  }

  ~Foo()
  {
    delete bar;
  }

  void doSomething()
  {
    bar->doSomething();
  }

private:
  Bar* bar;
};

除了删除析构函数中的对象外,还值得将它们设置为NULL吗?

As well as deleting the objects in the destructor is it also worth setting them to NULL?

我假设在上面的例子的析构函数中将指针设置为NULL是浪费时间。

I'm assuming that setting the pointer to NULL in the destructor of the example above is a waste of time.

推荐答案

由于析构函数是在对象调用之前调用的最后一个对象,所以我不需要将它设置为 NULL

Since the destructor is the last thing that is called on an object before it "dies," I would say there is no need to set it to NULL afterwards.

在任何其他情况下,我总是在调用<$后设置一个指针 NULL c $ c> delete 就可以了。

In any other case, I always set a pointer to NULL after calling delete on it.

这篇关于是否值得在析构函数中将指针设置为NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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