#include <iostream>#include <memory>using namespace std;/*** 如何对shared_ptr, weak_ptr空指针进行判断?* 除了常规的shared_ptr::get, use_count(), 测试直接用if语句进行判断*/int main(){std::shared_ptr<int> p1;std::shared_ptr<int> p2(new int);cout << "p1.use_count = " << p1.use_count() << endl; // p1.use_count = 0cout << "p2.use_count = " << p2.use_count() << endl; // p2.use_count = 1if (p1) cout << "p1 is not null" << endl;else cout << "p1 is null" << endl; // p1 is nullif (p2) cout << "p2 is not null" << endl; // p2 is not nullelse cout << "p2 is null" << endl;std::weak_ptr<int> p3;std::weak_ptr<int> p4(p1);std::weak_ptr<int> p5(p2);cout << "p3.use_count = " << p3.use_count() << endl; // p3.use_count = 0cout << "p4.use_count = " << p4.use_count() << endl; // p4.use_count = 0cout << "p5.use_count = " << p5.use_count() << endl; // p5.use_count = 1if (p3.lock()) cout << "p3 is not null" << endl;else cout << "p3 is null" << endl; // p3 is nullif (p4.lock()) cout << "p4 is not null" << endl;else cout << "p4 is null" << endl; // p4 is nullif (p5.lock()) cout << "p5 is not null" << endl; // p5 is not nullelse cout << "p5 is null" << endl;return 0;}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。