在测试一些使用 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:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::resize
这是 Boost 序列化程序的已知(已记录)行为吗?我可以检查输入流以查看它是否有效,或者反序列化程序中是否缺少 try/catch?
问候,
约翰
最佳答案
您正在编写一个字符串并读取您的 TestClass。
你的线路
archive & this->string2;
确实已经尝试从未初始化的内存中读取。这意味着,您很可能会尝试分配一个过大的 std::string(50% 的情况,很可能每次都有两个字符串)。
因此,异常来自您的代码,并且未从存档程序中捕获也就不足为奇了。
关于c++ - Boost序列化抛出std异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9681853/