【4】weak_ptr
//引入weak_ptr解决循环引用问题
#include <iostream>
#include <memory>
using namespace std;
class Test;
class Demo
{
public:
weak_ptr<Test> t; //指向Test类的弱智能指针
Demo(){cout << "Demo的无参构造" << endl;}
~Demo(){cout << "Demo的析构" << endl;}
};
class Test
{
public:
weak_ptr<Demo> d; //指向Demo类的弱智能指针
Test(){cout << "Test的无参构造" << endl;}
~Test(){cout << "Test的析构" << endl;}
};
int main()
{
shared_ptr<Demo> p1(new Demo);
shared_ptr<Test> p2(new Test);
p1->t = p2; //让p1中的指针成员指向p2
p2->d = p1; //让p2中的指针成员指向p1
cout << "p1的计数:" << p1.use_count() << endl;
cout << "p2的计数:" << p2.use_count() << endl;
//weak_ptr<Demo> p3(new Demo); weak_ptr不能独立使用,不能自己指向堆区的空间,需要使用shared_ptr赋值
weak_ptr<Demo> p3(p1);
cout << "p1的计数:" << p1.use_count() << endl;
return 0;
}