weak_ptr是一种不控制对象生存周期的智能指针,它指向一个shared_ptr管理的对象...它不会改变shared_ptr的引用计数——《C++ Primer .5th》。很明显,weak_ptr的特点是“弱引用”。有什么用?应用场景是什么地方?
考虑它的胞兄shared_ptr,每次复制之后引用计数加一,不再指向对象(自身销毁或指向其他对象)时时引用计数减一,减至零值调用所管理资源对象的析构函数。考虑这样一个情况,两个对象各自包含指向彼此的shared_ptr成员,形成环状引用,引用计数永远为1,不能销毁,造成内存泄漏。
//x86_64 win7_64 vs2013 ultimate
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class A;
class B;
class A{
public:
~A(){ cout << "destroying A\n" ; }
shared_ptr<B> pb;
};
class B{
public:
~B(){ cout << "destroying B\n" ; }
shared_ptr<A> pa;
};
void test(){
shared_ptr<A> a(new A());
shared_ptr<B> b(new B());
a->pb = b;
b->pa = a;
}
int main(){
cout << "begin test...\n";
test();
cout << "end test\n";
}
outpu