尝试使用Boost序列化库时出错

Error when trying to use the Boost Serialization library

本文关键字:出错 序列化 Boost      更新时间:2023-10-16

我制作了一个简单的程序来重现这个问题:

#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上的配置特有的问题。

发生了什么:

  1. Boost是由MacPorts使用内置的Apple GCC 4.2构建的
  2. 我用非Apple GCC 4.6.2(也是从MacPorts获得的)编译我的程序
  3. 运行时加载的boost二进制文件与我的二进制文件不兼容
  4. 撞车