//因为使用了 shared_ptr
//1.基类的析构即使不是 virtual 也可以正确的释放
// 这一点很重要,可以防止容器内的指针被以外释放
//2.shared_ptr 对象可以作为STL容器的对象
//3.shared_ptr 如何置 0
//3.shared_ptr 如何判断空值
#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
#include <boost/shared_ptr.hpp>
using namespace boost;
class A
{
protected:
int m_n;
public:
A(int n):m_n(n){}
virtual void Ring(){cout<<"A("<<m_n<<") ringing!"<<endl;}
protected:
virtual ~A(){cout<<"A("<<m_n<<") 析构"<<endl;}
};
class B:public A
{
public:
B(int n):A(n){}
virtual ~B(){cout<<"B("<<m_n<<") 析构"<<endl;}
virtual void Ring(){cout<<"B("<<m_n<<") ringing!"<<endl;}
};
shared_ptr<A> Create(int n)
{
shared_ptr<A> p(new B(n));
return p;
}
void Do()
{
cout<<"-----------------------------"<<endl;
vector<shared_ptr<A> > Myvec;
for(int i = 0; i < 10; i++)
{
Myvec.push_back(Create(i));
}
typedef vector<shared_ptr<A> >::iterator iterator;
iterator it = Myvec.begin(),itend = Myvec.end();
int i = 0;
for(;it != itend;it++)
{
if(i == 0 || i == 5)
(*it).reset();
i++;
if((*it))
(*it)->Ring();
}
cout<<"-----------------------------"<<endl;
}
int main(int argc, char *argv[])
{
Do();
system("PAUSE");
return EXIT_SUCCESS;
}
shared_ptr 复杂应用
最新推荐文章于 2025-01-08 00:03:36 发布