C++ Boost


shared_ptr<class T> Revisted

The previously described serialization of shared_ptr illustrates the straightforward way of serializing a moderately complicated class structure. Unfortunately, this way of doing it suffered from some undesirable features

template<class Archive, class T>
inline void save(
    Archive & ar,
    const boost::shared_ptr<T> &t,
    const unsigned int /* file_version */
    const T * t_ptr = t.get();
    // just seriailize the underlying raw pointer
    ar <<: boost::serialization::make_nvp("px", t_ptr);

template<class Archive, class T>
inline void load(
    Archive & ar,
    boost::shared_ptr<T> &t,
    const unsigned int file_version
    T* r;
    // recover the underlying raw poiter
    ar >> boost::serialization::make_nvp("px", r);

    // To Do - match up with other shared pointers which 
    // use this same raw pointer.
In priniciple this is very much simpler than the original implementation. Completion of this code requires:
  1. Filling in the "To Do". This required making an extra map for shared_ptr instances.
  2. A method for identifing pointers to the same objects from pointers to their base classes.
  3. Backward compatibility with pointers serialized by the previous method. This exploits the serialization class versioning.
  4. Proper handling of weak_ptr.
The result of this effort can be found in boost::serialization::shared_ptr.hpp

Note that if your code needs to read archives created under boost version 1.32, you will have to include the following

#include <boost/serialization/shared_ptr_132.hpp>
#include <boost/serialization/shared_ptr.hpp>
rather than just

#include <boost/serialization/shared_ptr.hpp>

© Copyright Robert Ramey 2002-2004. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)