saj*_*jas 13 c++ constructor exception-handling global
我知道拥有全局变量并不受欢迎.但在本书中,作者Bjarne Stroustrup撰写的C++编程语言称,"在非本地静态对象的初始化器抛出的情况下获得控制权的唯一方法是set_unexpected()".怎么做?
我在其他一些论坛上发布了这个问题并得到了一些答案.
第一个是声明一个指针而不是一个对象并在main()中初始化它
第二个是从另一个执行set_terminate的类派生类(其构造函数抛出异常),以便设置一个有意义的处理程序.第二个似乎在codeblocks ide中工作正常.
我用来测试它的代码是:
void f() //Unexpected exception handler
{
cout<<"Terminate called "<<endl;
exit (0);
}
class A //Base class that performs set_unexpected
{
terminate_handler h;
public:
A()
{
h=set_terminate(f);
}
~A()
{
set_terminate(h);
}
};
class B:public A //Derived class that throws unexpected_exception
{
public:
B()
{
throw 1;
}
};
B b;
int main()
{
}
Run Code Online (Sandbox Code Playgroud)
程序显示消息:"终止被叫"并退出.