【问题标题】:boost::archive::text_iarchive constructor exceptionboost::archive::text_iarchive 构造函数异常
【发布时间】:2015-04-13 22:21:54
【问题描述】:

我在 64 位 Windows 7 上使用 Embarcaderro C++ Builder XE7(默认提供 Boost 库)。

我觉得很奇怪, boost::archive::text_iarchive 的构造函数抛出了一些异常,因为似乎没有放错地方。我在 stackoverflow 上发现了类似的问题,但问题是,构造函数没有放在 try 块中。

我的代码看起来像这样(请注意,这个 main() 实际上是在按下按钮时执行的函数,因为我使用 C++ Builder。粘贴整个代码会令人困惑且不必要)。

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>
using namespace std;

int main()
{
    int numbers1[10] , numbers2[10];
    for(int i=0; i<10; i++) {numbers1[i] = i;}

    ofstream ofs("D:/Pulpit/file.txt", ios::out | ios::trunc);
    if(!ofs.good()) return 1;
    boost::archive::text_oarchive oar(ofs); //no exception
    oar << numbers1;

    fstream ifs("D:/Pulpit/file.txt", ios::in);
    if(!ifs.good()) return 1;
    boost::archive::text_iarchive iar(ifs); //exception
    iar >> numbers2;
}

如您所见,它只是 iarchive 的定义,带有 std::ifstream 参数,它已正确打开(因为 if(!ifs.good()))。但是我仍然得到 boost::archive::archive_exception 类型的异常。真正奇怪的是我无法以任何方式处理它。甚至 catch(...) 也没有捕捉到它,我的程序终止了。

我确定 costructor(或者可能是析构函数?)抛出了异常——注释掉最后两行后一切正常。

输出类 - oarchive - 不会抛出异常。它似乎可以很好地序列化所有内容,但那时我无法阅读。如果我尝试使用 stringstreams 而不是 fstreams,从而排除文件故障,也会发生同样的事情。

【问题讨论】:

  • 你真的能读懂文件吗?并在不使用文件的情况下验证内容(例如,写入 std::stringstream 并将其读回?)。也就是说,能不能减少和消除?
  • @sehe 是的,使用 ostringstream 和 istringstream,给出了相同的结果(输出似乎工作,输入崩溃),除了即使截断输入流也不能阻止构造函数中的异常(也无法捕获)。
  • 在这种情况下,发布自包含示例,以便我们可以实际解决问题:)
  • 完成。我没有发布实际代码,因为它是windows应用程序,所以会出现很多不重要的东西。我希望 int main() 就足够了。
  • 好的,已回答。具有讽刺意味的是,该行为似乎取决于编译器/平台:stringstream not crashing。但正如我在回答中所展示的,最好还是明确说明你想要什么

标签: c++ exception serialization boost catch-all


【解决方案1】:

您必须先关闭输出文件/存档,然后才能将其作为输入打开。

否则不会刷新完整的存档:

Live On Coliru

{
    std::ofstream ofs("file.txt");
    if (!ofs.good())
        return 1;

    boost::archive::text_oarchive oar(ofs); // no exception
    oar << numbers1;
}

{
    std::ifstream ifs("file.txt");
    if (!ifs.good())
        return 1;
    boost::archive::text_iarchive iar(ifs); // no exception!
    iar >> numbers2;
}

stringstream 解决方案:Live On Coliru

输出

0 1 2 3 4 5 6 7 8 9 

【讨论】:

  • 非常感谢先生,这正是问题所在!
猜你喜欢
  • 2021-09-15
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 2016-01-23
  • 2015-05-08
  • 2010-12-01
相关资源
最近更新 更多