【发布时间】:2014-05-20 13:31:08
【问题描述】:
考虑一下这个sn-p:
// 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() 抛出的异常,并忽略它们?有人可以指出我在任何主要编译器源代码中的实现。
【问题讨论】: