shared_ptr 的循环依赖问题

#include <memory>
#include <iostream>
using namespace std;

struct A;
struct B;
struct A {
    shared_ptr<B> B_ptr;
    A() {
        cout << "construct A" << endl;
    }
    ~A() {
        cout << "destory A" << endl;
    }
};

struct B {
    shared_ptr<A> A_ptr;
    B() {
        cout << "construct B" << endl;
    }
    ~B() {
        cout << "destroy B" << endl;
    }
};

void loop() {
    shared_ptr<A> ap(new A()); // ap 的引用计数是1
    shared_ptr<B> bp(new B()); // bp 的引用计数是1
    cout << ap.use_count() << endl;
    cout << bp.use_count() << endl;
    ap -> B_ptr = bp; //ap的引用计数是2
    bp -> A_ptr = ap; //bp的引用计数是2
    cout << ap.use_count() << endl;
    cout << bp.use_count() << endl;
    // 将 ap 所指向的对象记作 Aobj,将bp所指向的对象记作 Bobj。
    // 准备析构 bp, 此时Bobj的use_count 是 2,因此析构bp不会销毁 Bobj,而是使 Bobj的use_count变为1。
    // 注意:此时 Aobj 的 use_count 是 2,一个来自 ap, 另一个来自 Bobj.A_ptr(记住:Bobj 并未被销毁)
    // 同理析构 ap 只会把 ap的use_count变为 1 而不会销毁 Aobj。这样就造成内存泄漏了。
}

int main() {
    loop();
    return 0;
}

References

Circular dependency issues with std::shared_ptr, and std::weak_ptr

转载于:https://www.cnblogs.com/Patt/p/10654148.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值