weak_ptr看起来更像shared_ptr的附属品,它从shared_ptr衍生,但不会控制所指向对象的生命周期。weak_ptr的弱就弱在这里。
1. 初始化
一共有三种形式,都非常简单,直接看代码:
shared_ptr<MyString> shpr = make_shared<MyString>("Hello shared_ptr");
cout << "shpr.get = " << shpr.get() << endl;
cout << "shpr.use_count = " << shpr.use_count() << endl;
//空weak_ptr
weak_ptr<MyString> wp1;
cout << "wp1.use_count = " << wp1.use_count() << endl;
//从shared_ptr构造weak_ptr
weak_ptr<MyString> wp2(shpr);
cout << "wp2.use_count = " << wp2.use_count() << endl;
//从其他weak_ptr构造weak_ptr
weak_ptr<MyString> wp3(wp2);
cout << "wp3.use_count = " << wp3.use_count() << endl;
/*
输出:
Constructed (Hello shared_ptr)!
shpr.get = 0x7fc419504098
shpr.use_count = 1
wp1.use_count = 0
wp2.use_count = 1
wp3.use_count = 1
Destructed (Hello shared_ptr)!
*/
虽然根据shared_ptr构造了两个weak_ptr,引用计数仍然为1。
2. 赋值
相应地,赋值操作同样简单:
shared_ptr<MyString> shpr = make_shared<MyString>("Hello shared_ptr");
cout << "shpr.get = " << shpr.get() << endl;
cout << "shpr.use_count = " << shpr.use_count() << endl;
weak_ptr<MyString> wp4;
weak_ptr<MyString> wp5;
wp4=shpr;
cout << "wp4.use_count = " << wp4.use_count() << endl;
wp5=wp4;
cout << "wp5.use_count = " << wp5.use_count() << endl;
cout << "shpr.get = " << shpr.get() << endl;
cout << "shpr.use_count = " << shpr.use_count() << endl;
输出:
Constructed (Hello shared_ptr)!
shpr.get = 0x7f8dcee059b8
shpr.use_count = 1
wp4.use_count = 1
wp5.use_count = 1
shpr.get = 0x7f8dcee059b8
shpr.use_count = 1
Destructed (Hello shared_ptr)!
*/
3. 使用
C++11标准库没有提供通过weak_ptr直接访问对象的方法,而是调用weak_ptr的lock方法生成一个shared_ptr,再通过shared_ptr访问对象:
上述示例输出为“127”,也就是说weak_ptr提供了一种按需锁定对象的手段。
其实,关于weak_ptr与shared_ptr之间的关系可参考:shared_ptr/weak_ptr示例