weak_ptr解决环形引用

// ConsoleApplication10.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "ConsoleApplication10.h"
#include
#include
using namespace std;

class B;
class A
{
public:
    A() { cout << "A()" << endl; };
    ~A() { cout << "~A()" << endl; };

    //shared_ptr m_b;//解开示例代码一注释
    //weak_ptr m_b; //解开示例代码二注释
};

class B
{
public:
    B() { cout << "B()" << endl; };
    ~B() { cout << "~B()" << endl; };

    shared_ptr m_a;
};


int main()
{
    //环形引用代码示例:解开示例代码一注释
    shared_ptr
pa = make_shared();
    shared_ptr pb = make_shared();

    cout << "pa,pb:" << pa.use_count() << "," << pb.use_count() << endl;

    pa->m_b = pb;
    pb->m_a = pa;

    cout << "pa,pb:" << pa.use_count() << "," << pb.use_count() << endl;

    //weak_ptr解决环形引用:解开示例代码二注释

    
    return 0;
}

你可能感兴趣的:(C,C++)