c++ - 为什么虚拟析构函数的行为如此?

标签 c++

我读到必须在具有虚方法的类中声明虚析构函数。我只是不明白为什么必须将它们声明为虚拟的。我知道为什么我们需要从以下示例中获得虚拟析构函数。我只是想知道为什么编译器不为我们管理虚拟析构函数。关于虚拟析构函数的工作,我需要了解什么吗? 下面的示例表明,如果未将析构函数声明为虚拟的,则不会调用派生类的析构函数,这是为什么?

class Base 
{
    // some virtual methods
public:
    Base()
    {std::cout << "Base Constructor\n";}
    ~Base()
    {std::cout << "Base De-structor\n";}

};

class Derived : public Base
{
public:
    Derived()
    {std::cout << "Der constructor\n";}
    ~Derived()
    { std::cout << "Der De-structor\n";}
} ;         
void main()
{

    Base *b = new Derived();
    delete b;
}

最佳答案

I just wanted to know why compilers dont manage virtual destructors for us.

因为在 C++ 中,您为使用的东西付费。默认情况下,拥有一个 virtual 析构函数涉及编译器向该类添加一个虚拟表指针,这会增加其大小。这并不总是可取的。

The following example shows that if destructors are not declared virtual the destructors of derived class are not called why is that ?

该示例表现出未定义的行为。这简直是​​违反规则。并非所有析构函数都被调用这一事实只是一种可能的表现形式。它可能会崩溃。

Is there something I need to know about working of virtual destructors ?

是的。如果您通过指向基类的指针删除对象,则它们是必需的。否则就是未定义的行为。

5.3.5 删除[expr.delete]

3) In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined. (emphasis mine)

关于c++ - 为什么虚拟析构函数的行为如此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13019129/

相关文章:

c++ - MFC C++ 将枚举值插入到 CArray

虚拟机的 C++ For 循环优化

c++ - 算法不适用于非常量对象的 const_iterator

c++ - 更改接口(interface)类中私有(private)成员变量的指针类型二进制兼容吗?

c++ - 如何在另一台电脑的 Excel 中使用依赖于 gsl dll 的 c++ dll?

c++ - 使用 std::sort 对具有结构对的列表进行排序

c++ - 从一些 C++ 框架或 python 开始

c++ - 在 makefile 中添加 c++11 以消除错误 to_string is not declared in this scope

c++ - llvm-gcc std::allocator 错误?

c++ - 无法反序列化对象 - Qt