智能指针 (三)

2014-11-23 23:11:57 · 作者: · 浏览: 21
下面看一下,weak_ptr是如何解决循环引用,将类B中指向aptr的shared_ptr改为weak_ptr即可。
[cpp]
#include
#include
#include
using namespace std;
using namespace boost;
class B;
class A {
public:
~A() {
cout << "ref count of B: " << bptr.use_count() << endl;
cout << "deconstruct A" << endl;
}
shared_ptr bptr;
};
class B {
public:
~B() {
cout << "ref count of A: " << aptr.use_count() << endl;
cout << "deconstruct B" << endl;
}
weak_ptr aptr;
};
void test()
{
cout << "begin" << endl;
shared_ptr bptr(new B);
aptr->bptr = bptr;
bptr->aptr = waptr;