12.1

b1和b2各包含4个元素,且这4个元素是b1和b2共享的。

更多:StrBlob的data成员是一个指向string的vector(即vector<string>)的shared_ptr,因此StrBlob的赋值不会拷贝vector的内容,而是多个StrBlob对象共享同一个vector对象。因此题目中尽管只是对b2进行了增加元素的操作,但结果就是b1和b2均包含4个string。

 

12.2

 1 #ifndef MY_STRBLOB_H
 2 #define MY_STRBLOB_H
 3 #include <iostream>
 4 #include <memory>
 5 #include <string>
 6 #include <initializer_list>
 7 #include <vector>
 8 #include <stdexcept>
 9 
10 //using声明在头文件中的全局作用域中
11 //在相应的实现文件就不要再次声明了 
12 using std::shared_ptr;
13 using std::make_shared;
14 using std::vector;
15 using std::string;
16 using std::initializer_list;
17 using std::out_of_range;
18 using std::cin;
19 using std::cout;
20 using std::endl;
21 
22 class StrBlob {
23 public:
24     using size_type = vector<string>::size_type;
25     StrBlob();
26     StrBlob(initializer_list<string> il);
27     size_type size() const { return data->size(); }
28     bool empty() const { return data->empty(); }
29     void push_back(const string &s);
30     void pop_back();
31     //返回string的引用,是因为调用点会使用该string
32     //如b.front() = "first"; 
33     string& front();
34     string& back();
35     //只有const StrBlob对象才会调用以下函数 
36     const string& front() const;
37     const string& back() const;
38 private:
39     shared_ptr<vector<string>> data;
40     void check(size_type i, const string &msg) const; 
41 }; 
42 
43 StrBlob::StrBlob(): data(make_shared<vector<string>>())
44 {
45 }
46 
47 StrBlob::StrBlob(initializer_list<string> il): data(make_shared<vector<string>>(il))
48 {    
49 }
50 
51 void StrBlob::check(size_type i, const string &msg) const
52 {
53     if (i >= data->size())
54         throw out_of_range(msg);
55 }
56 
57 void StrBlob::push_back(const string &s)
58 {
59     data->push_back(s);
60 }
61 
62 void StrBlob::pop_back()
63 {
64     check(0, "此StrBlob对象指向一个空vector!\n");
65     data->pop_back();
66 }
67 
68 string& StrBlob::front()
69 {
70     check(0, "此StrBlob对象指向一个空vector!\n");
71     return data->front();
72 }
73 
74 string& StrBlob::back()
75 {
76     check(0, "此StrBlob对象指向一个空vector!\n");
77     return data->back();
78 }
79 
80 const string& StrBlob::front() const
81 {
82     check(0, "此StrBlob对象指向一个空vector!\n");
83     cout << "调用对象为const StrBlob!\n";
84     return data->front();
85 }
86 
87 const string& StrBlob::back() const
88 {
89     check(0, "此StrBlob对象指向一个空vector!\n");
90     cout << "调用对象为const StrBlob!\n";
91     return data->back();
92 }
93 #endif
StrBlob.h

相关文章: