Question

Suppose I have a class A, which contains a private member B const * p, which is accessible via the public function B const& A::get(). How do I serialize function A use the boost save_construct_data and load_construct_data functions?

Here is my contained attempt (please note that this example illustrates the issue itself, not the reason why I am using this get function):

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

#include <fstream>

class B
{
public:
    int a;

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

class A
{
public:
    A(B const * p) : p(p) {}
    B const& get() const {return *p;}
private:
    B const * 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){}
};

namespace boost 
{ 
    namespace serialization 
    {
        template<class Archive>
        inline void save_construct_data(
        Archive & ar, A const * t, unsigned const int file_version
        )
        {
            ar << &t->get();
        }

        template<class Archive>
        inline void load_construct_data(
        Archive & ar, A * t, const unsigned int file_version
        )
        {
            B const * p;
            ar >> p;

            ::new(t) A(p);
        }
    }
}

// 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()
{

}

The error is: error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const B *' (or there is no acceptable conversion)

Était-ce utile?

La solution

You cannot serialize a temporary (AFAICT that's Boost limitation).

B const * p = &t->get();
ar << p;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top