Write-time copy (COW) implementation:
#include <iostream> #include <cassert>using namespace std;class string{public:string ( Char *str= ""): _str (New char[strlen (str) +sizeof (int) +1]) {* (int*) _str=1;_str+=4;strcpy (_STR,STR);} String (CONST&NBSP;STRING&&NBSP;STR): _str (STR._STR) {+ + (* (int*) (_str-4));} ~string () {if (_str!=null) {if (--(* (int*) (_str-4))) {delete[] (_str-4);}} String& operator= (CONST&NBSP;STRING&&NBSP;STR) {if (THIS!=&STR) {if (--(* (int*) (_str-4))) {delete[ ] (_str-4);} _str=str._str;++ (* (int*) (_str-4));} Return *this;} Char& operator[] (Int index) {assert (Index>=0 && index<strlen (_STR)); _str[ index]=* (_str+index); return _str[index];} friend ostream& operator<< (OSTREAM&&NBSP;OS,CONST&NBSP;STRING&&NBSP;STR);p rivate: Char *_str;};o stream& operator<< (ostream& os,const string& str) {Cout<<str._str <<endl;return os;} Int main () {//STRING&NBSP;S1("Hello"); STRING&NBSP;S2 ("ABCDEFG"); Cout<<s2;cout<<s2[0];getchar ();//string s3=s2;//string s3 (S2); return 0;}
This article is from the "July boreas" blog, please be sure to keep this source http://luminous.blog.51cto.com/10797288/1749228
Implementation of the String Class Ultimate Edition