我在从 std::istringstream
构造 boost::archive::text_iarchive
时似乎遇到错误
#include <vector>
#include <string>
#include <thread>
#include <atomic>
#include <iostream>
#include <unordered_map>
#include <functional>
#include <sstream>
#include "boost/asio.hpp"
#include "boost/bind.hpp"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
int main() {
std::vector<char> readBuffer_(8, 'x');
std::string archive_data(&readBuffer_[0], readBuffer_.size());
std::istringstream archive_stream(archive_data);
if (archive_stream) {
std::cout << "functioning" << std::endl;
}
boost::archive::text_iarchive archive(archive_stream);
std::cout << "woop" << std::endl;
}
可能是什么问题?
最佳答案
由于输入数据 xxxxxxxx
反序列化非法,代码出现异常。
input_stream_error 的文档:
An error has occured during stream input or ouput. Aside from the common situations such as a corrupted or truncated input file, there are several less obvious ones that sometimes occur. This includes an attempt to read past the end of the file. Text files need a terminating new line character at the end of the file which is appended when the archive destructor is invoked. Be sure that an output archive on a stream is destroyed before opening an input archive on that same stream. That is, rather than using something like
您可以通过将输入字符串替换为有效的序列化内容来验证它:
#include <array>
#include <atomic>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <functional>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
int main() {
std::istringstream archive_stream(
"22 serialization::archive 9 3 0 1 3 5 0 0 2 0 0 0 1 3 one 2 3 two");
if (archive_stream) {
std::cout << "functioning" << std::endl;
}
try {
boost::archive::text_iarchive archive(archive_stream);
} catch (const std::exception& e) {
std::cout << "except hit:" << e.what() << std::endl;
}
std::cout << "woop" << std::endl;
}
一个related question查看 boost 序列化格式详细信息。一般来说,我们应该对boost实现结果生成的内容进行反序列化,以避免此类错误。
补充一下,我们应该捕获异常以使我们的程序健壮,有几个原因会导致数据损坏并出现反序列化异常:
- 磁盘数据损坏
- 网络传输错误
- 系统的其他进程/模块存在错误
关于c++ - 从 std::istringstream 构造 boost::archive::text_iarchive 时出现未知异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68236872/