有一些文章的结论是“永远不要从析构函数抛出异常”和“std::uncaught_exception() 没有用”,例如:
-
http://www.gotw.ca/gotw/047.htm(赫伯·萨特撰写)
但我似乎没有明白这一点。所以我写了一个小的测试示例(见下文)。
由于测试示例一切正常,我非常感谢一些关于它可能有什么问题的评论?
测试结果:
./main
Foo::~Foo(): caught exception - but have pending exception - ignoring
int main(int, char**): caught exception: from int Foo::bar(int)
./main 1
Foo::~Foo(): caught exception - but *no* exception is pending - rethrowing
int main(int, char**): caught exception: from Foo::~Foo()
example:
// file main.cpp
// build with e.g. "make main"
// tested successfully on Ubuntu-Karmic with g++ v4.4.1
#include <iostream>
class Foo {
public:
int bar(int i) {
if (0 == i)
throw(std::string("from ") + __PRETTY_FUNCTION__);
else
return i+1;
}
~Foo() {
bool exc_pending=std::uncaught_exception();
try {
bar(0);
} catch (const std::string &e) {
// ensure that no new exception has been created in the meantime
if (std::uncaught_exception()) exc_pending = true;
if (exc_pending) {
std::cerr << __PRETTY_FUNCTION__
<< ": caught exception - but have pending exception - ignoring"
<< std::endl;
} else {
std::cerr << __PRETTY_FUNCTION__
<< ": caught exception - but *no* exception is pending - rethrowing"
<< std::endl;
throw(std::string("from ") + __PRETTY_FUNCTION__);
}
}
}
};
int main(int argc, char** argv) {
try {
Foo f;
// will throw an exception in Foo::bar() if no arguments given. Otherwise
// an exception from Foo::~Foo() is thrown.
f.bar(argc-1);
} catch (const std::string &e) {
std::cerr << __PRETTY_FUNCTION__ << ": caught exception: " << e << std::endl;
}
return 0;
}
ADDED:换句话说:尽管有些文章中有警告,但它仍按预期工作 - 那么它可能有什么问题呢?
赫伯·萨特指的是另一个问题。他正在谈论:
try
{
}
catch (...)
{
try
{
// here, std::uncaught_exception() will return true
// but it is still safe to throw an exception because
// we have opened a new try block
}
catch (...)
{
}
}
所以问题是如果std::uncaught_exception()
返回 true 你不确定是否可以安全地抛出异常。你最终必须避免抛出异常std::uncaught_exception()
为了安全起见,返回 true。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)