Boost logo

Boost Users :

Subject: [Boost-users] Serialization problem with cyclic references (pointers)
From: krisdamato (kristian.damato_at_[hidden])
Date: 2013-11-27 11:58:30


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-references-pointers-tp4655477.html
Sent from the Boost - Users mailing list archive at Nabble.com.

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