Serializing Vector of Objects which contains Vectors of Pointers

血红的双手。 提交于 2019-12-11 11:58:59

问题


I have 3 classes ("Leader", "Researchers", "Workers") which all derive from a base-class "Team".

I have a class "Project" which contains a vector of pointers to different Teams.

I use all of the following headers, in this order, in all of my class declarations:

#include <sstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/split_member.hpp>

To (de)serialize the Team object I use:

private:
  friend class boost::serialization::access ;

  template <typename Archive>
  void serialize(Archive& ar, const unsigned int /*version*/)
  {
      ar & teamname ;
  }

To (de)serialize the Leader, Researchers, Workers objects I use:

typedef Team _super;

friend class boost::serialization::access ;

template <typename Archive>
void serialize(Archive& ar, const unsigned int /*version*/)
{
    ar & boost::serialization::base_object<_super>(*this) ;
    ar & contactTelephoneNumber ;
}

The Project holds a std::vector of pointers to different teams and a string using:

std::vector<Team *> teams ;
std::string note ;

I use the following code in the Project class for serialization:

private:
  friend class boost::serialization::access ;

  template <typename Archive>
  void serialize(Archive& ar, const unsigned int /*version*/)
  {
      //ar & BOOST_SERIALIZATION_NVP(teams) ; //ERROR OCCURS HERE
      ar & teams;
      ar & note ;
  }

And to serialize the vector of Project objects in the main I use:

{
    std::ostringstream archiveStream ;
    boost::archive::text_oarchive archive(archiveStream) ;
    archive << BOOST_SERIALIZATION_NVP(projects) ;

    //Get serialized info as string
    archivedProjects = archiveStream.str() ;
}

This all compiles fine. The issue is at Run-Time. When the above section of the code is reached, I get the following error:

terminate called after throwing an instance of 'boost::archive::archive_exception' 
what(): 
    unregistered class - derevided class not registered or exported"

The program goes as far as:

ar & teams;

In the Questionnaire class's serialization attempt.


回答1:


As in n.m.'s link: you need to register the classes with Boost so that it knows what classes are what when serialising.

You need to add the following line for each class where "Project" serializes:

ar.template register_type<ClassName>() ; //ClassName = Team etc


来源:https://stackoverflow.com/questions/17640045/serializing-vector-of-objects-which-contains-vectors-of-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!