【发布时间】:2012-10-11 16:39:07
【问题描述】:
我写了一个非常简单的解决方案,但是有人笑了,发现了一个缺陷,如下所示http://ideone.com/IcWMEf
#include <iostream>
#include <ostream>
#include <functional>
#include <exception>
using namespace std;
// Wrong scope(failure)
class FailBlockT
{
typedef function<void()> T;
public:
T t;
FailBlockT(T t)
{
this->t=t;
}
~FailBlockT()
{
if (std::uncaught_exception())
{
t();
}
}
};
struct Test
{
~Test()
{
try
{
FailBlockT f([]()
{
cout << "failure" << endl;
});
// there is no any exception here, but "failure" is printed.
// See output below
}
catch(...)
{
cout << "some exception" << endl;
}
}
};
int main()
{
try
{
Test t;
throw 1;
}
catch(int){}
return 0;
}
简而言之,问题是我的代码查看std::uncaught_exception()。当抛出异常并执行正常的析构函数时。如果我在那里使用范围故障,它会查看 std::uncaught_exception() 并认为对象范围由于异常而丢失,而不是简单地走出范围。
我想不出任何好的解决方案来区分正常离开范围与在其中抛出异常。是的,我知道在 dtors 中抛出是一个坏主意,但这就是为什么我没有注意到这个问题,因为我从不抛出异常。
我如何区分/解决这个问题?
【问题讨论】:
-
目前还不清楚您到底想要完成什么。
-
@sth 我加粗了,有帮助吗?
-
@acidzombie24:好的,我们试试这个方法。 为什么您要“区分正常离开范围与在其中抛出异常”?更具体地说,为什么你需要在析构函数中这样做,唯一的目的应该是在对象之后进行清理?为什么析构函数需要关心它是否由于异常而被清理?
-
另外,什么是“范围故障”?
-
@NicolBolas 这个问题的答案解释了 Scope(failure) {...} 是什么 stackoverflow.com/questions/1247778/… 并且在演示中喜欢 37-39 显示了问题。没有抛出异常,但它认为它有。
标签: c++ exception c++11 destructor