55
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?

Niall
  • 30,036
  • 10
  • 99
  • 142
tmlen
  • 8,533
  • 5
  • 31
  • 84

1 Answers1

51

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.

Community
  • 1
  • 1
Niall
  • 30,036
  • 10
  • 99
  • 142
  • 1
    This has been the answer for a long time, but is any compiler /actually/ using final for devirtualization? – Johan Lundberg May 27 '16 at 22:10
  • 5
    @JohanLundberg: Quick experimentation with the [Compiler Explorer](https://godbolt.org/g/f02eYq) and locally shows that at least gcc 6.1, clang 3.8 and MSVC++2015U2 use the `final` keyword for devirtualization. – user786653 May 28 '16 at 07:32
  • 3
    For anyone curious I think this is where this optimization currently happens in clang: [CodeGenFunction::CanDevirtualizeMemberFunctionCall](https://github.com/llvm-mirror/clang/blob/0e2d28ae3ba7407eb4c0b777f63e237013608261/lib/CodeGen/CGClass.cpp#L2676) – user786653 May 28 '16 at 20:59
  • 5
    @JohanJundberg There is an excellent blog serious from one of the gcc developers about devirtualization: http://hubicka.blogspot.de/2014/01/devirtualization-in-c-part-1.html. It also contains an explanation when final helps, and gcc introduced a warning for cases where adding `final`would enable optimizations which cannot be done otherwise. – Jens May 29 '16 at 19:12