13.44 compile a simplified version of the string class in the standard library and name it string. Your class should have at least one default constructor and one constructor that accepts the C-style string pointer parameters. Use allocator to allocate the required memory for your string class.
13.47 Add a copy constructor and a copy value assignment operator, and add a print statement. A message is printed every time the function is executed.
13.48 define a vector <string> and call push_back multiple times on it. Run the program and observe how many times the string has been copied.
#include<iostream>#include<string>#include<memory>#include<utility>#include<cstring>#include<vector>using namespace std;class String{public: String()=default; String(char *c); String(const String&); String& operator=(const String&); string* begin() const { return elements;} string* end() const { return first_free;}private: static allocator<string> alloc; string *elements; string *first_free;};allocator<string> String::alloc;String::String(char *c){ size_t capacity=strlen(c); auto data=alloc.allocate(capacity); auto dest=data; string s; s.copy(c,strlen(c)); alloc.construct(dest++,s); elements=data; first_free=dest;}String::String(const String &s){ cout<<"copy construct"<<endl; auto capacity=s.end()-s.begin(); auto data=alloc.allocate(capacity); uninitialized_copy(s.begin(),s.end(),data); elements=data; first_free=data+capacity;}String& String::operator=(const String &s){ cout<<"copy = construct"<<endl; auto capacity=s.end()-s.begin(); auto data=alloc.allocate(capacity); uninitialized_copy(s.begin(),s.end(),data); if(elements) { auto begin=elements; auto end=first_free; while(begin!=end) alloc.destroy(begin++); alloc.deallocate(elements,first_free-elements); } elements=data; first_free=data+capacity; return *this;}int main(){ vector<String> vec; char ch[]="hello"; char ch1[]="world!"; cout<<vec.capacity()<<endl; cout<<endl; vec.push_back(String(ch)); cout<<vec.capacity()<<endl; cout<<endl; vec.push_back(String(ch1)); cout<<vec.capacity()<<endl; cout<<endl; vec.push_back(String(ch)); cout<<vec.capacity()<<endl; cout<<endl; vec.push_back(String(ch1)); cout<<vec.capacity()<<endl; cout<<endl; vec.push_back(String(ch1)); cout<<vec.capacity()<<endl; cout<<endl; vec.push_back(String(ch1)); cout<<vec.capacity()<<endl; return 0;}
Running result:
Explanation: http://blog.csdn.net/HEYUTAO007/article/details/6702626
Custom string class and add custom types to STL containers