智能指针 (五)
weak_ptr waptr(aptr);
aptr->bptr = bptr;
bptr->aptr = waptr;
cout << "ref count of bptr: " << bptr.use_count() << endl;
cout << "ref count of aptr: " << waptr.use_count() << endl;
cout << "end" << endl;
}
int main()
{
test();
cout << "after test" << endl;
}
运行结果:
[plain]
begin
ref count of bptr: 2
ref count of aptr: 1
end
ref count of B: 1
deconstruct A
ref count of A: 0
deconstruct B
after test
begin
ref count of bptr: 2
ref count of aptr: 1
end
ref count of B: 1
deconstruct A
ref count of A: 0
deconstruct B
after test
可以看到A和B都被析构了,并且在test函数的结尾处,检查aptr的引用计数是1,而bptr是2,这是因为weak_ptr指向这个对象,不会引起引用计数的改变。