string类的实现终极版
生活随笔
收集整理的這篇文章主要介紹了
string类的实现终极版
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
寫時拷貝(COW)的實現(xiàn):
#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?String&?str):_str(str._str){++(*(int*)(_str-4));}~String(){if(_str!=NULL){if(--(*(int*)(_str-4))){delete[]?(_str-4);}}}String&?operator=(const?String&?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&?os,const?String&?str);private:char?*_str; };ostream&?operator<<(ostream&?os,const?String&?str) {cout<<str._str<<endl;return?os; }int?main() {//String?s1("hello");String?s2("abcdefg");cout<<s2;cout<<s2[0];getchar();//String?s3=s2;//String?s3(s2);return?0; }轉(zhuǎn)載于:https://blog.51cto.com/luminous/1749228
總結(jié)
以上是生活随笔為你收集整理的string类的实现终极版的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: eclipse整体替换
- 下一篇: Delphi Qjson