提升序列化
namespace boost {
namespace serialization {
template <class Archive, class T>
inline void save
(Archive &archive,
const std::shared_ptr<T> subtree,
const unsigned int file_version)
{
// only the raw pointer has to be saved
const T *const subtree_x = subtree.get();
archive << subtree_x;
}
template <class Archive, class T>
inline void load
(Archive &archive,
std::shared_ptr<T> subtree,
const unsigned int file_version)
{
T *p_subtree;
archive >> p_subtree;
#if BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, == 1)
subtree.release();
subtree = std::shared_ptr< T >(p_subtree);
#else
subtree.reset(p_subtree);
#endif
}
template <class Archive, class T>
inline void serialize
(Archive &archive,
std::shared_ptr<T> subtree, // no const or else get compile-time error
const unsigned int file_version)
{
boost::serialization::split_free(archive, subtree, file_version);
}
} // namespace serialization
} // namespace boost
树类
class Tree{
private:
class TreeNode{
public:
std::shared_ptr<TreeNode> node_factory(const T &new_key, const long &new_index)
{
return std::shared_ptr<TreeNode>(new TreeNode(new_key, new_index));
}
friend class Tree;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &archive, const unsigned int /* file_version */){
archive & key;
archive & index;
archive & left;
archive & right;
}
T key;
long index;
std::shared_ptr<TreeNode> left;
std::shared_ptr<TreeNode> right;
}; // End Tree Node Class Definition
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &archive, const unsigned int version){
archive & root;
}
};
作家
bool save(std::shared_ptr<Tree> &tree, const std::string &search_tree_file_name)
{
// create and open a binary archive for output
std::ofstream writer(search_tree_file_name, std::ofstream::out | std::ofstream::binary);
if(writer){
boost::archive::binary_oarchive serial_writer(writer);
//set_flags(0, true);
// write class instance to archive
serial_writer << *tree;
// archive and stream closed when destructors are called
}else if(writer.fail()){
writer.clear();
}
return true;
}
读者
enter code here bool load(std::shared_ptr<Tree> &tree, const std::string &search_tree_file_name)
{
// create and open a binary archive for output
std::ifstream reader(search_tree_file_name, std::ifstream::in | std::ifstream::binary);
if(reader){
boost::archive::binary_iarchive serial_reader(reader);
// read class state from archive
serial_reader >> *tree;
// archive and stream closed when destructors are called
}else if(reader.fail()){
reader.clear();
}
return true;
}
我已经写入并验证了对文件的成功序列化,但未能从可用对象反序列化到可用对象。
无论我是用文本还是二进制编写,我都可以验证序列化输出是否正确,但由于某种原因,序列化输出不会反序列化,并且在加载时留下一个空对象。