【问题标题】:Boost serialization throws std exceptionBoost序列化抛出std异常
【发布时间】:2012-03-13 09:59:44
【问题描述】:

在测试一些使用 Boost 序列化程序的代码时,我看到在反序列化时抛出了 std::length_error。我在 Linux 上运行下面的代码(在 Windows 上我没有看到这个问题)。我正在使用 Boost 1.47.0。

我的序列化类:

class TestClass
{
public:
    TestClass() {};

    TestClass(const char* string1, const char* string2, const char* string3):
        string1(string1),
        string2(string2),
        string3(string3)
    {};

    template<class Archive>
    void serialize(Archive & archive, const unsigned int version)
    {
        // When the class Archive corresponds to an output archive, the
        // & operator is defined similar to <<.  Likewise, when the class Archive
        // is a type of input archive the & operator is defined similar to >>.
        archive & this->string1;
        archive & this->string2;
        archive & this->string3;
    }

    std::string string1;
    std::string string2;
    std::string string3;
};

我的测试代码:

TestClass testClass;
std::string value("nonsense");
try
{
    std::stringstream stringStream;
    stringStream << value;
    boost::archive::text_iarchive serializer(stringStream);
    serializer >> testClass;
}
catch (const boost::archive::archive_exception& e)
{
    ....
}

执行此代码时,我得到一个 std::length_error:

在抛出 'std::length_error' 实例后调用终止
what(): basic_string::resize

这是 Boost 序列化器的已知(记录)行为,我可以检查输入流以查看它是否有效或反序列化器中是否缺少 try/catch?

问候,
约翰

【问题讨论】:

  • string::resize 只会在有人试图使size() 大于max_size() 时抛出length_error。除非平台限制了分配大小,否则这几乎是不可能的。
  • 我认为因为 text_archive 几乎没有结构,所以大多数错误都是这种类型的,而不是 archive_exception 的,也许如果你使用其他存档类型,比如 xml,archive_exception 会被引发。解决方案是捕获父标准异常,并根据应用程序重新抛出任何对您的程序提供更多信息的异常。
  • @alfC:我希望(并且实际上期望)这些异常会被归档程序捕获。我正在捕获archive_exception,但没有捕获std异常。我现在将 std::excpetion 添加到 catch 中,现在它可以工作了。

标签: c++ boost boost-serialization


【解决方案1】:

您正在编写一个字符串并读取您的 TestClass。

你的线路

archive & this->string2;

已经尝试从未初始化的内存中读取。这意味着,您可能会尝试分配一个太大的 std::string(50% 的时间,每次都非常可能有两个字符串)。

因此,异常来自您的代码,没有从归档器中捕获也就不足为奇了。

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    相关资源
    最近更新 更多