了解在 noexcept 函数中调用抛出函数时真正发生的情况

问题描述 投票:0回答:1

请参阅以下代码,其中包含调用另一个抛出函数的函数的 3 个实现。

# include <stdexcept>

void f()
{
    throw std::runtime_error("");
}

void g1()
{
    f();
}

void g2() noexcept
{
    f();
}

void g3() noexcept
{
    try{ f(); } catch(...){ std::terminate(); }
}

int main()
{
    return 0;
}

根据我对

noexcept
规范的理解,
g2
g3
严格等效。但是,当我使用 GCC 在 Compiler Explorer 中编译它时,生成的代码对于
g1
g2
是严格等效的,但对于
g3
则不然:

g1():
        push    rbp
        mov     rbp, rsp
        call    f()
        nop
        pop     rbp
        ret
g2():
        push    rbp
        mov     rbp, rsp
        call    f()
        nop
        pop     rbp
        ret
g3():
        push    rbp
        mov     rbp, rsp
        call    f()
        jmp     .L9
        mov     rdi, rax
        call    __cxa_begin_catch
        call    std::terminate()
.L9:
        pop     rbp
        ret

为什么?

c++ gcc terminate noexcept
1个回答
0
投票

阅读 cppreference.com 上的 noexcept 参考,我得出的结论是编译后的代码不受

noexcept

的影响

它只是一个编译时评估,因此如果单独使用,不会影响编译器的输出。

© www.soinside.com 2019 - 2024. All rights reserved.