1

我的意思是获得一些知识stack unwinding并遇到了这个页面,它用下面的例子演示了它。

#include <iostream>
using namespace std;

struct E {
  const char* message;
  E(const char* arg) : message(arg) { }
};

void my_terminate() {
  cout << "Call to my_terminate" << endl;
};

struct A {
  A() { cout << "In constructor of A" << endl; }
  ~A() {
    cout << "In destructor of A" << endl;
    throw E("Exception thrown in ~A()");
  }
};

struct B {
  B() { cout << "In constructor of B" << endl; }
  ~B() { cout << "In destructor of B" << endl; }
};

int main() {
  set_terminate(my_terminate);

  try {
    cout << "In try block" << endl;
    A a;
    B b;
    throw("Exception thrown in try block of main()");
  }
  catch (const char* e) {
    cout << "Exception: " << e << endl;
  }
  catch (...) {
    cout << "Some exception caught in main()" << endl;
  }

  cout << "Resume execution of main()" << endl;
}

但是,当我使用g++ /*clang++* 编译时,它得到了核心转储。输出如下:

In try block
In constructor of A
In constructor of B
In destructor of B
In destructor of A
Call to my_terminate
已放弃 (核心已转储)   #core dump

谁能给我一些提示?

4

2 回答 2

2

答案是您在抛出异常时正在抛出异常。

main()中,您构造了一个 A 实例。然后你抛出一个异常。 它被捕获之前,A::~A被调用,它也会抛出一个异常。同时存在两个异常会导致terminate()(或用户提供的等效项)被调用(默认情况下,调用 abort(),这会丢弃一个核心。无论哪种方式,程序都无法恢复。)

另外:这是导致一般最佳实践规则的原因,即您不得在析构函数中抛出异常,除非您打算让它杀死您的程序。

于 2012-10-30T14:48:11.117 回答
0

set_terminate()期望函数提供给它终止程序。

不带参数并返回 void 的函数。该函数不应返回并应终止程序。terminate_handler 是一个不带参数并返回 void 的函数指针类型。

如果您没有在提供的函数中退出,set_terminate 在调用终止函数后会自动调用 abort()。只需添加exit(0);my_terminate()避免看到此 abort() 消息。

于 2012-10-30T14:38:34.737 回答