Derived class stored in ptr_vector not being destructed
试图找到使用ptr_向量存储、访问和释放对象的最佳方法,尤其是当存储的对象从其他对象继承时(ptr_向量不应存在任何对象切片问题)。但是当运行下面的程序时,令人惊讶的是派生类没有被破坏。有人知道为什么吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #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 |
程序输出为:
1 2 3 4 5 6 7 | Constructed A() Constructed B0 Constructed A() Constructed B1 * Destructed B1 * Destructed A1 * Destructed A0 |
为什么b0没有被摧毁?物体被切割了吗?
基类的析构函数不是虚拟的:
1 | ~A() {cout<<"* Destructed A"<<id<<endl;} |
应该是:
1 | virtual ~A() {cout<<"* Destructed A"<<id<<endl;} |
为什么?看看什么时候你的析构函数应该是虚拟的?