StrBlob: 共享字符串数组
2023年12月28日 2023年12月30日
说明
StrBlob拷贝构造函数的合成版本拷贝指向vector容器的shared_ptr
实现
1#include <iostream> 2#include <vector> 3#include <string> 4#include <initializer_list> 5#include <memory> 6 7using std::cout; 8using std::endl; 9using std::initializer_list; 10using std::make_shared; 11using std::ostream; 12using std::shared_ptr; 13using std::string; 14using std::vector; 15 16class StrBlob 17{ 18 friend ostream &operator<<(ostream &os, const StrBlob &sb); 19public: 20 typedef vector<string>::size_type size_type; 21 StrBlob(); 22 StrBlob(initializer_list<string> il); 23 // 使用合成的拷贝构造函数和拷贝赋值运算符 24 size_type size() const { return data->size(); } 25 bool empty() const { return data->empty(); } 26 void push_back(const string &t) { data->push_back(t); } 27 void pop_back(); 28 string &front(); 29 string &back(); 30private: 31 shared_ptr<vector<string>> data; 32 void check(size_type i, const string &msg) const; 33}; 34 35// 创建一个StrBlob对象,为data申请内存 36StrBlob::StrBlob() : data(make_shared<vector<string>>()) { } 37 38// 创建一个StrBlob对象,为data申请内存并初始化 39StrBlob::StrBlob(initializer_list<string> il): data(make_shared<vector<string>>(il)) { } 40 41// 检查给定位置的有效性 42void StrBlob::check(size_type i, const string &msg) const 43{ 44 if (i >= data->size()) 45 throw std::out_of_range(msg); 46} 47 48// 若容器不空: 返回首元素或者尾元素,删除尾元素 49string& StrBlob::front() 50{ 51 check(0, "front on empty StrBlob"); 52 return data->front(); 53} 54string& StrBlob::back() 55{ 56 check(0, "back on empty StrBlob"); 57 return data->back(); 58} 59void StrBlob::pop_back() 60{ 61 check(0, "pop_back on empty StrBlob"); 62 data->pop_back(); 63} 64 65ostream &operator<<(ostream &os, const StrBlob &sb) 66{ 67 for (const string &s : *(sb.data)) 68 os << s << "\t"; 69 return os; 70} 71 72int main() 73{ 74 StrBlob sb{"Hat", "Shoe"}, sb2 = sb; 75 cout << sb2 << endl; 76 77 sb.pop_back(); 78 cout << sb2 << endl; 79 80 return 0; 81}
输出
Hat Shoe Hat