Is there a performance limitation when a virtual method is called from a class that is known to be a derived class at compile time? See code below.
It depends. Most compilers will de-virtualize the code as follows:
Derived1 d; d.speak();
The dynamic type of an object is known at the call site, so the compiler can avoid passing through the vtable to call and can simply call Derived1::speak()
directly.
In your example, the compiler should be smarter, because in force_speak
you only have Derived1*
pointers (stored inside unique_ptr
objects), and in this context it does not unique_ptr
out if the dynamic type of objects with a pointer is Derived1
or some more derived type. The compiler needs to include a force_speak
call in main
(where the dynamic type is known) or use some additional type information to enable devirtualization. (As an example of additional knowledge, optimizing the entire program may determine that there are no other derived types in the production program, so Derived1*
must point to Derived1
.)
Using the C ++ 11 final
keyword can help compilers devirtualize some cases, for example. if Derived1
marked final
, then the compiler knows that Derived1*
can only point to Derived1
, and not to any other type derived from it that can override speak()
source share