references count 以及copy on write

 

  产生一个reference-counted String class 并不困难,但是必须注意许多细节。

  比如 copy-on-write

         Pointers,References,以及copy-on-Write

         考虑以下代码:

         String s1 = "hello";

         char *p =&s1[1];

         String s2 = s1;

         *p ='x'; //同时修改了 s1 s2,这不是用户想要的

 

 

#include <iostream> using namespace std; class String { public: String(const char *realvalue); String(const String& rhs); String& operator = (const String& rhs); char& operator[] (size_t num); const char& operator[] (size_t num) const ; ~String(); private: struct Stringvalue { int count; bool sign; char *date; Stringvalue(const char *thevalue); ~Stringvalue(); }; Stringvalue *value; }; String::String(const char *realvalue):value(new Stringvalue(realvalue)) { } String::String(const String& rhs) { if(rhs.value->sign) { value = rhs.value; ++rhs.value->count; } else { value = new Stringvalue(rhs.value->date); } } String& String::operator =(const String &rhs) { if(this == &rhs) { return *this; } if(--value->count == 0) { delete value; } if(rhs.value->sign) { value = rhs.value; ++rhs.value->count; } else { value = new Stringvalue(rhs.value->date); } return *this; } char& String::operator [] (size_t num) { if(value->count > 1) { --value->count; value = new Stringvalue(value->date); } value->sign = false; return value->date[num]; } const char& String::operator [] (size_t num) const { return value->date[num]; } String::~String() { cout<<"~String()"<<endl; if(--value->count == 0) delete value; } String::Stringvalue::Stringvalue(const char *thevalue) :count(1),sign(true) { date = new char[strlen(thevalue)+1]; strcpy(date,thevalue); } String::Stringvalue::~Stringvalue() { cout<<"~Stringvalue()"<<endl; delete []date; } void fun() { String s1("hello world"); char *p = &s1[1]; //String s2("hello"); String s2(s1); String s3 = s1; *p = 'E'; cout<<"s1[1]:"<<s1[1]<<endl; cout<<"s2[1]:"<<s2[1]<<endl; cout<<"s3[1]:"<<s3[1]<<endl; } int main() { fun(); system("pause"); return 0; } 

你可能感兴趣的:(references count 以及copy on write)