智能指针引用计数

	class Demo : public std::enable_shared_from_this<Demo> {
    public:
        std::string key;
        std::string value;
    };
    std::shared_ptr<Demo> A = std::shared_ptr<Demo>(new Demo());
    int count1 = A.use_count();//1
    std::shared_ptr<Demo> B = A;
    int count2 = A.use_count();//2
    int count3 = B.use_count();//2
    std::weak_ptr<Demo> C = A;
    int count4 = A.use_count();//2
    int count5 = B.use_count();//2
    int count6 = C.use_count();//2
    std::shared_ptr<Demo> D = C.lock();
    int count7 = A.use_count();//3
    int count8 = B.use_count();//3
    int count9 = C.use_count();//3
    int count10 = D.use_count();//3
    std::shared_ptr<Demo> E = std::shared_ptr<Demo>(A.get()); //这种写法会导致内存空间重复释放
    int count11 = A.use_count();//3
    int count12 = B.use_count();//3
    int count13 = C.use_count();//3
    int count14 = D.use_count();//3
    int count15 = E.use_count();//1
    std::shared_ptr<Demo> F = A->shared_from_this();
    int count16 = A.use_count();//4
    int count17 = B.use_count();//4
    int count18 = C.use_count();//4
    int count19 = D.use_count();//4
    int count20 = E.use_count();//1
    int count21 = F.use_count();//4
    std::weak_ptr<Demo> G = A->shared_from_this();
    int count22 = A.use_count();//4
    int count23 = B.use_count();//4
    int count24 = C.use_count();//4
    int count25 = D.use_count();//4
    int count26 = E.use_count();//1
    int count27 = F.use_count();//4
    int count28 = G.use_count();//4

    A = nullptr;
    int count29 = A.use_count();//0
    int count30 = B.use_count();//3
    int count31 = C.use_count();//3
    int count32 = D.use_count();//3
    int count33 = E.use_count();//1
    int count34 = F.use_count();//3
    int count35 = G.use_count();//3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值