A More Comprehensive Example
Because copies of RWCStrings are so inexpensive, you are encouraged to store them by value inside your objects, rather than storing a pointer. This will greatly simplify their management, as the following comparison demonstrates. Suppose you have a window whose background and foreground colors can be set. A simple-minded approach to setting the colors would be to use pointers as follows:
 
class SimpleMinded {
const RWCString* foreground;
const RWCString* background;
public:
setForeground(const RWCString* c) {foreground=c;}
setBackground(const RWCString* c) {background=c;}
};
On the surface, this approach is appealing because only one copy of the string need be made. In this sense, calling setForeground() seems efficient. However, a closer look indicates that the resulting semantics can be muddled: what if the string pointed to by foreground changes? Should the foreground color change? If so, how will class Simple know of the change? There is also a maintenance -problem: before you can delete a color string, you must know if anything is still pointing to it.
Here is a much easier approach:
 
class Smart {
RWCString foreground;
RWCString background;
public:
setForeground(const RWCString& c) {foreground=c;}
setBackground(const RWCString& c) {background=c;}
Now the assignment foreground=c will use value semantics. The color that class Smart should use is completely unambiguous. Copy on write makes the process efficient, too, since a copy of the data will not be made unless the string should change. The next example maintains a single copy of white until white is changed:
 
Smart window;
RWCString color("white");
window.setForeground(color); // Two references to white
color = "Blue"; // One reference to white, one to blue