Boost logo

Boost :

Subject: Re: [boost] [serialization] Must the objects being serializedoutlive the archive?
From: Robert Ramey (ramey_at_[hidden])
Date: 2010-09-17 12:16:39

Chris Yuen wrote:
> Robert,

> As you can see from the code example, I want to be able to
> deserialize a
> list of these "commands" from the base pointer, because I actually
> have hundreds of these polymorphic commands and they need to each
> have a virtual "Execute()" method so that they know how to apply
> themselve to an "Actioner." (Instead of using a giant switch-case in
> the Actioner to
> identify each command) I figured it's better than using a magic
> number, opcode approach

it is better, and the serialization library supports and even
encourages this. Just serialize and de-serialize through a base
class pointer.

> I was under the impression that if I want to deserialize using a base
> pointer, I must also serialize via the base pointer, is that correct?


> So I guess the below won't work with the original deserialization
> code?
>> {
>> boost::scoped_ptr<Strings> s;
>> const Strings * s = new Strings("Hello", "World"));
>> oa << s;
>> .... // same for all the other stuff
>> // s deleted as it goes out of scope
>> }

This would work. What won't work is

    boost::scoped_ptr<Strings> s;
    const Strings * s = new Strings("Hello", "World"));
    const * x = s;
    oa << s;
    delete s;
    oa << x;

Your making this way too hard, just look at the examples and tests to see
that all you have to do is serialize though a base class pointer. When the
(base class) pointer is deserialized, an object of the most derived class
is created automagically. The serialization library takes care of keep
track of the true (i.e. most derived type).

Robert Ramey

Boost list run by bdawes at, gregod at, cpdaniel at, john at