2

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

#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 文档,但我不知道如何处理这样的递归情况。其中类包含相同类型的对象的两个指针。我应该如何修改树或序列化函数以使其工作?谢谢你。

4

1 回答 1

1

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

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

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

这样就可以了,存档旨在处理“反向指针”;递归结构对它来说是小菜一碟。

祝你好运!

于 2013-10-31T07:31:57.110 回答