2

I have a tree class that I need to serialize. The code:

#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

I've looked at a lot of other comments and code samples online, both this site and the Boost docs, but I don't see how to handle a situation that is recursive like this. Where the class contains two pointers of objects of the same type. How should I either modify the tree or serialization function to make this work? Thank you.

Richard Żak
  • 814
  • 1
  • 11
  • 21

1 Answers1

1

IMHO, you should serialize tree.left and tree.right as pointers, not objects. They can and should be equal to NULL sometimes (otherwise your tree would be infinite).

Your code also need a proper default constructor which sets these members to NULL. It is also not clear from your code who owns and destroys the trees. I would consider forbidding the copy constructor (e.g. derive your class from boost::noncopyable).

You do not need the macro BOOST_CLASS_TRACKING(AVLtree, track_always), Boost.Serialize will apply it anyway since you will be serializing (some) AVLtree(s) as pointers.

That will work just fine, Archive is designed to handle "back-pointers"; recursive structure is a piece of cake for it.

Good luck!

Michael Simbirsky
  • 3,045
  • 1
  • 12
  • 24