模拟shared_ptr循环引用

时间:2018-03-15 14:44:45

标签: c++

我想创建两个对象,彼此共享一个shared_ptr,故意在visual studio中创建循环引用案例,调试器疯了(正如预期的那样,在快照中显示),但程序仍然执行(为什么?)和给出结果。我现在想用weak_ptr替换指针,但是怎么做?

struct B;
struct A
{
    void print() { cout << "A " << endl; }
    shared_ptr<B> pB;
};


struct B
{
    void print() { cout << "B " << endl; }
    shared_ptr<A> pA;
};

int main()
{
    shared_ptr<A> a = make_shared<A>(); 
    shared_ptr<B> b = make_shared<B>();

    a->pB = b;
    b->pA = a;
    a->print();
    a->pB->print();

    a.reset();

    b->pA->print();

    return 0;
}

enter image description here

1 个答案:

答案 0 :(得分:1)

使用std::weak_ptr,它看起来像:

struct B;
struct A
{
    void print() const { std::cout << "A " << std::endl; }
    std::weak_ptr<B> pB;
};

struct B
{
    void print() const { std::cout << "B " << std::endl; }
    std::weak_ptr<A> pA;
};

int main()
{
    auto a = std::make_shared<A>(); 
    auto b = std::make_shared<B>();

    a->pB = b;
    b->pA = a;
    a->print();
    auto wb = a->pB.lock();
    if (wb) { wb->print(); } else { std::cout << "nullptr\n"; }

    a.reset();

    auto wa = b->pA.lock();
    if (wa) { wa->print(); } else { std::cout << "nullptr\n"; }
}

Demo