c++ - 默认情况下,final 类的方法是否应用于函数指针优化?

标签 c++ c++11 vtable

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

如果我有课:

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

关于c++ - 默认情况下,final 类的方法是否应用于函数指针优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47456271/

相关文章:

c++ - 访问使用 def 文件导出的静态变量时崩溃

C++ 当 bool 改变时触发函数

c++ - 函数作为 std::function 包装器的构造函数的参数

c++ - 'Constexpr' 与 'extern const' 对比。哪个优先?

c++ - cppunit 和 xcode 项目的 vtable 问题

多重继承中的c++ vtable,指向thunk方法的指针

c++ - C++中是否有任何默认函数来搜索字符串中的单词?

c++ - 为什么这两个循环在使用 -O3 编译时运行得同样快,但在使用 -O2 编译时却不是?

c++ - 无法将带有 bool 网格的文本文件读入 vector 的 vector 中

C++:直接使用派生类型的模板方法模式