读书人

关于bad_exception和auto_ptr的有关问

发布时间: 2012-02-19 19:43:38 作者: rapoo

关于bad_exception和auto_ptr的问题
1
书上说违背函数异常规范定义,即抛出异常规范中没定义的异常会导致调用unexpected(),而且会把抛出的异常转换为bad_exception,但我始终无法捕获这个异常。

class E1{
};

class E2{
};

void func() throw(E1,bad_exception)
{
throw E2();
}

int main()
{
try
{
func();
}
catch (bad_exception &e) //也无法捕获E2
{
cout < < "E2 " < <endl;
}
}
为什么不能捕获到bad_exception?


2 auto_ptr与auto_ptr_ref是什么关系?
auto_ptr类中有一个自定义转换模板函数
template <typename _Tp1>
operator auto_ptr_ref <_Tp1> () throw()
{ return auto_ptr_ref <_Tp1> (this-> release()); }

这个转换用在哪里地方 ?



[解决办法]
auto_ptr_ref 是一个完全 internal to auto_ptr 的类型,用于限定 auto_ptr 的部分特殊语意。
[解决办法]
加catch(...)试。
[解决办法]
楼主看的资料是对的,只不过是没看仔细而已;想要捕获unexcept exception 需要在程序执行的最初先调用set_unexcepted。比如下面的代码,我在mingw上测试是可以达到要求的。

#include <exception>
#include <iostream>
using namespace std;
class E1 {};
class E2 {};
void fun() throw(E1&,bad_exception&)
{
throw E2();
}
void handlunexpect()
{
throw E2();
}
int main(int argc,char* argv[])
{
set_unexpected(handlunexpect);
try{
fun();
}
catch(bad_exception& e)
{
cout < < "unexcep exception " < < endl;
}
return 0;
}

读书人网 >C++

热点推荐