      1  #include <iostream>
      2
      3  using namespace std;
      4
      5  class SharedString
      6  {
      7  public:
      8      SharedString();
      9      SharedString(const char* right);
     10      SharedString(const SharedString& right);
     11      ~SharedString();
     12      SharedString& operator=(const SharedString&);
     13  private:
     14      class StringReference;
     15      StringReference* p;
     16      void reassign(StringReference*);
     17  };
     18
     19  class SharedString::StringReference
     20  {
     21  public:
     22     int count;
     23     char* buffer;
     24     StringReference(const char* right);
     25     ~StringReference();
     26  };
     27
     28  SharedString::SharedString() : p(NULL)
     29  {
     30     cout << "Entering SharedString() \n";
     31  }
     32
     33  SharedString::SharedString(const char* right) : p(NULL)
     34  {
     35     reassign(new StringReference(right));
     36  }
     37
     38  SharedString::SharedString(const SharedString& right) : p(NULL)
     39  {
     40     reassign(right.p);
     41  }
     42
     43  SharedString::~SharedString()
     44  {
     45     reassign(NULL);
     46  }
     47
     48  SharedString& SharedString::operator=(const SharedString& right)
     49  {
     50     reassign(right.p);
     51     return *this;
     52  }
     53
     54  void SharedString::reassign(StringReference* np)
     55  {
     56     if (np != NULL) // Increment count on the new value
     57        np->count += 1;
     58     if (p != NULL)  // Decrement reference counts on old value
     59     {
     60        p->count -= 1;
     61        if (p->count == 0)
     62           delete p;
     63     }
     64     p = np;  // Change binding
     65  }
     66
     67  SharedString::StringReference::StringReference(const char* right)
     68  {
     69     count = 0;
     70     int n = 0;
     71     while (right[n] != '\0')
     72        n++;
     73     buffer = new char[1 + n];
     74     for (int i = 0; i < n; i++)
     75        buffer[i] = right[i];
     76     buffer[n] = '\0';
     77  }
     78
     79  SharedString::StringReference::~StringReference()
     80  {
     81     delete [] buffer;
     82  }
     83
     84  SharedString g; // global value
     85
     86  int main ( )
     87  {
     88          cout << "starting execution\n";
     89          cout << "SharedString a = \"Fred\";\n";
     90      SharedString a = "Fred";
     91          cout << "SharedString b = \"Alice\";\n";
     92      SharedString b = "Alice";
     93          cout << "SharedString c;\n";
     94      SharedString c;
     95          cout << "c = a;\n";
     96      c = a;
     97          cout << "a = b;\n";
     98      a = b;
     99          cout << "g = b;\n";
    100      g = b;
    101      cout << "return 0;\n";
    102      return 0;
    103  }