shared_ptr引用计数功能,weak_ptr解决循环引用

链接:​​​​​​C++:智能指针(2)——shared_ptr引用计数功能,weak_ptr解决循环引用_cocoa0409的博客-CSDN

这一篇代码比较完整
C++智能指针weak_ptr详解_sinat_31608641的博客-CSDN博客_weakptr

如果不用weak_ptr,结果如下:导致无法析构

using namespace std;
class Parent;

class Child
{
public:
    shared_ptr<Parent> parent;
    Child() { cout << "hello Child" << endl; };
    ~Child() { cout << "bye Child" << endl; };  
};

class Parent
{
public:
    shared_ptr<Child> child;
    Parent() { cout << "hello Parent" << endl; };
    ~Parent() { cout << "bye Parent" << endl; };
    int GetNum(){return num;}
    void AddNum(){num++;}
private:
    int num = 0;
};

void ShowInfo()
{
    shared_ptr<Parent> parent(new Parent());
    shared_ptr<Child> child(new Child());
    parent->child = child;
    child->parent = parent;
    for (int i = 0; i < 10; ++i){parent->AddNum();}

    if (shared_ptr<Parent> var = child->parent)//如果未过期
    {
        cout << "Parent num is:" << var->GetNum() << endl;
    }
    else
        cout << "Parent is expired" << var->GetNum() << endl;
}
int main()
{
    ShowInfo();
    return 0;
}



 

 采用weak_ptr,结果如下:解决循环引用问题

using namespace std;

class Parent;

class Child
{
public:
    Child()=default;
	~Child() = default;
    weak_ptr<Parent> parent;
};

class Parent
{
public:
    Parent() = default;
    ~Parent() = default;
    shared_ptr<Child> child;
    int Get() { return 3; };
};

void Test(shared_ptr<Child>& c)
{
   shared_ptr<Parent> p(new Parent());
    c->parent = p;
    p->child = c;
    if (shared_ptr<Parent> pp = c->parent.lock())//未过期
    {
        cout << pp->Get() << endl;
    }
    else
        cout << "expired" << endl;
}
int main()
{
    shared_ptr<Child> c(new Child);
    Test(c);
    if (shared_ptr<Parent> pp = c->parent.lock())//未过期
    {
        cout << pp->Get() << endl;
    }
    else
        cout << "expired" << endl;
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值