string类的实现终极版

来源:互联网 发布:仿起点小说php源码 编辑:程序博客网 时间:2024/06/05 17:35

写时拷贝(COW)的实现:

#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;}


本文出自 “七月朔风” 博客,请务必保留此出处http://luminous.blog.51cto.com/10797288/1749228

0 0
原创粉丝点击