http://www.cppblog.com/aaxron/archive/2010/12/23/137293.html
一旦使用的继承机制, 如果基类没有设置为虚函数, 那么子类的析构函数很可能不会调用.
为什么是可能而不是一定呢?
因为是只会在指针的场景;
class Base
{
public:
Base(){
cout<<"Base Construcing"<<endl;
}
~Base(){
cout<<"Base Destrucing"<<endl;
}
};
class Derived : public Base
{
public:
Derived(){
cout<<"Derived Constructing"<<endl;
}
~Derived(){
cout<<"Derived Destructing"<<endl;
}
};
int main() {
Base *base = new Derived;
delete base;
cout<< "*************分割线*************"<<endl;
Derived Derived;
return 0;
}
下面是输出
Base Construcing
Derived Constructing
Base Destrucing
*************分割线*************
Base Construcing
Derived Constructing
Derived Destructing
Base Destrucing
- 可以看出, 当使用父类指针的时候, 如果虚析构函数不具有多态性(virtual), 那么,Base*就只会调用Base类的析构函数,而不会去寻找子类的析构函数.
- 也不能把Base* 改成Derived指针,因为Derived指针有一天也可能变成其他类型的父类