Boost logo

Boost :

From: Robert Ramey (ramey_at_[hidden])
Date: 2004-01-14 13:53:19


Vladimir Prus wrote:

>In a project of mine we plan to store some number of objects into an archive
>and later load them. The problem is that the number of objects is not known
>when you're writing an archive, so when reading, you don't know where to
>stop.

>I wonder if the following code will work:

> ifstream ifs(...);
> boost::binary_iarchive ia(ifs);

> while(ifs) {
> some_object obj;
> ia >> obj;
> objects.push_back(obj);
> }

>The problem is that I don't know what archive will do on stream errors. For
>the above to work, it should stop doing anything. But I can't find any
>documentation about what happens -- I think it's better to discuss and
>document that.

I recently added stream error checking to the archives. An attempt
to read past eof will result in throwing and exception
boost::archive::archive_exception::stream_error.

In my view the above would be an error. It couple the serialization
of data to the archive type. There is not requirement that an archive
be based on streams. If an archive is based on a stream, the stream
itself shouldn't be manipulated while an archive save/load is in
progress as it would in general throw things out of sync. It would
also violate the priniciple of de-coupling of the archive from
serializaiton of a class.

So I would write the above as:

 ifstream ifs(...);
   boost::binary_iarchive ia(ifs);

   size_t count;
   ia >> count;
   while(count-- > 0)
     ia >> obj;

or if havng a count is intolerable

   optional<T> obj;
   for(;;){
     ia >> obj;
     if(! obj.is_initialized)
         break;
     objects. push_back obj
   }

or whatever

Robert Ramey


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk