c++ - 从 std::istringstream 构造 boost::archive::text_iarchive 时出现未知异常

标签 c++ boost boost-serialization

我在从 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/

相关文章:

C++ 转换日期格式

c++ - 使用 Boost 序列化双端队列 vector 的问题

c++ - boost 几何 : legacy objects adaptation

c++ - Eigen 矩阵 + Boost::Serialization/C++17

c++ - boost 序列化: safe to ignore warning?

c++ - 尽管一切看起来都正确,为什么 boost::serialize 不起作用? ("unregistered class")

c++ - 将位解压缩为单精度 float 的最快方法

c++ - 我可以使用什么 C++ 库来创建和简化贝塞尔曲线

c++ - 应用中的脚本系统

c++ - 无法使用包装不同下一层的两个 ssl_stream 编译代码