如何使用std :: shared_ptr进行boost :: serialization?

时间:2013-09-28 06:49:42

标签: c++ boost boost-serialization

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

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

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>'的序列化库shared_ptr。 1}}。我在这里缺少什么?

注意:据我所知,我假设std::shared_ptrboost/serialization/shared_ptr.hpp定义了serialize函数是错误的,因此这个问题的正确答案可能就是我要么必须为std::shared_ptr定义我自己的serialize函数,要么转换为std::shared_ptr

2 个答案:

答案 0 :(得分:2)

这是我能够提出的最佳答案。如果某人有更好的发言权,我会接受这个答案。

使用提升的boost/serialization/shared_ptr.hpp标题不是std::shared_ptr的支持,而是对boost::shared_ptr的支持。如果您希望序列化使用共享指针对象而不引导您自己的序列化代码,那么您需要将std::shared_ptr个对象转换为boost::shared_ptr个对象和live with the consequences

我的误解是我认为boost/serialization/shared_ptr.hppserialize定义了std::shared_ptr方法。我错了。

答案 1 :(得分:1)

不,std :: shared_ptr和boost :: shared_ptr是不相关的类模板。

Boost.Serizalization不支持std::shared_ptr开箱即用,但您可以在应用中添加此类支持 - 只需查看<boost/serialization/shared_ptr.hpp>标题即可。

相关问题