【发布时间】: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