c++ - 如何序列化包含指向基元的指针的类?

标签 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()
{

}

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

最佳答案

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.

因此:

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;

关于c++ - 如何序列化包含指向基元的指针的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076299/

相关文章:

c++ - out_of_range、range_error 和 over/underflow_error 之间的区别?

c++ - Qt如何删除QObjects?

c++ - boost::archive::binary_iarchive 上的 std::bad_alloc

c++ - 为什么 make_nvp 需要非常量引用?

c++ - 如何在 waf 构建系统中安装具有不同名称的库?

C++图形界面数据库编程

c++ - 有人曾经将 boost::singleton 与 boost::logger 一起使用过吗?

linux - CMakeLists 无法找到新安装的 HDF5?

c++ - 使用 shared_ptr 返回 vector 的指针

c++ - boost 序列化 - 序列化 std::tr1::shared_ptr?