我正在尝试以下示例:
class base // base class
{
public:
std::list<base*> values;
base(){}
void initialize(base *b) {
values.push_front(b);
}
virtual ~base()
{
values.clear();
cout<<"base called"<<endl;
}
};
class derived : public base // derived class
{
public:
~derived(){
cout<<"derived called"<<endl;
}
};
int main()
{
derived *d = new derived;
base *b = new base;
b->initialize(static_cast<base *>(d)); /* filling list */
delete b;
return 0;
}
问题1:为什么派生类的析构函数没有被调用,而我的基类析构函数中执行了 values.clear()
?
问题2:如果基类析构函数是虚拟的,是否需要定义派生类的析构函数?
delete
删除对象,因此未调用派生类的析构函数! - Bo Persson