weak_ptr弱引用的智能指针
用来监视shared_ptr的,不会使引用计数加1,不管理shared_ptr内部的指针,主要为了监视shared_ptr生命周期,更像是shared_ptr的一个助手。
weak_ptr用来返回this指针,解决循环引用的问题。
一、基本用法:
用expired方法,获取资源状态是否被释放
用lock方法获取所监视的share_ptr
weak_ptr
{
shared_ptr
//gp = ps;
wp = ps;
cout << wp.use_count() << endl;
if (wp.expired())
{
cout << "资源释放了--" << endl;
}
else
{
cout << "资源有效--" << endl;
auto spt = wp.lock();
cout << "spt:"<<*spt << endl;
}
}
if (wp.expired())
{
cout << "资源释放了" << endl;
}
else
{
cout << "资源有效" << endl;
}
cout << wp.use_count() << endl;
二、weak_ptr返回this指针
class A :public enable_shared_from_this
{
public:
shared_ptr Getself()
{
return shared_from_this();
}
A()
{
cout << "A,construct" << endl;
}
~A()
{
cout << "~~A,discontruct" << endl;
}
};
shared_ptr sp1(new A);
shared_ptr sp2 = sp1->Getself();
三、解决循环引用问题
struct A;
struct B;
struct A
{
shared_ptr bptr;
~A()
{
cout << "A is delete" << endl;
}
};
struct B
{
weak_ptr aptr;
~B()
{
cout << "B is delete" << endl;
}
};
cout << "begin" << endl;
{
shared_ptr ap(new A);
shared_ptr bp(new B);
ap->bptr = bp;
bp->aptr = ap;
}
cout << "end"<< endl;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)