本文介绍了如果派生中没有数据成员,是否仍需要C ++虚拟析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有此代码

class Base{
  public:
        int getVal();
  private:
         int a, b;
};

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

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

我知道虚拟析构函数可以正确删除内容,但是即使在派生类中没有虚函数且没有数据成员的情况下,使用基指针删除(在没有虚拟析构函数的情况下)也很糟糕吗?如果这样做会发生什么?

I know a virtual destructor would delete things properly, but is it bad to delete with base pointer (when there is no virtual destructor) even if there are no virtual functions and no data members in the derived class? What will happen if this is done?

推荐答案

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

For primitive-type data, your example will most likely work in practice. As a matter of fact, incurring a vtable could actually hinder performance (so there may be some legitimate use here), but it is technically undefined, per 5.3-5.4:

这实际上取决于类中数据的堆",并且由于没有堆分配的成员(在您的情况下),所以应该没问题,但这绝对是代码的味道.

It really all depends on the "heapness" of the data in your class, and as there are no heap-allocated members (in your case), you should be fine, but it's definitely a code smell.

这篇关于如果派生中没有数据成员,是否仍需要C ++虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:36