1

我正在尝试使用 boost 的功能来序列化指向原语的指针(这样我就不必自己取消引用并进行深度存储)。但是,当我尝试这样做时,会遇到一堆错误。这是一个应该包含的类的简单示例以及saveload文件中写入和读取类内容的方法。该程序无法编译:

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

}

请注意,我对取消引用指针的解决方案感兴趣;我希望 boost 为我解决这个问题(其中许多类可能指向同一个底层对象)。

4

1 回答 1

3

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

默认情况下,从不跟踪由实现级别类序列化特征指定的原始数据类型。如果希望通过指针(例如用作引用计数的 long)跟踪共享原始对象,则应将其包装在类/结构中,使其成为可识别的类型。更改 long 的实现级别的替代方案会影响整个程序中序列化的所有 long - 可能不是人们想要的。

因此:

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;
于 2013-09-29T10:41:28.427 回答