Robert Ramey | 22 May 18:42

Re: [serialization] Handling of references into a std::map

This can't work.

load a pointer creates a new pointer with a copy of the original object.

adding the following to your test should make this clear

...
std::cout << "ref: " << *m.ref << std::endl;
...
 std::cout << "ref: " << *m2.ref << std::endl;

Robert Ramey

Bernhard Maeder wrote:
> Hello all
>
> I'm trying to serialize a std::map along with some pointers that are
> referencing onto some of the Value elements of that map. What I see
> now, is that those references are not loaded correctly. Here's what I
> do:
>
> #include <sstream>
> #include <boost/archive/text_oarchive.hpp>
> #include <boost/archive/text_iarchive.hpp>
> #include <boost/serialization/map.hpp>
>
> struct dummy
> {
>    template<typename Archive>
>    void serialize(Archive & ar, const unsigned int version)
>    {
>    }
> };
>
> struct map_ref_test
> {
>    std::map<std::size_t, dummy> m;
>    dummy * ref;
>
>    template<typename Archive>
>    void serialize(Archive & ar, const unsigned int version)
>    {
>        ar & m;
>        ar & ref;
>    }
> };
>
> int main()
> {
>    std::ostringstream os;
>
>    map_ref_test m;
>    m.m[0] = dummy();
>    m.m[1] = dummy();
>    m.m[2] = dummy();
>    m.ref = &(m.m[1]);
>
>    // serialize
>    boost::archive::text_oarchive out(os);
>    out << const_cast<map_ref_test const &>(m);
>
>    // De-serialize
>    map_ref_test m2;
>    std::string ser = os.str();
>    std::istringstream is(ser);
>    boost::archive::text_iarchive in(is);
>
>    in >> m2;
>
>    std::cout << "0:   " << &m.m[0] << std::endl;
>    std::cout << "1:   " << &m.m[1] << std::endl;
>    std::cout << "2:   " << &m.m[2] << std::endl;
>    std::cout << "ref: " << m.ref << std::endl;
>
>    std::cout << "0:   " << &m2.m[0] << std::endl;
>    std::cout << "1:   " << &m2.m[1] << std::endl;
>    std::cout << "2:   " << &m2.m[2] << std::endl;
>    std::cout << "ref: " << m2.ref << std::endl;
> }
>
> This creates the following output:
>
> 0:   0x805bfc4
> 1:   0x805bfe4
> 2:   0x805c004
> ref: 0x805bfe4
> 0:   0x805ca04
> 1:   0x805ca24
> 2:   0x805ca44
> ref: 0xbfacad5c
>
> I'd expect the last line to read:
>
> ref: 0x805ca24
>
> So, what am I doing wrong? Should this even work?
>
> BTW: I'm using Boost 1.33.1
>
> Thanks a lot!
> Bernhard 

Gmane