C++ 11,智能指针(整理总结)3

weak_ptr弱引用的智能指针

用来监视shared_ptr的,不会使引用计数加1,不管理shared_ptr内部的指针,主要为了监视shared_ptr生命周期,更像是shared_ptr的一个助手。

weak_ptr用来返回this指针,解决循环引用的问题。

一、基本用法:

用expired方法,获取资源状态是否被释放

用lock方法获取所监视的share_ptr

    weak_ptr<int> wp;
    {
        shared_ptr<int> ps(new int(1));
        //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<A>
{
public:
    shared_ptr<A> Getself()
    {
        return shared_from_this();
    }
    A()
    {
        cout << "A,construct" << endl;
    }
    ~A()
    {
        cout << "~~A,discontruct" << endl;
    }
};

    shared_ptr<A> sp1(new A);
    shared_ptr<A> sp2 = sp1->Getself();

三、解决循环引用问题

struct A;
struct B;

struct A
{
    shared_ptr<B> bptr;
    ~A()
    {
        cout << "A is delete" << endl;
    }
};

struct B
{
    weak_ptr<A> aptr;
    ~B()
    {
        cout << "B is delete" << endl;
    }
};

    cout << "begin" << endl;
    {
        shared_ptr<A> ap(new A);
        shared_ptr<B> bp(new B);
        ap->bptr = bp;
        bp->aptr = ap;
    }
    cout << "end"<< endl;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿土有品

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值