概述
练习13.49 13.50
1 #include <iostream> 2 #include <string> 3 #include <utility> 4 #include <memory> 5 #include <algorithm> 6 #include <vector> 7 8 using namespace std; 9 10 class String { 11 friend ostream &print(ostream &os, String &s); 12 public: 13 String(): element(nullptr), first_free(nullptr) {} 14 String(char *); 15 size_t size() const{ return first_free - element; } 16 String(const String&); 17 String& operator=(const String&); 18 String(String&&) noexcept; 19 String& operator=(String&&) noexcept; 20 ~String() { free(); } 21 private: 22 static allocator<char> alloc; 23 pair<char *, char *> alloc_n_copy(const char*, const char *); 24 void free(); 25 char *element; 26 char *first_free; 27 }; 28 allocator<char> String::alloc; 29 ostream &print(ostream &os, String &s); 30 31 int main() 32 { 33 vector<String> vec; 34 String s1("hello"); 35 String s2("world"); 36 String s3(s1); 37 String s4 = s2; 38 s3 = s1; 39 String s5 = std::move(s4); 40 vec.push_back(s1); 41 vec.push_back(s2); 42 vec.push_back(s3); 43 vec.push_back(s4); 44 vec.push_back(s5); 45 system("pause"); 46 return 0; 47 } 48 49 String::String(char *s) 50 { 51 int i = 0; 52 while (s[i] != '