智能指针使用
void Check(weak_ptr<int> &wp)
{
shared_ptr<int> sp = wp.lock();
if (sp != nullptr) {
cout<<"still "<<*sp<<endl;
} else {
cout<<"pointer is invalid."<<endl;
}
}
int main()
{
shared_ptr<int> sp1(new int(33));
shared_ptr<int> sp2 = sp1;
weak_ptr<int> wp = sp1;
cout<<*sp1<<endl;
cout<<*sp2<<endl;
Check(wp);
sp1.reset();
cout<<*sp2<<endl;
Check(wp);
sp2.reset();
Check(wp);
}
输出结果
33
33
still 33
33
still 33
pointer is invalid.
说明:weak_ptr可以用在校验shared_ptr的有效性,如Check函数使用。