Boost logo

Boost Users :

Subject: [Boost-users] [serialization] Workarounds for serialization of std::map / non-default constructors
From: Chard (boost_at_[hidden])
Date: 2009-09-08 05:24:15


When serializing a std::map (specifically, the loading part) if either the
key or value type of the map's pair is not default constructable then
workarounds are required (note: this has only been confirmed with the
std::map implementation provided with MSVC71).

E.g.:

{{{
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/map.hpp>

#include <sstream>
#include <utility>

////////
// Example, non-default constructable class
class X
{
public:
    X(int i) : i_(i) {}

private:
    int i_;
    friend class boost::serialization::access;
    template <typename A>
    void serialize(A &ar, const unsigned)
    {}
};

template <typename A>
inline void load_construct_data(A &ar, X * a, const unsigned)
{
    ::new(a)X(1); // e.g.
}

//////////////////////////////////////////

void test_ser_pair()
{
    std::map<double, X> theMap;

    theMap.insert(std::make_pair(0.5, X(1)));

    std::string text;
    {
        std::ostringstream ostr;
        boost::archive::text_oarchive arch(ostr);
        arch & theMap;
        text = ostr.str();
    }
    {
        std::istringstream istr(text);
        boost::archive::text_iarchive arch(istr);
        // Next line doesn't compile under MSVC7.1 because the serialization
        // of map uses the default constructor of std::pair.
        arch & theMap;
    }
}
}}}

My current workaround is to provide a specialization of just the std::pair
constructor for my map's pair, but it would be nice if the library could
provide a workaround.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net