虚拟析构函数的默认替代 [英] default override of virtual destructor

查看:81
本文介绍了虚拟析构函数的默认替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人都知道基类的解释器通常必须是虚拟的。但是派生类的析构函数呢?在C ++ 11中,我们具有关键字 override并能够显式使用默认析构函数。

  struct父级
{
std :: string a;
虚拟〜Parent()
{
}

};

struct子级:public父级
{
std :: string b;
〜Child()覆盖=默认值;
};

在Child类的析构函数中同时使用关键字 override和 = default是否正确?在这种情况下,编译器会生成正确的虚拟析构函数吗?



如果是,那么我们可以认为这是一种良好的编码风格,并且我们应该始终以此方式声明派生类的析构函数确保基类析构函数是虚拟的?

解决方案


同时使用两个关键字 override是否正确和 = default在Child类的析构函数中?在这种情况下,编译器会生成正确的虚拟析构函数吗?


是的,这是正确的。在任何理智的编译器上,如果代码编译没有错误,则该析构函数定义将是无操作的:它的缺失一定不能改变代码的行为。


我们可以认为这是一种很好的编码样式吗?


这是优先选择的问题。对我来说,只有将基类类型设计为模板才有意义:它将对基类强制要求具有虚拟析构函数。否则,当基本类型固定时,我会认为此类代码是噪音。这并不是说基类会发生神奇的变化。 但是,如果您的队友头脑僵硬,希望在不检查依赖于他们可能破坏的代码的情况下进行更改,那么最好保留析构函数的定义-作为额外的保护层。 p>

Everyone knows that the desructor of base class usually has to be virtual. But what is about the destructor of derived class? In C++11 we have keyword "override" and ability to use the default destructor explicitly.

struct Parent
{
  std::string a;
  virtual ~Parent()
  {
  }

};

struct Child: public Parent
{
  std::string b;
  ~Child() override = default;
};

Is it correct to use both keywords "override" and "=default" in the destructor of Child class? Will compiler generate correct virtual destructor in this case?

If yes, then can we think that it is good coding style, and we should always declare destructors of derived classes this way to ensure that base class destructors are virtual?

解决方案

Is it correct to use both keywords "override" and "=default" in the destructor of Child class? Will compiler generate correct virtual destructor in this case?

Yes, it is correct. On any sane compiler, if the code compiles without error, this destructor definition will be a no-op: its absence must not change the behavior of the code.

can we think that it is good coding style

It's a matter of preference. To me, it only makes sense if the base class type is templated: it will enforce a requirement on the base class to have a virtual destructor, then. Otherwise, when the base type is fixed, I'd consider such code to be noise. It's not as if the base class will magically change. But if you have deadheaded teammates that like to change things without checking the code that depends on what they may be possibly breaking, it's best to leave the destructor definition in - as an extra layer of protection.

这篇关于虚拟析构函数的默认替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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