我正在尝试使用 boost 的功能来序列化指向基元的指针(这样我就不必取消引用并自己进行深度存储)。但是,当我尝试这样做时,我遇到了一堆错误。下面是一个类的简单示例,该类应该包含 save
和 load
方法,它们可以从文件中写入和读取类内容。该程序无法编译:
#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/