14.9. Using XML to Save and Restore a Collection of Objects

Problem

You want to be able to save a collection of C++ objects to an XML document and read it back into memory later.

Solution

Use the Boost Serialization library. This library allows you to save and restore objects using classes called archives . To make use of this library, you must first make each of your classes serializable, which just means that instances of the class can be written to an archive, or serialized, and read back into memory, or deserialized. Then, at runtime, you can save your objects to an XML archive using the << operator and restore them using the >> operator.

To make a class serializable, add a member function template serialize with the following signature:

template<typename Archive>
void serialize(Archive& ar, const unsigned int version);

The implementation of serialize should write each data member of the class to the specified archive as a name-value pair, using the & operator. For example, if you want to serialize and deserialize instances of the class Contact from Example 14-2, add a member function serialize, as shown in Example 14-25.

Example 14-25. Adding support for serialization to the class Contact from Example 14-2

#include <boost/serialization/nvp.hpp> // "name-value pair" class Contact { ... private: friend class boost::serialization::access; template<typename Archive> void serialize(Archive& ar, const unsigned int version) { // Write (or read) each data-member as a name-value pair ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.