虚拟析构函数如何工作? [英] How do virtual destructors work?
问题描述
我使用gcc。我知道如何虚拟析构函数解决问题时,我们销毁一个派生类对象指向一个基类指针。我想知道他们如何工作?
I am using gcc. I am aware how the virtual destructors solve the problem when we destroy a derived class object pointed by a base class pointer. I want to know how do they work?
class A
{
public:
A(){cout<<"A constructor"<<endl;}
~A(){cout<<"A destructor"<<endl;}
};
class B:public A
{
public:
B(){cout<<"B constructor"<<endl;}
~B(){cout<<"B destructor"<<endl;}
};
int main()
{
A * a = new B();
delete a;
getch();
return 0;
}
当我将A的析构函数更改为虚函数时,问题就解决了。这是什么内在的工作。为什么我使A的析构函数虚拟。我想知道A和B的vtable发生了什么?
When I change A's destructor to a virtual function, the problem is solved. What is the inner working for this. Why do I make A's destructor virtual. I want to know what happens to the vtable of A and B?
推荐答案
你需要知道的关键是,在上面的代码中的虚拟析构函数是未定义的行为,这不是你想要的。虚拟析构函数与任何其他虚拟函数一样 - 当你调用 delete
时,程序将决定在运行时调用哪个析构函数并解决你的问题。
The key thing you need to know is that not using a virtual destructor in the above code is undefined behavior and that's not what you want. Virtual destructors are like any other virtual functions - when you call delete
the program will decide what destructor to call right in runtime and that solves your problem.
这篇关于虚拟析构函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!