代码之家  ›  专栏  ›  技术社区  ›  Superlokkus

抛出main,即未捕获到SIGSEGV中的异常结果

  •  0
  • Superlokkus  · 技术社区  · 9 月前

    Given the code

    #include <iostream>
    #include <stdexcept>
    
    class Test {
    public:
        Test() { std::cout << "Constructor called" << std::endl; }
        ~Test() { std::cout << "Destructor called" << std::endl; }
    };
    
    int main() {
        Test obj1;
    
        try 
        {
            Test obj2;
            throw std::runtime_error("Exception thrown"); 
        } // Object 2 is destroyed here
        catch (...)
        {
            throw; // std::abort
        }
    } // not reached (implementation defined), Object 1 destructor never called
    
    

    我理解为什么的析构函数 obj2 没有被调用,因为它的实现定义了在未捕获异常的情况下进行堆栈展开,但我不明白为什么在通常的L inux platforms it's allowed or thinks it has to terminate with a SIGSEGV signal 。据我所知,预计会有SIGABRT。

    1 回复  |  直到 9 月前
        1
  •  3
  •   Artyer    9 月前

    这是编译器资源管理器的人工产物(/bug?)。 SIGABRT 成为 SIGSEGV : https://github.com/compiler-explorer/compiler-explorer/issues/5224

    在我的计算机上运行它可以:

    $ ./example ; echo "Program returned: $?"
    Constructor called
    Constructor called
    Destructor called
    terminate called after throwing an instance of 'std::runtime_error'
      what():  Exception thrown
    Aborted
    Program returned: 134
    

    即使在编译器资源管理器上,您也可以处理 SIGABRT 看到它还在那里,只有一个 sigsegov 之后: https://godbolt.org/z/6dYsP5K5K

    std::signal(SIGABRT, [](int) {
        std::cout << "Caught SIGABRT\n" << std::flush;
    });
    std::signal(SIGSEGV, [](int) {
        std::cout << "Caught SIGSEGV\n" << std::flush;
        std::_Exit(1);
    });
    

    编译器资源管理器输出:

    Program returned: 1
    terminate called after throwing an instance of 'std::runtime_error'
      what():  Exception thrown
    Constructor called
    Constructor called
    Destructor called
    Caught SIGABRT
    Caught SIGSEGV
    

    我的电脑:

    $ ./example ; echo "Program returned: $?"
    Constructor called
    Constructor called
    Destructor called
    terminate called after throwing an instance of 'std::runtime_error'
      what():  Exception thrown
    Caught SIGABRT
    Aborted
    Program returned: 134