O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required