1.使用weak_ptr 不会导致 shared_ptr计数增加
2.weak_ptr不支持 *和->对指针进行访问
3.必要时使用 lock()可将weak_ptr转为shared_ptr
#include<iostream>
using namespace std;
class test {
public:
test() {
cout << "调用构造函数" << endl;
}
~test() {
cout << "调用析构函数" << endl;
}
void func() {
cout << "void func()" << endl;
}
};
int main(void) {
shared_ptr<test>sp(new test());
shared_ptr<test>sp2(new test());
//weak_ptr<test>wp(new test());//报错
weak_ptr<test>wp;
wp = sp;//使用共享赋值构造
weak_ptr<test>wp2(sp2);//使用共享构造
//使用weak_ptr 不会导致 shared_ptr计数增加
cout << "weak_ptr wp:" << wp.use_count() << endl;//1
cout << "shared_ptr:" << sp.use_count() << endl;//1
//weak_ptr不支持 *和->对指针进行访问
sp->func();
// wp->func();//报错
//必要时使用 lock()可将weak_ptr转为shared_ptr
shared_ptr<test>sp3;
sp3 = wp.lock();
cout << "---sp3 = wp.lock()---" << endl;
cout<<"shared_ptr sp3:" << sp3.use_count() << endl;
system("pause");
return 0;
}
结果: