weak_ptr 解决 shared_ptr循环引用的问题

#include <iostream>
#include <memory>

using namespace std;
 
class Parent;
 
class Child
{
public:
    Child(){
        std::cout << "Child construction" << std::endl;
    }
	~Child(){
        std::cout << "Child destruction" << std::endl;
    }
    weak_ptr<Parent> parent;
};
 
class Parent
{
public:
    Parent(){
        std::cout << "Parent construction" << std::endl;
    }
    ~Parent(){
        std::cout << "Parent destruction" << std::endl;
    }
    shared_ptr<Child> child;
    int Get() { return 3; };
};
 
void Test(shared_ptr<Child>& c)
{
    std::cout << "3child use count = " << c.use_count() <<std::endl;
    shared_ptr<Parent> p(new Parent());
    c->parent = p;
    p->child = c;
    std::cout << "4child use count = " << c.use_count() <<std::endl;
    if (shared_ptr<Parent> pp = c->parent.lock())//未过期
    {
        cout << pp->Get() << endl;
    }
    else
        cout << "expired" << endl;
    std::cout << "5child use count = " << c.use_count() <<std::endl;
}
int main()
{
    shared_ptr<Child> c(new Child);
    std::cout << "1child use count = " << c.use_count() <<std::endl;
    Test(c);
    std::cout << "2child use count = " << c.use_count() <<std::endl;
    if (shared_ptr<Parent> pp = c->parent.lock())//未过期
    {
        cout << pp->Get() << endl;
    }
    else{
        cout << "expired" << endl;
        std::cout << "6child use count = " << c.use_count() <<std::endl;
    }
    return 0;
}

执行结果:

➜  build ./main
Child construction
1child use count = 1
3child use count = 1
Parent construction
4child use count = 2
3
5child use count = 2
Parent destruction
2child use count = 1
expired
6child use count = 1
Child destruction
➜  build 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值