SpamBot
SpamBot

Reputation: 1458

Boost serialization with pointers

The data structure I would like to serialize is mostly a list of objects. An object may have a pointer to another. Serialization then fails with a pointer conflict. http://www.boost.org/doc/libs/1_60_0/libs/serialization/doc/exceptions.html#pointer_conflict

Here is a minimal example of my data structure: (My real structure is more complicated.)

struct Data
{
  std::vector<Object> objects;
}
struct Object
{
  std::string name;
  Object *other;
}

I can work around be changing list elements to pointers std::vector<Object*> because boost can then create the elements anywhere, however, that is very intrusive. Another idea would be to make sure all objects are created first, and then the pointers. But how can I achieve this? Any alternatives?

Upvotes: 0

Views: 2002

Answers (2)

SpamBot
SpamBot

Reputation: 1458

I finally worked around my pointer_conflict issue by using (smart) pointers for all data that is referenced multiple times.

struct Data
{
  std::vector< std::unique_ptr<Object> > objects;
}
struct Object
{
  std::string name;
  Object *other;
}

Because an Object may always be created at an arbitrary location, the order in the serialization does not matter. The drawback is that the data structure has changed. In my application, this entails a few changes in the getter and setter methods of Data.

Upvotes: 0

Kevin SUN
Kevin SUN

Reputation: 158

you can do like the following: 1) define an ID in the Object 2) when do serialise the class, use the ID for the pointer 3) after all the data is done, loop all the objects to make ID to actual pointer

if this is just a vector, then you could ignore the Object pointer when do serial and deserial, because you know it is continuously linked, so it is easy to re-link continuously when do de-serial by having a temp pointer of previous object linked to current object.

Upvotes: 1

Related Questions