Persisting the Serializable Objects
Now that the classes have been prepared with serialization support, consider the code that could be used to persist the residential and rural_land objects — as pointers to real_property — at application shutdown, and restore these objects when the application is restarted. The main logic for the example application is in listing.cpp.
But before looking at the main logic, there is one more setup requirement. Recall from the use case description that at application shutdown the RWTPtrOrderedVector collection of real_property objects is written out to a file as a single operation. When the application is restarted, it reads in the file and restores the RWTPtrOrderedVector collection with all its real_property objects.
For this to work, you must make the RWTPtrOrderedVector collection serializable. To do this, apply the macro RW_DECLARE_STREAMABLE_PTR_SEQUENCE() on the collection. This macro declares the global input and output operators needed for streaming a collection of pointers. This macro can occur anywhere in the code so long as it is guaranteed to occur after the #include of the header file for RWTPtrOrderedVector, which is tpordvec.h. Since this include occurs in listing.cpp, this is the safest place to apply the macro.
Here is the code that includes the collection and prepares it for serialization:
 
// from listing.cpp
 
// Get the header file for RWTPtrOrderedVector
#include <rw/tpordvec.h>
 
// Create global operators to support streaming of an
// RWTPtrOrderedVector collection
RW_DECLARE_STREAMABLE_PTR_SEQUENCE(RWTPtrOrderedVector)
Now you are ready to look at the main logic, beginning with the code for persisting the collection of real_property objects at application shutdown.
 
// Here is the shutdown processing, which
// - creates an output stream to a file
// - serializes out the RWTPtrOrderedVector collection,
// whose name is “properties”
 
ofstream fout(“properties.xml”); //1
 
RWObjectOutputStream out = //2
RWXmlObjectOutputStreamImp::make(fout,
RWXmlObjectOutputStreamImp::sequenceTag); //3
out << properties; //4
//1 Create an output file stream to the file properties.xml.
//2 Create an XML object output stream, passing the output file stream as a parameter.
//3 As the second parameter, specify sequenceTag, denoting that the object to be serialized out is a collection.
//4 Stream out the RWTPtrOrderedVector collection properties.
Next, look at the code for restoring the collection at application startup.
 
// Here is the startup processing, closely mirrors
// the shutdown processing.
 
ifstream fin(“properties.xml”); //1
 
RWObjectInputStream in = //2
RWXmlObjectInputStreamImp::make(fin,
in >> properties; //3
//1 Create an input file stream to read in the file properties.xml.
//2 Create an XML object input stream, passing the input file stream as a parameter.
//3 Stream the data into the properties collection.