加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如果派生中没有数据成员,C是虚拟析构函数还是需要的吗?

发布时间:2020-12-16 06:01:25 所属栏目:百科 来源:网络整理
导读:假设我有这个代码 class Base{ public: int getVal(); private: int a,b;};class Derived::public Base{ public: void printVal();};int main(){ Base *b = new Derived(); delete b; } 我知道一个虚拟析构函数会正确删除事物,但是使用基本指针(当没有虚拟析
假设我有这个代码
class Base{
  public:
        int getVal();
  private:
         int a,b;
};

class Derived::public Base{
    public:
         void printVal();
};

int main(){
    Base *b = new Derived();
    delete b;    
}

我知道一个虚拟析构函数会正确删除事物,但是使用基本指针(当没有虚拟析构函数)时,即使在派生类中没有虚拟函数也没有数据成员,这是不好的.如果这样做会发生什么?

解决方法

对于原始类型的数据,您的示例很可能在实践中工作.事实上,引发一个vtable可能会阻碍性能(因此这里可能有一些合法用途),但是在5.3-5.4中它在技术上是未定义的:

If the static type of the operand [of
the delete operator] is different from
its dynamic type,the static type
shall be a base class of the operand’s
dynamic type and the static type shall
have a virtual destructor or the
behaviour is undefined.

它完全取决于你的类中数据的“堆积”,而没有堆分配的成员(在你的情况下),你应该是好的,但它绝对是一个代码的气味.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读