+reference counting -copy on write // #include <iostream> #include <cstdio> #include <map> #include <vector> #include <set> #include <stack> #include <string> #include <string> #include <cassert> #include <queue> using namespace std; #define NULL 0 class MyString { friend ostream& operator<<(ostream &out,const MyString &s); public: MyString(const char* c="") { assert(c!=NULL); p=new char[strlen(c)+1]; strcpy(p,c); rCount=new unsigned; *rCount=1; } ~MyString() { GarbageCollection(); } MyString(const MyString &another) { p=another.p; rCount=another.rCount; ++*rCount; } const MyString& operator=(const MyString &another) { if(&another==this) return *this; GarbageCollection(); p=another.p; rCount=another.rCount; ++*rCount; return *this; } char &operator[](unsigned index) { assert(index<strlen(p)); return p[index]; } private: void GarbageCollection() { if(--*rCount==0) { delete rCount; delete[] p; cout << "Destructor~" << endl; } } private: char *p; //reference counting unsigned *rCount; }; ostream& operator<<(ostream &out,const MyString &s) { out << s.p; return out; } void Test() { //MyString str("abc"); //MyString str2=str; //MyString str3("xyz"); //cout << str << '/t' << str2 << '/t' << str3 << endl; //str2[1]='z'; //str=str3; //cout << str << '/t' << str2 << '/t' << str3 << endl; // MyString s1("aaa"); s1=s1; cout << s1 << endl; //MyString s1; //cout << s1; } int main() { // Test(); return 0; }