参考文献:https://www.codeproject.com/Articles/8394/Smart-Pointers-to-boost-your-code
std:: auto_ptr中的智能指针有如下缺点:
(1)auto_ptr不能共享所有权;
(2)auto_ptr不能指向数组;
(3)auto_ptr不能作为容器的成员;
(4)不能通过赋值操作来初始化auto_ptr;
std::auto_ptr<int>p(new int(42)); //OK
std::auto_ptr<int>p = new int(42); //ERROR
(5)不要把auto_ptr放入容器。
所以如果需要使用智能指针,推荐使用boost库中的智能指针:
简单的单一对象的唯一所有权。不可拷贝。 | ||
简单的数组的唯一所有权。不可拷贝。 | ||
在多个指针间共享的对象所有权。 | ||
在多个指针间共享的数组所有权。 | ||
一个属于 shared_ptr 的对象的无所有权的观察者。 | ||
带有一个侵入式引用计数的对象的共享所有权。 |
智能指针scoped的使用:
void Sample1_Plain()
{
CSample * pSample(new CSample);
if (!pSample->Query() )
// just some function...
{
delete pSample;
return;
}
pSample->Use();
delete pSample;
}
#include "boost/smart_ptr.h"
void Sample1_ScopedPtr()
{
boost::scoped_ptr<CSample> samplePtr(new CSample);
if (!samplePtr->Query() )
// just some function...
return;
samplePtr->Use();
}
智能指针shared
的使用:
void Sample2_Shared()
{
// (A) create a new CSample instance with one reference
boost::shared_ptr<CSample> mySample(new CSample);
printf("The Sample now has %i references\n", mySample.use_count()); // should be 1
// (B) assign a second pointer to it:
boost::shared_ptr<CSample> mySample2 = mySample; // should be 2 refs by now
printf("The Sample now has %i references\n", mySample.use_count());
// (C) set the first pointer to NULL
mySample.reset();
printf("The Sample now has %i references\n", mySample2.use_count()); // 1
// the object allocated in (1) is deleted automatically
// when mySample2 goes out of scope
}
Boost库中的智能指针是通过引用计数值来确定对象是否应该被释放。强引用是当引用对象活着时,这引用也存在,shared_ptr就是强引用;而弱引用的引用对象活着时不一定存在,不修改引用计数值,只是普通的指针,但弱引用能检查对象是否已经被释放,避免访问非法内存。
boost::weak_ptr必须从一个boost::share_ptr或另一个boost::weak_ptr转换而来,当对象存在循环引用时,引用计数值为1,也就存在无法释放内存的问题,采用弱指针可以解决该问题,弱指针不更改引用计数,只需将循环引用的一方使用弱引用即可:
typedef boost::shared_ptr<parent> parent_ptr;
typedef boost::shared_ptr<children> children_ptr;
class parent {
children_ptr children;
};
class children {
parent_ptr parent;
};
class children {
boost::weak_ptr<parent> parent;
};