默认情况下,final class 的方法是否应用于指向函数优化的指针?

Are methods of the final class applied to pointer to function optimization by default?

如此处所述: How does the compiler benefit from C++'s new final keyword? 正如这个问题中所述,方法的final关键字可以优化对简单函数指针调用的vtable调用。

如果我有 class:

class Derived final : public Base
{
virtual void Foo() override;
//virtual void Foo() final override; Are these statements equal?
}

编译器会将此类方法标记为 final 并应用函数指针而不是 vtable 吗? 我对具有最高优化级别集的 vc120 和 clang 编译器行为感兴趣。

没有什么可以阻止编译器推断 Foo 无法进一步覆盖。由于您在问题中指定了 Clang,下面是我使用 -O1:

在 Clang 5 上测试的示例代码
struct Base {
    virtual void Foo() = 0;
};

struct  Derived final : public Base
{
virtual void Foo() override {}
//virtual void Foo() final override; Are these statements equal?
};

Derived* getD();

int main() {

    getD()->Foo();

    return 0;
}

它产生了这个(Live on godbolt):

main:                                   # @main
        push    rax
        call    _Z4getDv
        mov     rdi, rax
        call    _ZN7Derived3FooEv
        xor     eax, eax
        pop     rcx
        ret
_ZN7Derived3FooEv:                      # @_ZN7Derived3FooEv
        ret

如您所见,编译器完全能够推断出它可以直接调用 Derived::Foo