Assignment #2: More C++ Classes and Operator Overloading

Implement a String class with lazy copy semantics. Lazy copy semantics means that the basic operations to copy a String, namely operator= and the copy constructor do not actually do a deep copy. Instead, they share basic information. This works great, as long as none of the Strings that are sharing the basic state are changed. But if a mutator is applied a String whos internal state is being shared, then you have to be unshare the String from its copies prior to applying the mutator. Thus, the mutator will force the actual copy to occur.

The details of basic idea requires you to define a nested StringObject struct:

class String
{
    ...

  private:
    struct StringObject
    {
        char *buffer;
        int strLength;
        int bufferLength;
        int referenceCount;   // The number of String that share this.
    };

    StringObject *data;
};
The String class stores a pointer to StringObject. A copy constructor can then simply copy the pointers, and add one to the referenceCount. The destructor will decrement the referenceCount, and if it falls to zero, reclaim the StringObject (so StringObject should have a destructor). Clearly, the accessors are easily implemented by following the pointer. The mutators require that you make a deep copy of the StringObject (if it is being shared) since at that point, the StringObject can no longer be shared. In that case you will also need to decrement the referenceCount for the pre-existing StringObject. A special case is operator=, which can replace its existing StringObject with a different existing StringObject, adjusting reference counts.