Nav*_*Nav 1 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
Run Code Online (Sandbox Code Playgroud)
该程序的输出是:
Constructed A()
Constructed B0
Constructed A()
Constructed B1
* Destructed B1
* Destructed A1
* Destructed A0
Run Code Online (Sandbox Code Playgroud)
为什么B0不被破坏?物体被切成薄片了吗?
基类的析构函数不是虚拟的:
~A() {cout<<"* Destructed A"<<id<<endl;}
Run Code Online (Sandbox Code Playgroud)
应该:
virtual ~A() {cout<<"* Destructed A"<<id<<endl;}
Run Code Online (Sandbox Code Playgroud)
为什么?看你的析构函数什么时候应该是虚拟的?
| 归档时间: |
|
| 查看次数: |
291 次 |
| 最近记录: |