提升树的序列化?

时间:2013-10-29 21:34:07

标签: c++ boost-serialization gcc4

我有一个需要序列化的树类。代码:

#include <string>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/tracking.hpp>
using namespace std;

class AVLtree {
public:
    string name;
    int fid;
    int p1;
    int n1;
    double ig;

    AVLtree *left;  // left subtree
    AVLtree *right; // right subtree
    int height;     // height of the tree
    long TotalNodes;
};
BOOST_CLASS_TRACKING(AVLtree, track_always)
namespace boost {
namespace serialization {
template<class Archive>
void serialize(Archive &ar, AVLtree &tree, const unsigned int version) {
    ar & tree.name;
    ar & tree.fid;
    ar & tree.p1;
    ar & tree.n1;
    ar & tree.ig;
    ar & tree.height;
    ar & tree.TotalNodes;
    ar & *tree.left; // Haven't yet tried it with *tree.left, but just tree.left saves the memory address, not the object
    ar & *tree.right;
} // end serialize()
} // end namespace serialization
} // end namespace boost

我在网上查看了很多其他评论和代码示例,包括本网站和Boost文档,但我不知道如何处理像这样的递归情况。其中类包含两个相同类型的对象指针。我应该如何修改树或序列化功能才能使其工作?谢谢。

1 个答案:

答案 0 :(得分:1)

恕我直言,你应该序列化tree.lefttree.right作为指针,而不是对象。它们有时也应该等于NULL(否则你的树将是无限的)。

您的代码还需要一个正确的默认构造函数,将这些成员设置为NULL。你的代码中也不清楚拥有和销毁树木的人。我会考虑禁止复制构造函数(例如从boost :: noncopyable派生你的类)。

你不需要宏BOOST_CLASS_TRACKING(AVLtree, track_always),Boost.Serialize无论如何都会应用它,因为你将序列化(某些)AVLtree作为指针。

这将工作得很好,Archive旨在处理“反向指针”;递归结构对它来说是件小事。

祝你好运!