您的位置:首页 > 其它

Item 13 管理在堆上new出来的对象

2011-04-25 13:26 127 查看
void f()
{
std::auto_ptr<Investment> pInv(createInvestment());
...
}


创建Investment资源之后立即交给资源管理器auto_ptr
,这叫Resource Acquisition Is Initialization (RAII)。

资源管理器在dtor里销毁资源。如果发生异常,会很麻烦。

不要用多个auto_ptr管理同一个资源。否则会发生多次销毁。auto_ptr本身也改装了copy动作(copy ctor和assignment operator)。

std::auto_ptr<Investment> pInv1(createInvestment());
std::auto_ptr<Investment> pInv2(pInv1);	// pInv2 now points to the object; pInv1 is now null
pInv1 = pInv2;							// now pInv1 points to the object, and pInv2 is null


因为有着这种奇怪的拷贝行为,所以auto_ptr不能用于管理STL容器内的元素。STL容器要求,其元素必须能正常拷贝。

可使用“引用计数智能指针”:reference-counting smart pointer (RCSP)来代替auto_ptr。和垃圾收集类似,不同之外在于RCSP不能处理“循环引用”。

shared_ptr就是一种RCSP:

void f()
{
...
std::tr1::shared_ptr<Investment> pInv(createInvestment());
...
}


对于初始化,和auto_ptr没什么不同。

void f()
{
...
std::tr1::shared_ptr<Investment> pInv1(createInvestment());
std::tr1::shared_ptr<Investment> pInv2(pInv1);	// both pInv1 and pInv2 now point to the object
pInv1 = pInv2;									// ditto — nothing has changed
...
}	// pInv1 and pInv2 are destroyed, and the object they point to is automatically deleted


auto_ptr和tr1::shared_ptr都用delete来析构对象,而非delete[]。所以不能管理对象数组。但是如果误用,编译器不报错。

boost::scoped_array和boost::shared_array可管理数组对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: