|
Boost Users : |
Subject: Re: [Boost-users] [serialization] problem exporting derived classes
From: Robert Ramey (ramey_at_[hidden])
Date: 2009-02-18 21:52:02
The problem is that you're saving the derived type and loading the base
type. If you want to load through a base class pointer, you have to save
through a base class pointer.
change
DerivedNode* n1 = new DerivedNode();
DerivedNode* n2 = new DerivedNode();
DerivedNode* n3 = new DerivedNode();
to BaseNode* n1 = new DerivedNode();
BaseNode* n2 = new DerivedNode();
BaseNode* n3 = new DerivedNode();
Robert Ramey
Jens Weggemann wrote:
> Hello,
>
> I've been trying out boost::serialization and ran into a problem
> trying to serialize objects of derived classes.
> I set up this simple class hierarchy:
>
> class BaseNode {
> std::vector<BaseNode*> children_;
> ...
> friend class boost::serialization::access;
> template<class Archive>
> void serialize(Archive &ar, unsigned version) {
> ar & children_;
> }
> };
> class DerivedNode : public BaseNode
> {
> ...
> friend class boost::serialization::access;
> template<class Archive>
> void serialize(Archive &ar, unsigned version) {
> ar & boost::serialization::base_object<BaseNode>(*this);
> }
> };
>
> All works fine as long as I register the types with the archives:
>
> arch.register_type(static_cast<BaseNode*>(NULL));
> arch.register_type(static_cast<DerivedNode*>(NULL));
>
> Now the documentation suggests exporting the classes as an alternative
> to that. But when I instead put
>
> BOOST_CLASS_EXPORT(BaseNode)
> BOOST_CLASS_EXPORT(DerivedNode)
>
> the polymorphism is not handled correctly and e.g. a tree of 3
> DerivedNodes is restored as a single BaseNode object.
> What am I missing here?
>
> The full code for this test is at
> http://noonti.de/tree_serialization.cpp.txt
>
>
> Thanks,
>
> Jens
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net