Tools.h++ Manual
19-2 104011 Tandem Computers Incorporated
19
1. The
RWCString
object "
a
" is where the actual allocation and
initialization of the memory to hold the string "
kernel
" happens.
2–3 When objects "
b
" and "
c
" are created from it, they merely increment a
reference count in the original data and return. At this point, there are
three objects looking at the same piece of data.
4 The function
setGlobal()
sets the value of the global
RWCString g
to
the same value. Now the reference count is up to four, and there is still
only one copy of the string "
kernel
."
5 Finally, object "
b
" tries to change the value of the string. It looks at the
reference count and sees that it is greater than one, implying that the
string is being shared by more than one object. It is at this point that a
clone of the string is made and modified. The reference count of the
original string drops back down to three, while the reference count of the
newly cloned string is one.
Amore 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. Here's an example. Suppose you have a
window whose background and foreground colors can be set. A simple
minded approach to do this would be:
RWCString c(a);// 3
setGlobal(a);// Still only one copy of "kernel"! // 4
b += "s";// Now b has its own data: "kernels"// 5
}
class SimpleMinded {
const RWCString* foreground;
const RWCString* background;
public:
setForeground(const RWCString* c) {foreground=c;}
setBackground(const RWCString* c) {background=c;}
};
#include <rw/cstring.h>