Boost logo

Boost Users :

Subject: [Boost-users] Problems using boost serializing and custom constructors
From: Allan Nielsen (a_at_[hidden])
Date: 2012-03-06 09:58:32


Hi

I'm trying to use boost::serialize for the first time, but I have some
troubles figuring out how to serialize a class like this:

#include <vector>

struct Foo {
    struct Bar {
        std::vector<int> * data; // Must point to Foo::data

        Bar( std::vector<int> * d ) : data(d) { }
    };

    std::vector<int> data;
    std::vector<Bar> elements;

    Foo() {
        // do very time consuming calculation to populate "data" and "elements"
    }
};

Here is what I have tried:

struct Foo {
    struct Bar {
        std::vector<int> * data;

        Bar( ) : data( 0 ) { }
        Bar( std::vector<int> * d ) : data(d) { }

        template<class Archive>
        void serialize(Archive & ar, const unsigned int version) {
            ar & data; // is this correct?
        }
    };

    std::vector<int> data;
    std::vector<Bar> elements;

    Foo() {
        std::cerr << "Running default constructor" << std::endl;
        data.push_back(1);
        data.push_back(2);
        data.push_back(3);
        data.push_back(4);
        data.push_back(5);
        elements.push_back( Bar( &data ) );
        elements.push_back( Bar( &data ) );
        elements.push_back( Bar( &data ) );
    }

    template<class Archive>
    Foo( Archive & ar ) {
        ar >> data; // is this corrent?
        ar >> elements;
    }

private:
    BOOST_SERIALIZATION_SPLIT_MEMBER();
    friend class boost::serialization::access;

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const {
        const std::vector<int> * data_ptr = &data;

        // should data be seriliazed as pointer...
        // it is used as a pointer in Bar
        ar << data_ptr;
        ar << elements;
    }
};

int main(int argc, const char *argv[])
{
#if 0
    // serialize
    Foo foo;
    boost::archive::text_oarchive oar(std::cout);
    oar << foo;

#else
    // deserialize
    boost::archive::text_iarchive oar(std::cin);
    Foo foo(oar);

#endif
    std::cerr << foo.data.size() << std::endl;
    std::cerr << foo.elements.size() << std::endl;

    std::cerr << (&foo.data) << std::endl;
    for( const auto& a : foo.data )
        std::cerr << a << " ";
    std::cerr << std::endl;

    for( const auto& a : foo.elements)
        std::cerr << a.data << " ";
    std::cerr << std::endl;

    return 0;
}

The only problem is that it does not work. After I deserialize Foo,
data is still empty.

Please advise me on how to do this properly.

Best regards
Allan W. Nieslen


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