shared_ptr类
1 /* StrBlob.H */ 2 3 #include<iostream> 4 #include<string> 5 #include<vector> 6 #include<memory> 7 #include<initializer_List> 8 using namespace std; 9 10 class StrBlob { 11 public: 12 typedef vector<string>::size_type size_type; 13 StrBlob(); 14 StrBlob(initializer_list<vector<string>> il); 15 16 void check(int i, const string & msg) const; 17 18 bool empty() { return data->empty(); } 19 size_type size() const { return data->size(); } 20 void push_back(const string &t) { data->push_back(t); } 21 22 string &front(); 23 string &back(); 24 void pop_back(); 25 26 private: 27 shared_ptr<vector<string>> data; 28 void check(int i, const string &msg) const; 29 }; 30 31 StrBlob::StrBlob(): data(make_shared<vector<string>>()) {} 32 33 StrBlob::StrBlob(initializer_list<vector<string>> il): data(make_shared<vector<string>>(il)) {} 34 35 void StrBlob::check(int i, const string &msg) const 36 { 37 if (i >= data->size()) 38 throw out_of_range(msg); 39 } 40 41 string &StrBlob::front() 42 { 43 check(0, "front on empty StrBlob"); 44 return data->front(); 45 } 46 47 string &StrBlob::back() 48 { 49 check(0, "back on empty StrBlob"); 50 return data->back(); 51 } 52 53 void StrBlob::pop_back() 54 { 55 check(0, "pop_back on empty StrBlob"); 56 data->pop_back(); 57 }