析构函数中的std :: ios :: exceptions预期行为是什么?

时间:2014-05-20 04:37:37

标签: c++ c++11

请考虑以下代码段:

// Case 1: Explicitly calling close() does throw, as expected.
{
    std::ifstream f;
    f.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
    f.close();  // This will throw std::ifstream::failure, as close() on unopened file sets the failbit
}

// Case 2: close() will be called by destructor of object 'g', but does not throw.
{
    std::ifstream g;
    g.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
} // Does not throw, even though "g's" destructor will call close() method

现在我明白析构函数永远不应该泄漏C ++中的异常(这也许是案例2中观察到的行为的原因)。我的问题是:C ++标准是否保证上述观察到的行为,或者它只是一个工件(如果是的话,C ++ 03和C ++ 11在这方面有什么区别吗?任何相关的引用对C ++标准非常有帮助。)

此外,如何通常实现不抛出析构函数的特殊情况,析构函数代码是否只捕获close()抛出的异常,并忽略它们?有人可以指出我在任何一个主要的编译器源代码中实现它。

2 个答案:

答案 0 :(得分:3)

  

virtual ~basic_filebuf();

     

27.9.1.2/5 效果:销毁类的对象   basic_filebuf<charT,traits>。致电close()。如果发生异常   在破坏对象期间,包括对close()的调用,   例外是被抓住但未被重新招募(见17.6.5.12)。

强调我的。

答案 1 :(得分:1)

您观察到的行为是标准的。 basic_ifstream类包含basic_filebuf对象(§27.9.1.6)。 basic_filebuf对象的析构函数调用basic_filebuf::close但会抑制抛出的任何异常。

引用§27.9.1.2/ 5 [filebuf.cons] (强调添加)

  

virtual ~basic_filebuf();
效果:销毁类的对象   basic_filebuf<charT,traits>。致电close()。如果发生异常   在销毁对象期间,包括对close()的调用,   异常被抓住但未被重新招募(见17.6.5.12)。