Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler Optimization of virtual function calls

Most popular example to illustrate why virtual dispatch happens at runtime is when it cannot be determined at compile time which Derived class is going to be created. For example:

Base* b = (rand() % 2 == 1 ? new Derived1() : new Derived2());

or when it depends on user input.

Suppose none of that is the case and it can be completely determined at compile time which Derived class the base pointer is referring to.

If it is known at compile time which Derived class the base class pointer points to, does the compiler optimize the virtual function call by substituting it with appropriate Derived function and not doing vtable lookup during runtime?

like image 998
nishantsingh Avatar asked Jun 12 '18 11:06

nishantsingh


1 Answers

Such optimization is called Devirtualization. At least Clang performs it, see this blog post and this post on mailing list.

like image 177
arrowd Avatar answered Sep 29 '22 04:09

arrowd