Streaming supports the detection and correct handling of aliased pointers to objects.
Suppose that:
Without the detection of aliased objects, writing A and B to the stream would cause two copies of C to be written to the stream. Reading the streamed data back in would then result in the creation of two copies of C, one associated with A, the other with B. This would not only waste memory, but would also be logically incorrect. Changes made in one copy of C would not be reflected in the other, and thus would not be seen by both A and B.
With the appropriate use of writeAliasedObject instead of plain writeObject, the duplicate write of C would be recognized, and would be replaced by a flag, on the stream, that refers back to the initial write. When A and B are read, only one C would be created. The pointers in both A and B would refer to this single object.
Note: For some derived classes with multiple virtual inheritance, base classes may be reachable through multiple paths of the inheritance hierarchy. When a client streams a single instance of the derived class, the base class streaming functions may be invoked more than once. However, streaming classes ensure that there will no adverse effect on the results.
Monomorphic streaming is used when you know the exact type of the data you are streaming. Compared to polymorphic streaming, this can save some overhead. Monomorphic streaming is useful for simple data types, and structs and objects without vtables.
Polymorphic streaming is used to stream an object given a pointer or reference to one of its base classes. This is similar to calling a function which takes a base class pointer, but passing in a pointer to a derived type. When a client reads from the stream, objects of the correct type are automatically constructed and initialized from the stream data.
Consider, for example, the subclasses of IMGraphic. A typical drawing has lines, ellipses, and curves, as well as polygons. If you are streaming out many of these objects, you don't want to have to remember the precise sequence of data types that you have streamed out. Polymorphism lets you classify all these objects as an IMGraphic. You can then let the runtime type system figure out the precise class of the object being streamed in to a pointer of type IMGraphic.
Polymorphic streaming, however, incurs more overhead than monomorphic streaming in terms of time and space. Polymorphic streaming includes the type of each object along with the object's state in the external (stream) representation of the object. This extra information gives the runtime system the information it needs to reconstruct the correct object when it is streamed back in.
Introduction to the
Streaming Classes
Data Streams
Exceptions Defined by the
Streaming Classes
Streaming
Aliases and Aliased Objects
Streaming
Objects Monomorphically
Streaming
Objects Polymorphically
Transitioning
from Older Streaming Constructs