weak_ptr是shared_ptr得到協助者,可以觀察shared_ptr是否過期,weak_ptr不改變引用計數,也不能使用 *,->操作符,是一個很弱的智能指針。例如下面的代碼:
#include <iostream>
#include <boost/make_shared.hpp>
#include <boost/weak_ptr.hpp>
using namespace std;
using namespace boost;
class test
{
public:
test()
{
cout << "構造" << endl;
}
~test()
{
cout << "析構" << endl;
}
void fun()
{
cout << "fun()" << endl;
}
};
int main()
{
boost::shared_ptr<test> sp1 = boost::make_shared<test>();
boost::weak_ptr<test> wp = sp1;
cout << "sp1是否過期:" << wp.expired() << endl;
sp1.reset();
cout << "sp1是否過期:" << wp.expired() << endl;
return 0;
}
運行結果
expired()方法可以監控shared_ptr是否釋放內