1. 测试代码
#include <iostream>
#include <memory>
using namespace std;class B;
class A {
public:shared_ptr<B> pb;~A() { cout << "kill A\n";}
};class B {
public:shared_ptr<A> pa;~B() { cout << "kill B\n";}
};int main()
{shared_ptr<A> sa(new A());shared_ptr<B> sb(new B());if (sa && sb){sa->pb = sb;sb->pa = sa;}cout << "sa use count:" << sa.use_count() << endl;return 0;
}
输出结果:
2. 测试代码
#include <iostream>
#include <memory>
using namespace std;class B;
class A {
public:weak_ptr<B> pb;void doSomthing(){shared_ptr<B> pp = pb.lock();if (pp){cout << "sb use count:" << pp.use_count() << endl;}}~A() { cout << "kill A\n";}
};class B {
public:shared_ptr<A> pa;~B(){ cout << "kill B\n"; }
};int main()
{shared_ptr<A> sa(new A());shared_ptr<B> sb(new B());if (sa && sb){sa->pb = sb;sb->pa = sa;}sa->doSomthing();cout << "sb use count:" << sb.use_count() << endl;return 0;
}
输出结果: