Copy on write – HP Integrity NonStop J-Series User Manual
Page 270

Click on the banner to return to the user guide home page.
©Copyright 1996 Rogue Wave Software
Copy on Write
Classes
RWCString
,
RWWString
, and
RWTValVirtualArray
use a technique called copy on
write to minimize copying. This technique offers the advantage of easy-to-understand value
semantics with the speed of reference counted pointer implementation.
Here is how the technique works. When an
RWCString
is initialized with another RWCString via
the copy constructor:
RWCString(const RWCString&);
the two strings share the same data until one of them tries to write to it. At that point, a copy of
the data is made and the two strings go their separate ways. Copying only at "write" time makes
copies of strings, particularly read-only copies, very inexpensive. In the following example, you
can see how four objects share one copy of a string until one of the objects attempts to change
the string:
#include
RWCString g; // Global object
void setGlobal(RWCString x) { g = x; }
main(){
RWCString a("kernel"); // 1
RWCString b(a); // 2
RWCString c(a); // 3
setGlobal(a); // Still only one copy of "kernel"! // 4
b += "s"; // Now b has its own data: "kernels" // 5
}
//1
The actual allocation and initialization of the memory to hold the string kernel occurs
at the
RWCString
object a.
//2 - //3 When objects b and c are created from a, 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.