如何序列化包含指向原语的指针的类?

qua*_*ant 1 c++ boost boost-serialization

我正在尝试使用 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()
{

}
Run Code Online (Sandbox Code Playgroud)

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

小智 5

在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;
Run Code Online (Sandbox Code Playgroud)