Serialization problem with cyclic references (pointers)
Try steppin through this code where the deserialization takes place. On every machine I've tried this (and I've tried it with two different Boost builds as well) parent stays null every time. Can anyone point out the reason why? This is giving me a headache :( I suspect it's got something to do with there being cyclic references between parent and child... #include <boost\archive\binary_oarchive.hpp> #include <boost\archive\binary_iarchive.hpp> #include <boost\serialization\vector.hpp> #include <fstream> #include <memory> #include <vector> class A { public: A() { parent = nullptr; someInt = 0; } template <class Archive> void serialize(Archive& archive, const unsigned int version) { archive & someInt; archive & parent; archive & children; } int someInt; A* parent; std::vector<A*> children; }; int main() { A* newA = new A(); A* newPtr = new A(); newPtr->someInt = 5; newPtr->parent = newA; newA->children.push_back(newPtr); // Save. std::ofstream outputFile("test", std::fstream::out | std::fstream::binary); if (outputFile.is_open()) { boost::archive::binary_oarchive outputArchive(outputFile); // Serialize objects. outputArchive << newA; outputArchive << newPtr; outputFile.close(); } delete newA; delete newPtr; newA = nullptr; newPtr = nullptr; // Load.| std::ifstream inputFile("test", std::fstream::binary | std::fstream::in); if (inputFile && inputFile.good() && inputFile.is_open()) { boost::archive::binary_iarchive inputArchive(inputFile); // Load objects. inputArchive >> newA; inputArchive >> newPtr; inputFile.close(); } return 0; } -- View this message in context: http://boost.2283326.n4.nabble.com/Serialization-problem-with-cyclic-referen... Sent from the Boost - Users mailing list archive at Nabble.com.
Note that if I uncomment the serialization of `children`, `parent` deserializes correctly. Can't figure out what is going on. -- View this message in context: http://boost.2283326.n4.nabble.com/Serialization-problem-with-cyclic-referen... Sent from the Boost - Users mailing list archive at Nabble.com.
How about this? class A { public: A() { parent = nullptr; someInt = 0; } BOOST_SERIALIZATION_SPLIT_MEMBER() template <class Archive> void save(Archive& archive, const unsigned int version) const { archive << someInt; archive << children; } template <class Archive> void load(Archive& archive, const unsigned int version) { archive >> someInt; archive >> children; for( std::vector<A*>::iterator iter = children.begin(); iter != children.end(); ++iter) { (*iter)->parent = this; } } int someInt; A* parent; std::vector<A*> children; }; You will serialize the whole tree starting from the root node with this. -- View this message in context: http://boost.2283326.n4.nabble.com/Serialization-problem-with-cyclic-referen... Sent from the Boost - Users mailing list archive at Nabble.com.
participants (2)
-
krisdamato
-
kwanti