String classes encapsulate the behavior of an array of characters. Usual implementations have copy constructors and overloaded assignment operator for performing allocation and copy of the encapsulated character array. For all functions, which take an instance of such a class, results in creation of a temporary object and invokes the copy constructor. The copy constructor in turn makes a copy of the whole string. This leads to a lot of wastage in terms of memory as well as processing power.
An efficient way of handling this situation is to reference count the objects. The example here demonstrates how to perform reference counting on objects. The reference-counted string class implementation presented here is a simple but full blown class that can be used in your projects as-is. Here, in the copy constructor, we don't make a copy of the whole string, but instead we increment the reference count of that string thus implying that more than one people are using it. In the destructor, we decrement the reference count implying that there is one less person pointing to it. During assignment, we decrement the reference count for the current string, point to the new string and increment the reference count of the new string. The string destroys itself when its reference count reaches zero.
Download: A Reference-Counted String Class (cdstring.zip)