存储在ptr_vector中的派生类未被破坏

时间:2010-10-19 13:59:05

标签: c++ boost ptr-vector

试图找到使用ptr_vector存储,访问和释放对象的最佳方法,尤其是当存储对象从其他对象继承时(ptr_vector不应该有任何对象切片问题)。 但是当运行下面的程序时,令人惊讶的是派生类没有被破坏。谁知道为什么?

#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/foreach.hpp>
using namespace std;

class A
{
 public:
 int id;
 A() {cout<<"Constructed A()"<<endl;}
 A(int i):id(i) {cout<<"Constructed A"<<i<<endl;}
 ~A() {cout<<"* Destructed A"<<id<<endl;}
};
class B:public A
{
 public:
 int i;
 B() {cout<<"Constructed B"<<endl;}
 B(int ii):i(ii) {id=ii;cout<<"Constructed B"<<i<<endl;}
 ~B() {cout<<"* Destructed B"<<i<<endl;}
};

class zoo
{
 boost::ptr_vector<A> the_animals;
public:
 void addAnimal(A* a) {the_animals.push_back( a );}
 void removeAnimal(int id) {the_animals.release(the_animals.begin()+id); }
 void removeOwnership(int id) {the_animals.release(the_animals.begin()+id).release();}
};

int main()
{
 zoo z;
 z.addAnimal( new B(0) );
 //delete abc;z.addAnimal(abc);//doing this will cause heap corruption
 B* lion=new B(1);
 z.addAnimal(lion);
 z.removeOwnership(1);
        delete lion;
 z.removeAnimal(0);
}//main

该计划的输出是:

Constructed A()
Constructed B0
Constructed A()
Constructed B1
* Destructed B1
* Destructed A1
* Destructed A0

B0为什么不被破坏?物体被切成了吗?

1 个答案:

答案 0 :(得分:8)

基类的析构函数不是虚拟的:

 ~A() {cout<<"* Destructed A"<<id<<endl;}

应该是:

 virtual ~A() {cout<<"* Destructed A"<<id<<endl;}

为什么?见When should your destructor be virtual?