Infiltrator
Infiltrator

Reputation: 1681

Loading an old boost::serialisation archive with different class layout

I have an old (boost::serialisation) archive, which was generated using:

class Data;
data = new Data();
ar & data;

Now the code has changed to:

class Header;
class Data;
header = new Header();
data = new Data();
ar & header;
ar & data;

So, my question: how do I load the old archive with the new code? As far as I can tell, boost::serialisation doesn't allow archive versioning, and if I just try to load it, it'll give me an "input stream error", because it'll try to ar & header; on data that was saved with ar & data;.

EDIT: I'm aware of BOOST_CLASS_VERSION(ns::Class, x), but this does not apply to archives.

Upvotes: 2

Views: 270

Answers (2)

Infiltrator
Infiltrator

Reputation: 1681

So it seems that there is no way to do it other than writing a conversion program for the old version archives.

However, now having the 'header' in there, in future, I can bump the version of that and use some logic in my loading function if I ever need to add more classes to the top level.

Upvotes: 0

Yakov Galka
Yakov Galka

Reputation: 72529

Boost serialization does allow versioning. Unfortunately you did not know this so you just broke backward compatibility by saving new archives with ar & header without bumping the class version.

The tutorial linked above explains it well. In your case, when you decided to add the header, you had to do it as follows:

class YourClass
{
    /* ... */

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        if(version > 0)
            ar & header;
        ar & data;
    }
};

BOOST_CLASS_VERSION(YourClass, 1)

You must bump the version of the class each time you change the serialization code, even if you add fields only at the end.

Upvotes: 2

Related Questions