一、工厂函数返回的指针最好存储在智能指针中,当调用工厂函数的函数返回时,智能指针调用其析构函数自动释放资源。以防止因为没有使用delete函数而导致内存泄露。
工厂函数:Investment* CreatInvestment() { .............}
例如:void f()
{
Investment* pInv = CreatInvestment();
.......//此处可能会报错并跳出,导致释放资源
delete pInv;
}
智能指针1:std::auto_ptr<Investment> pInv1( CreatInvestment() );
智能指针2:std::tr1::shared_ptr<Investment> pInv1( CreatInvestment() );
两种智能指针区别:
std::auto_ptr<Investment> pInv2(pInv1);//现在pInv2指向对象,pInv1为NULL
pInv1 = pInv2;//现在pInv1指向对象,pInv2为NULL
std::tr1::shared_ptr<Investment> pInv2(pInv1);//现在两个指针都指向对象
pInv1 = pInv2;//现在两个指针都指向对象
二、如果想要从智能指针中获取原始资源,可以使用get()函数
std::tr1::shared_ptr<Investment> pInv1( CreatInvestment() );
int daysHeld(const Investment* pi)//返回投资天数
int days = daysHeld(pInv1);//错误!!!daysHeld()函数的形式参数为Investment*而不是智能指针
int days = dasHeld( pInv1.get() )//正确!返回原始资源,即指向Investment类的指针
三、以独立语句将new的对象存储于智能指针内,以防止内存泄露
int priority();
processWidget( std::tr1::shared_ptr<Widget> pw, int pri );
如此调用函数可能会导致内存泄露:
processWidget(std::tr1::shared_ptr<Widget>(new Wideget) , priority() );//错误!!!!
priority() 可能是首先执行new Wideget语句,然后执行priority() 语句,最后执行智能指针构造函数调用。如果
priority() 执行期间异常,那么new Wideget返回的指针没有放入智能指针,造成内存泄露。。。
正确写法:(分开写)
std::tr1::shared_ptr<Widget> pw(new Widget);
processWidget(std::tr1::shared_ptr<Widget>(pw, priority() );