【问题标题】:Error when trying to use the Boost Serialization library尝试使用 Boost 序列化库时出错
【发布时间】:2012-01-27 21:50:12
【问题描述】:

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

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

【问题讨论】:

  • 什么版本的 boost 和你使用什么编译器?代码在我的机器上运行良好。
  • 是的,这里也一样。用 1.46.1 和 VS2010 试了一下

标签: c++ boost boost-serialization


【解决方案1】:

事情是这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多