因为weak_ptr指向的对象可能不存在(shared_ptr指向的最后一个对象被销毁时),因而用它不能直接访问对象,必须调用lock函数检查其指向的对象是否存在。很容易写出一个选择语句进行控制:
?
- auto bb = make_shared<string>(2, 'b'); weak_ptr<string> xbb(bb);
- if (shared_pr<int> np = xbb.lock()) { // np不为空条件成立 // 在if语句内,np和xbb共享对象
- }
补充weak_ptr相关的函数,便于理解:
w.reset 将w置为空
w.use_count() 与w共享对象的个数
w.expired() 若w.use_count()为0,返回true,否则返回false
w.lock() 若w.expired()为true,返回一个空shared_ptr,否则返回一个指向w的对象的shared_ptr
加入《C++ Primer 5th》中的12.19题参照,题中和“智能指针和异常”并未在本篇随笔中介绍
- #include <iostream> #include <string>
- #include <vector> #include <memory>
- #include <initializer_list> using namespace std;
- using std::string; using std::vector;
- class StrBlobPtr; class StrBlob {
- public: friend class StrBlobPtr; // 友元
- StrBlobPtr begin(); // 声明StrBlob类中的begin()和end() StrBlobPtr end(); // 返回一个指向它自身的StrBlobPtr
- public: typedef vector<string>::size_type size_type; // 类型别名,size_type = vector<string>::size_type
- StrBlob::StrBlob(initializer_list<string> il) : data(make_shared<vector<string>>(il)) {}; // 接受一个initializer_list参数的构造函数将其参数传 递给对应的vector构造函数,通过拷贝列表










