Question

I'm trying to build a tree like structure to hold a test made up of a series of questions.

The idea is that Test, Question, QuestionPart would all derive from the following class:

class Node
{    
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & boost::serialization::make_nvp("children", m_children);
        ar & boost::serialization::make_nvp("intro", m_intro);
    }

public:
    Node(){};   
    virtual ~Node(){};

    virtual void addChildNode( Node* _child );      
    virtual const std::string getIntro() const;
    virtual Node* getChild( const _index ) const;
    virtual void setIntro( std::string _intro );

protected:
    std::vector<Node*> m_children;
    std::string m_intro;
};

Before doing all the other classes I tried out the following:

void saveTest( const Node &test, const char* filename)
{
    // make an archive
    std::ofstream ofs(filename);
    boost::archive::xml_oarchive oa(ofs);
    oa << BOOST_SERIALIZATION_NVP(test);
}

void createTest()
{
    Node* test = new Node();
    Node* question1 = new Node();

    question1->setIntro("Question 1");

    test->addChildNode(question1);
    test->setIntro("Test");

    saveTest( *test, fileLocation.c_str() );
}

But this is throwing an exception and only creating the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="10">
<test class_id="0" tracking_level="1" version="0" object_id="_0">
<children class_id_reference="0" object_id="_1">
    <children</boost_serialization>

Any insight would be much appreciated.

Was it helpful?

Solution

It turned out to be a simple fix; having seen an example here, I changed the following:

std::vector<Node*> m_children;

to

boost::ptr_vector<Node> m_children;

which requires the following include:

#include <boost/ptr_container/serialize_ptr_vector.hpp>

However, I'm not sure why this works (objects were not being tracked possibly?), so an explanation would be welcome!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top