I believe your example should work as written. Where does it fail? Robert Ramey Ivan Rachev wrote:
Does anyone have an idea how to serialize dynamic arrays of objects?
An example follows at the end. Its weakness shows up when an outside pointer points to an element in the array. The problem is that the type being serialized is T but not T*.
Thanks, Ivan
#include <fstream>
#include
#include #include class A { friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) {} };
//IVAN Element always points to the beginning of an array of // 'Size' elements. The array is NOT null-terminated. If // size == 0, Elements may hold an undefined value. User // is responsible for initializing, new-ing and delete-ing. // Assumption: if there is an outside pointer to an object // inside this array, after loading the array // that pointer will hold a different object. template <typename T> struct DynamicArray { int Size; T* Element;
friend class boost::serialization::access; template<class Archive> void save(Archive & ar, const unsigned int version) const { ar & Size; for (int i = 0; i < Size; ++i) ar & Element[i]; } template<class Archive> void load(Archive & ar, const unsigned int version) { ar & Size; //TODO: assert(Size >=0); if (Size > 0) { Element = new T[Size]; for (int i = 0; i < Size; ++i) ar & Element[i]; } } BOOST_SERIALIZATION_SPLIT_MEMBER() };
int main() { DynamicArray<A> ArrayOfAs; A* secondElement;
std::ifstream ifs("test.txt"); boost::archive::text_iarchive ia(ifs); ia & ArrayOfAs; ia & secondElement; // this guy will point to a copy of the // 2nd element but NOT the 2nd element itself
delete [] ArrayOfAs.Element; }