这个问题已经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.hpp
为std::shared_ptr
定义了一个serialize
方法。我错了。
关于c++ - 如何使 boost::serialization 与 std::shared_ptr 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19064221/