标签:count() 循环引用 问题 生命周期 上班 cout weak_ptr ptr 引用
*
和->
,因为它不共享指针,不能操作资源。shared_ptr<int> sp(new int(10));
weak_ptr<int> wp(sp);
cout<<wp.use_count()<<endl; //结果将输出1
shared_ptr<int> sp(new int(10));
weak_ptr<int> wp(sp);
if(wp.expired())
std::cout << "weak_ptr无效,所监视的智能指针已被释放\n";
else
std::cout << "weak_ptr有效\n";
//结果将输出:weak_ptr有效
std::weak_ptr<int> gw;
void f()
{
if(gw.expired()) //所监视的shared_ptr是否释放
{
std::cout << "gw is expired\n";
}
else
{
auto spt = gw.lock();
std::cout << *spt << "\n";
}
}
int main()
{
{
auto sp = std::make_shared<int>(42);
gw = sp;
f();
}
f();
}
/*
输出:
42
gw is expired
*/
struct A: public std::enable_shared_from_this<A>
{
std::shared_ptr<A> GetSelf()
{
return shared_from_this();
}
~S()
{
cout<<"A is deleted"<<endl;
}
};
std::shared_ptr<A> spy(new A);
std::shared_ptr<A> p = spy->GetSelf();//OK
/*
输出结果
A is deleted
*/
struct A;
struct B;
struct A{
std::shared_ptr<B> bptr;
~A() {cout<<"A is deleted!"<<endl;}
};
struct B{
std::shared_ptr<A> aptr;//将A B中的任何一个改成 weak_ptr
~B() {cout<<"B is deleted!"<<endl;}
};
void TestPtr()
{
{
std::shared_ptr<A> ap(new A);
std::shared_ptr<B> bp(new B);
ap->bptr = bp;
bp->aptr = ap;
}//Objects should be destroyed
}
标签:count() 循环引用 问题 生命周期 上班 cout weak_ptr ptr 引用
原文地址:https://www.cnblogs.com/fewolflion/p/12960302.html