3
在测试使用Boost序列化器的一些代码时,我看到在反序列化时抛出了std :: length_error。我在Linux上运行下面的代码(在Windows上我没有看到这个问题)。我正在使用Boost 1.47.0。Boost序列化抛出std异常
我的序列化类:
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:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::resize
这是已知的(记录)Boost序列化程序的行为,我可以检查输入流以查看它是否有效或是否存在try/catch mi在反序列化器中进行选择?
问候,
约翰
'string :: resize'只有在有人试图让size()大于max_size()时才会抛出'length_error'。除非平台限制了分配大小,否则这几乎是不可能的。 – 2012-03-13 10:14:50
我认为,因为text_archive几乎没有结构,大多数错误将是这种类型,而不是archive_exception的,也许如果您使用其他存档类型,如xml,则会引发archive_exception。解决方案是捕获父级标准异常,并根据应用程序重新抛出任何异常对您的程序更具信息性。 – alfC 2012-03-13 23:10:18
@alfC:我希望(并且实际上是期待)这些例外可能会被归档人员捕获。我捕获的是archive_exception,但不是std的异常。我现在将std :: excpetion添加到catch中,现在它可以工作。 – Borkhuis 2012-03-20 11:17:29