<分区>
我一直在想,为什么只有虚方法的基类才需要虚析构函数? 看看这段代码(阅读评论):
class Base{
private:
int x;
public:
Base():x(0){}
~Base(){
cout<<"Base dtor"<<endl;
}
};
class Derived : public Base{
int y;
public:
Derived():y(0){}
~Derived(){
cout<<"Derived dtor"<<endl;
}
};
int main(){
Derived *pd = new Derived;
Base *pb = pd;
delete pb; // this destroys only the base part, doesn't it?
// so why doesnt the derived part leak?
return 0;
}
我用 Valgrind 运行它,看到输出是“Base dtor”,没有发生内存泄漏。那么,如果只调用了基类dtor,为什么派生类部分没有泄露呢?