Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost serialization and doubles

I am trying to serialize a class to a string using the boost serialization library and included in my class are several double member variables.

Below is the code I'm using to serialize:

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>

std::stringstream ss;
boost::archive::text_oarchive oa(ss);
oa << mPoint;

Here is the serialiation method within my Point class:

friend class boost::serialization::access;

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

When I serialize to a string, boost doesn't appear to handle the double to string conversion as I would expect (there appear to be rounding issues). Researching a bit it looks like others have reported the same behavior. I also understand the precision related issues associated with converting a double to a string and vice versa and how this could cause the issue.

What is strange and I don't understand though is this doesn't appear to happen when I'm using a stringstream itself and redirecting the double to the stream nor when I use boost's lexical_cast function to convert from a stringstream.str() back to a double. Before discovering boost had its own serialization/deserialization classes, I had actually written my own using stringstream and lexical_cast calls and it worked w/o issue. I'm really hoping I don't have to abandon the serialization library and go back to what I had before. Hopefully there is just some setting/trait/etc. I'm missing.

like image 486
Dave LeJeune Avatar asked Jun 02 '11 13:06

Dave LeJeune


People also ask

What is Boost serialization?

The library Boost. Serialization makes it possible to convert objects in a C++ program to a sequence of bytes that can be saved and loaded to restore the objects. There are different data formats available to define the rules for generating sequences of bytes. All of the formats supported by Boost.


1 Answers

You could try forcing your stream to use scientific format for floating point before serialising to it:

ss << std::scientific;

It looks like the boost library sets the precision correctly, but doesn't appear to set the format. Alternatively, you can I think derive and override the logic for saving and/or loading floating point numbers without throwing away the rest of the library - start here.

It also looks like there is work in progress on supporting infinities etc.

like image 105
Alan Stokes Avatar answered Sep 30 '22 00:09

Alan Stokes