Hi,
I'm experiencing a runtime error while using boost's serialization for
std::map. I am defining a map like:
std::map m;
and serializing it as I do any other container or primitive type.
However when the map contains more than two elements, there is a
runtime exception when reading a serialized file back in. I'm using
visual studio 8. Following is the exact source code I'm trying this
with (very short sample app). Can anyone see what I'm doing wrong, or
if there is an error with the boost code? I took a look at the written
file in a binary editor and it looks fine.
#include
#include
#include
#include <fstream>
#include <string>
#include <map>
using namespace std;
// This is a test class to use as the map data.
class CSomeData {
public:
CSomeData(){};
CSomeData(float f0, string str0)
{
m_f0 = f0;
m_str0 = str0;
}
float m_f0;
string m_str0;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & m_f0;
ar & m_str0;
}
};
// This is the class we really want to try serializing.
class CTest {
public:
CTest(){};
CTest(int nNumber)
{
m_nNumber = nNumber;
// Fill with some dummy data.
m_mTst.insert(make_pair(0, CSomeData(0.23f, "hi hi hi")));
m_mTst.insert(make_pair(1, CSomeData(7.65f, "second one")));
m_mTst.insert(make_pair(2, CSomeData(9.23f, "third one")));
m_mTst.insert(make_pair(3, CSomeData(5.6766, "chosen one")));
}
~CTest(){};
int m_nNumber;
map m_mTst;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & m_nNumber;
ar & m_mTst;
}
};
int main()
{
std::ofstream ofs("filename");
// Write class instance to archive. Writing seems to work ok.
const CTest ct(5);
{
boost::archive::binary_oarchive oa(ofs);
oa << ct;
}
// Try to restore it sometime later.
CTest ctNew;
{
std::ifstream ifs("filename", std::ios::binary);
boost::archive::binary_iarchive ia(ifs);
// READING CAUSES THE EXCEPTION!
ia >> ctNew;
}
return 0;
}
Thanks,
Mark