我需要在析构函数中取消一个成员变量吗? [英] Do I need to nullify a member variable in the destructor?

查看:198
本文介绍了我需要在析构函数中取消一个成员变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要明确清除一个向量成员变量(在dtor中的on)(请参见下面的代码)。清除向量的好处是什么,即使它将在最后一行之后被销毁dtor代码将被执行?

  class A 
{
〜A()
{
values.clear();
}

private:
std :: vector< double> values_;
};

类似的问题

> class B
{
〜B()
{
if(NULL!= p)
{
delete p_;
p_ = NULL;
}
}

私人:
A * p_;
};

因为没有办法dtor会被调用两次,为什么要使p_无效?

解决方案

在类 A 中,绝对没有理由 .clear() 向量在析构函数中的成员变量向量



类中 c $ c> B ,清理代码可以写成:

  

无需测试 p_!= NULL 第一个因为 delete NULL; 被定义为无操作。在您删除之后,也不需要设置 p_ = NULL ,因为



也就是说,你很少需要使用这个函数,因为p _ delete 在C ++代码中。您应该更倾向于使用范围绑定资源管理(SBRM,也称为资源获取初始化)来自动管理资源生命周期。



在这种情况下,您可以使用智能指针。 boost :: scoped_ptr std :: unique_ptr (从C ++ 0x)都是不错的选择。与使用原始指针相比,它们都不应该有任何开销。另外,它们都抑制隐式声明的拷贝构造函数和拷贝赋值运算符的生成,这通常是你想要的,当你有一个成员变量是一个指向动态分配对象的指针。


Why one would want to explicitly clear the a vector member variable (of on in a dtor (please see the code below). what are the benefits of clearing the vector, even though it will be destroyed just after the last line of dtor code will get executed?

class A
{
~A()
{
   values.clear();
}

private: 
  std::vector < double > values_;
};

similar question about a the following code:

class B
{
~B()
{
   if (NULL != p)
   {
       delete p_;
       p_ = NULL;
   }
}

private: 
  A * p_;
};

Since there is no way the dtor will get called twice, why to nullify p_ then?

解决方案

In class A, there is absolutely no reason to .clear() the vector-type member variable in the destructor. The vector destructor will .clear() the vector when it is called.

In class B, the cleanup code can simply be written as:

delete p_;

There is no need to test whether p_ != NULL first because delete NULL; is defined to be a no-op. There is also no need to set p_ = NULL after you've deleted it because p_ can no longer be legitimately accessed after the object of which it is a member is destroyed.

That said, you should rarely need to use delete in C++ code. You should prefer to use Scope-Bound Resource Management (SBRM, also called Resource Acquisition Is Initialization) to manage resource lifetimes automatically.

In this case, you could use a smart pointer. boost::scoped_ptr and std::unique_ptr (from C++0x) are both good choices. Neither of them should have any overhead compared to using a raw pointer. In addition, they both suppress generation of the implicitly declared copy constructor and copy assignment operator, which is usually what you want when you have a member variable that is a pointer to a dynamically allocated object.

这篇关于我需要在析构函数中取消一个成员变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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