0

I have a base class and 4 derived classes. I store all my derived classes in a vector of base class pointer type. During first initialization I create each derived type differently using their constructors. Basically they each have different param types in their ctors. (I had to provide a protected default ctor to make BOOST_CLASS_EXPORT compile but that's a different story). I don't/can't save all the members (filled in ctor) of these derived classes.

Now, when I load objects from the disk using boost::serialize, these members (that are not serialized and specific to each derived type) are destroyed. And, I cannot think of a way to re-initialize these derived types since I only store the base class pointers.

What exactly I need is being able to load my derived types (pointers) partially, without deleting all their content..

Is there a way to overcome this, a magic boost define or function call perhaps? Otherwise, polymorphism with boost::serialize is not possible at all.. I should be missing something and hope I could define my problem good enough.

mentat
  • 2,748
  • 1
  • 21
  • 40

1 Answers1

0

You shouldn't need to create a default constructor just for serialization. You can instead have boost save/load the data needed by a non-default constructor, and use that to construct new objects when loading.

That way, whatever your constructors do to ensure the validity of data members can also happen during serialization, and the serialization library never has to manipulate the data members of your objects directly. This should prevent data erasure.

For example, if your class can be constructed using a name and a size, you could overload the functions as follows:

template <class Archive>
inline void save_construct_data(Archive & ar, const my_class * t, const unsigned int) {
    ar << my_class->name();
    ar << my_class->size();
}

template<class Archive>
inline void load_construct_data(Archive & ar, my_class * t, const unsigned int) {
    std::string name;
    int size;
    ar >> name;
    ar >> size;
    ::new(t)my_class(name, size); // placement 'new' using your regular constructor
}

Check out the docs here.

vsekhar
  • 5,090
  • 5
  • 22
  • 23