final是否在C ++中用于优化? [英] Is final used for optimization in C++?

查看:150
本文介绍了final是否在C ++中用于优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {
public:
    virtual void f() = 0;
};

class B : public A {
public:
    void f() final override { };
};

int main() {
    B* b = new B();
    b->f();
}

在这种情况下,编译器是否仍需要执行v表查找for b-&f; f(); ,还是可以直接调用 B :: f()标记为 final

In this case, is the compiler required to still do the v-table lookup for b->f();, or can it call B::f() directly because it was marked final?

推荐答案


是最终的在C ++中用于优化?

Is final used for optimization in C++?

它可以是也可以是。

如前所述,它已经被使用了; 请参见此处此处显示带有和不带有 final 的覆盖生成的代码。

As noted, it is being used already; see here and here showing the generated code for the override with and without final.

沿这些方面的优化将与虚拟调用的去虚拟化有关。这并不总是立即受到class或method的 final 的影响。尽管它们提供了确定的帮助,但仍适用虚拟函数和类层次结构的常规规则。

An optimisation along these lines would relate to the "de-virtualization" of the virtual calls. This is not always immediately affected by the final of the class nor method. Albeit they offer help to determine this, the normal rules of the virtual functions and class hierarchy apply.

如果编译器可以确定在运行时始终将调用特定方法(例如,给定带有自动对象的OP示例),无论采用哪种方法,它都可以应用无论如何都是优化是否为最终

If the compiler can determine that at runtime a particular method will always be called (e.g. given the OP example, with an automatic object), it could apply such an optimisation anyway, irrespective of whether the method is final or not.

优化属于 按条件规则 ,只要可观察到的行为按原样,编译器就可以应用任何转换原始代码已执行。

Optimisations fall under the as-if rule, that allow the compiler to apply any transformation so long as the observable behaviour is as-if the original code had been executed.

这篇关于final是否在C ++中用于优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆