Question

I am trying to use boost's functionality for serializing pointers to primitives (so that I don't have to de-reference and do a deep store myself). However, I get a pile of errors when I try to do it. Here is a simple example of a class that is supposed to contain save and load methods which write and read the class content from a file. This program does not compile:

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

#include <boost/serialization/shared_ptr.hpp>
#include <boost/shared_ptr.hpp>

#include <fstream>

class A
{
public:
    boost::shared_ptr<int> sp;
    int const * p;

    int const& get() {return *p;}

    void A::Save(char * const filename);
    static A * const Load(char * const filename);

        //////////////////////////////////
        // Boost Serialization:
        //
    private:
        friend class boost::serialization::access;
        template<class Archive>
        void serialize(Archive & ar,const unsigned int file_version)
        {
            ar & p & v;
        }
};

// save the world to a file:
void A::Save(char * const filename)
{
    // create and open a character archive for output
    std::ofstream ofs(filename);

    // save data to archive
    {
        boost::archive::text_oarchive oa(ofs);

        // write the pointer to file
        oa << this;
    }
}

// load world from file
A * const A::Load(char * const filename)
{
    A * a;

    // create and open an archive for input
    std::ifstream ifs(filename);

    boost::archive::text_iarchive ia(ifs);

    // read class pointer from archive
    ia >> a;

    return a;
}

int main()
{

}

Note that I am not interested in a solution that dereferences the pointer; I want boost to take care of that for me (many of these classes might be pointing to the same underlying object).

Was it helpful?

Solution

In http://www.boost.org/doc/libs/1_54_0/libs/serialization/doc/index.html:

By default, data types designated primitive by Implementation Level class serialization trait are never tracked. If it is desired to track a shared primitive object through a pointer (e.g. a long used as a reference count), It should be wrapped in a class/struct so that it is an identifiable type. The alternative of changing the implementation level of a long would affect all longs serialized in the whole program - probably not what one would intend.

Hence:

struct Wrapped {
    int value;
    private:
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar,const unsigned int file_version)
    {
        ar & value;
    }
};

boost::shared_ptr<Wrapped> sp;
Wrapped const * p;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top