C++智能指针读书笔记

2020-01-06 14:01:15于海丽
  •   StrBlob::StrBlob() : data(make_shared<vector<string>>()) {};                 // 构造函数,初始化data成员,指向动态分配的vector                                                            中的值初始化vector元素    void push_back(const string &t) { data->push_back(t); } 
  •   string& StrBlob::front() {      check(0, "front on empty StrBlob"); 
  •     return data->front();    } 
  •   string& StrBlob::back() {      check(0, "back on empty StrBlob"); 
  •     return data->back();    } 
  •   void StrBlob::pop_back() {             // 删除尾元素      check(0, "pop_back empty StrBlob"); 
  •     return data->pop_back();    } 
  •   string& front() const { return data->front(); };    string& back() const { return data->back(); }; 
  • private:    shared_ptr<vector<string>> data; 
  •   void StrBlob::check(size_type i, const string &msg) const {  // 检查元素是否存在      if (i >= data->size())                  // 若不存在 
  •       throw out_of_range(msg);               // 抛出异常    } 
  • };  class StrBlobPtr { 
  • public:    StrBlobPtr() : curr(0) {}; 
  •   StrBlobPtr(StrBlob &a, size_t sz = 0) : wptr(a.data), curr(sz) {};    string & deref() const { 
  •     auto p = check(curr, "dereference past end");      return (*p)[curr];  // check成功,返回一个p指针,指向make_shared指向的vector