Boost logo

Boost Users :

Subject: Re: [Boost-users] How to serialize basic_string<unsigned char>
From: Martin Dietze (di_at_[hidden])
Date: 2010-04-10 12:54:24


On Sat, April 10, 2010, Robert Ramey wrote:

> Just look at boost/serialization/string.hpp and do the same thing
> for unsigned char

Yes, that was my first thought, too. Consider the code below.
Execution fails with this assertion:

a.out: test.cc:47: void load(): Assertion `size == 10' failed.
Aborted

I also tried the collection-based approach which is currently
commented out in serialization/string.hpp, but this does not
compile since basic_string<> does not have a back() method.

-------------------- SNIP -----------------------

#include <string>
#include <fstream>
#include <cassert>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>

BOOST_CLASS_IMPLEMENTATION(std::basic_string<unsigned char>,
                           boost::serialization::primitive_type)
#define SIZE 10
#define FNAME "/tmp/archive.ser"

class A {
public:
  std::basic_string<unsigned char> m_string;
private:
  friend class boost::serialization::access;
  template<class Archive> void
  serialize (Archive & ar, const unsigned int version)
  {
    ar & m_string;
  }
};

void
save (void)
{
  A a;
  a.m_string.assign (SIZE, (unsigned char)0);
  for (int i = 0; i < SIZE; ++i)
    {
      a.m_string[i] = (unsigned char)i;
    }
  std::ofstream ofs (FNAME, std::ios::out | std::ios::binary);
  boost::archive::binary_oarchive oa (ofs);
  oa << a;
}

void
load (void)
{
  A b;
  std::ifstream ifs (FNAME, std::ios::in | std::ios::binary);
  boost::archive::binary_iarchive ia (ifs);
  ia >> b;
  size_t size = b.m_string.size ();
  assert (size == SIZE);
  for (int i = 0; i < b.m_string.size (); ++i)
    {
      assert ((int)b.m_string[i] == i);
    }
}

int
main (void)
{
  save ();
  load ();
  return 0;
}

-------------------- SNIP -----------------------

Cheers,

M'bert

-- 
----------- / http://herbert.the-little-red-haired-girl.org / -------------
=+= 
while (!asleep)
  ++sheep;

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net