这片CPP代码如何转储

How does this piece of cpp code dump?

本文关键字:转储 何转储 CPP 代码 这片      更新时间:2023-10-16

我的意思是要获得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

谁能给我一些提示?

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

main()中,您构建一个实例。然后,您抛出一个例外。被捕获, A::~A被称为 引发异常。在飞行中有两个例外,同时导致terminate()(或提供的用户提供的等效)被调用(默认情况下,call abort()降低了核心。无论哪种方式,程序都无法恢复。)

旁边:这是导致一般最佳实践规则的原因,除非您的意思是杀死程序。

set_terminate()期望函数providide 终止 program。

函数无参数并返回void。功能应 不返回,并且应终止程序。terminate_handler是一个 功能指针类型没有参数和返回void。

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