我做了一个简单的程序来重现问题:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/tuple/tuple.hpp>
#include <sstream>
#include <iostream>
template<typename T>
std::string serialize(const T & value)
{
std::ostringstream oss;
boost::archive::text_oarchive oa(oss);
oa << value;
return oss.str();
}
template<typename T>
T deserialize(const std::string & buffer)
{
std::istringstream iss(buffer);
boost::archive::text_iarchive ia(iss);
T ret;
ia >> ret;
return ret;
}
struct MyClass
{
MyClass() {}
MyClass(const std::string & name) : name(name) {}
template<class Archive>
void serialize(Archive & ar, const unsigned int)
{
ar & name;
}
std::string name;
};
int main()
{
MyClass myClass("Test");
std::string serialized = serialize(myClass);
std::cout << "Serialized: " << serialized << std::endl;
MyClass deserialized = deserialize<MyClass>(serialized);
std::cout << "Name after deserialization: " << deserialized.name << std::endl;
}
代码编译正常,但在运行时出现以下错误:
Serialized: 22 serialization::archive 9 0 0 4 Test
test(74010) malloc: *** error for object 0x109bf55e0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
在调试器中,我可以看到当 boost 尝试反序列化name
变量时会发生错误。
谁能帮我弄清楚我做错了什么?
更新
我在 Mac OS X Lion 上并使用 GCC 4.6.2 ( g++-mp-4.6 (GCC) 4.6.2
) 和 boost 1.48 版本。两者都通过 MacPorts 安装。
命令行是:
g++ -o test -I/opt/local/include -L/opt/local/lib main.cpp -lboost_serialization
您可以在此处从 subversion 签出代码:http: //stacked-crooked.googlecode.com/svn/trunk/Playground/Serialization。
更新
我在 Linux GCC 4.6.1 和 boost 1.48 上进行了测试,它运行良好。不知何故,这一定是我在 Mac 上的配置所特有的问题。