Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is final used for optimization in 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(); } 

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?

like image 364
tmlen Avatar asked May 24 '16 13:05

tmlen


People also ask

Does Final improve performance C++?

Marking your classes or member functions as final can improve the performance of your code by giving the compiler more opportunities to resolve virtual calls at compile time.

What is final specifier in c++?

final specifier in C++ 11 can also be used to prevent inheritance of class / struct. If a class or struct is marked as final then it becomes non inheritable and it cannot be used as base class/struct.


1 Answers

Is final used for optimization in C++?

It can be, and is.

As noted, it is being used already; see here and here showing the generated code for the override with and without 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.

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.

like image 75
Niall Avatar answered Sep 19 '22 15:09

Niall