c++ - 如何使 boost::serialization 与 std::shared_ptr 一起工作?

标签 c++ boost boost-serialization

这个问题已经asked here和其他一些地方,但答案似乎并没有真正解决最新的 Boost 库。

为了说明这个问题,假设我们要序列化一个包含共享指针(std::shared_ptr)的类,以及一个静态的load。将从文件和 save 构建类的函数将实例存储到文件的函数:

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

#include <fstream>
#include <memory>
#include <vector>

class A
{
public:
    std::shared_ptr<int> v;

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

}

上面的代码生成了一长串以c:\local\boost_1_54_0\boost\serialization\access.hpp(118): error C2039: 'serialize' : is not a member of 'std::shared_ptr<_Ty>'开头的错误,据我所知这不应该是真的,因为我已经加载了 boost shared_ptr表面上支持 std::shared_ptr 的序列化库.我在这里缺少什么?

注意:据我了解,我的假设是 boost/serialization/shared_ptr.hpp定义了一个 serialize std::shared_ptr 的功能是错误的,因此这个问题的正确答案可能是我要么必须定义我自己的 serialize std::shared_ptr 的功能或转换为 boost::shared_ptr

最佳答案

这是我能想出的最佳答案。如果有人对此有更好的看法,我会接受它作为答案。

boost 附带的boost/serialization/shared_ptr.hpp header 支持std::shared_ptr boost::shared_ptr。如果您想使用共享指针对象进行序列化, 盗用您自己的序列化代码,那么您需要将您的 std::shared_ptr 对象转换为 boost::shared_ptr 对象和 live with the consequences .

我的误解是我认为boost/serialization/shared_ptr.hppstd::shared_ptr定义了一个serialize方法。我错了。

关于c++ - 如何使 boost::serialization 与 std::shared_ptr 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19064221/

相关文章:

c++ - boost : Error : 2 overloads have similar conversions

c++ - Boost多边形库 bool 函数计算时间

c++ - boost 是否支持 c++11 的 std::tuple 的序列化?

Boost 序列化多态寄存器(导出)不能跨文件工作

c++ - 将结构作为模板参数传递 - 如何修复此代码?

c++ - 使用 WinHttp 发布表单

c++ - 从函数返回字符数组

c++ - 提升 vector 序列化追加问题

c++ - 从 Node JS 访问用 C++ 编写的设备 SDK

c++ - 如何传递信号以解除对 Linux 中 pause() 的阻塞?