智能指针 (二)
)
{
test();
cout << "after test" << endl;
}
#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;
}
shared_ptr aptr;
};
void test()
{
cout << "begin" << endl;
shared_ptr aptr(new A);
shared_ptr bptr(new B);
aptr->bptr = bptr;
bptr->aptr = aptr;
cout << "ref count of bptr: " << bptr.use_count() << endl;
cout << "ref count of aptr: " << aptr.use_count() << endl;
cout << "end" << endl;
}
int main()
{
test();
cout << "after test" << endl;
}
运行程序,可以发现A和B都没有被析构。下面通过weak_ptr解决这种循环引用的问题。
[plain]
begin
ref count of bptr: 2
ref count of aptr: 2
end
after test
begin
ref count of bptr: 2
ref count of aptr: 2
end
after test
3. weak_ptr
weak_ptr不管理对象的生命周期,但是可以感知一个对象的生死。weak_ptr是弱引用,用它指向一个对象,不会增加其引用计数。weak_ptr指向的对象底层有shared_ptr管理,要通过weak_ptr访问这个对象,必须构造成shread_ptr才行。具体可以通过shared_ptr的构造函数或者是lock方法。当最后一个指向该对象的shared_ptr被销毁时,该对象也会被销毁。此时,调用shared_ptr的构造函数会抛出boost::bad_weak_ptr异常,lock返回的shared_ptr是空的。
weak_ptr实现了拷贝构造函数、赋值运算符和比较运算符所以可以放入stl容器和关联容器中。