(1)用于Bridge模式:
#include <boost/smart_ptr.hpp>
using namespace boost;
class sample
{
private:
class impl;
boost::shared_ptr<impl> p;
public:
sample();
void print();
};
class sample::impl
{
public:
void print()
{
cout<<"impl::print()"<<endl;
}
};
sample::sample():p(new impl()) {}
void sample::print()
{
p->print();
}
int _tmain(int argc, _TCHAR* argv[])
{
sample s;
s.print();
return 0;
}
(2)用于Factory模式:不再返回原始指针,而是返回一个shared_ptr对象。
class abstract
{
public:
virtual void f()=0;
virtual void g()=0;
protected:
virtual ~abstract() {}
};
class impl:public abstract
{
public:
void f() {cout<<"impl::f"<<endl;}
void g() {cout<<"impl::g"<<endl;}
};
boost::shared_ptr<abstract> create()
{
return boost::shared_ptr<abstract>(new impl);
}
int _tmain(int argc, _TCHAR* argv[])
{
boost::shared_ptr<abstract> p=create();
p->f();
p->g();
return 0;
}
在以上程序中,不会产生create的指针忘记删除的情况。