我想使用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()
{
}
注意,我不感興趣在取消引用指針的解決方案;我希望能夠爲我提供幫助(其中許多類可能指向相同的基礎對象)。
,你會得到錯誤...? – john