简体   繁体   中英

Virtual methods whose type is known at compile-time

If I do something like:

Dog dog; //class with virtual methods
Cat cat; //class from same base as Dog

dog.eat(); //call virtual method
cat.eat(); //call virtual method

Then the eat()s will be normal method calls and will not require the v-table - correct? I can assume that it would run identical to a non-virtual method?

(and yes, I know that how compilers handle virtual functions is not in the standard - I want to know what most compilers do)

When you're using object.member - you're not dereferencing a pointer, so there's no effect to the virtual methods. Virtual comes into effect only when you have a pointer which can be polymorphic and dynamic dispatch is used.

For example:

Cat cat;
Animal *cat2 = &cat;
cat.eat(); // direct call
//... a lot of other code and function calls that pass cat2 around, to avoid optimization
cat2->eat(); // dynamic dispatch

edit corrected per comments

Visual Studio is able to optimize a virtual call into a direct call if profiling shows that a certain type is used most of the time.

Virtual Call Speculation – If a virtual call, or other call through a function pointer, frequently targets a certain function, a profile-guided optimization can insert a conditionally-executed direct call to the frequently-targeted function, and the direct call can be inlined.

See Profile Guided Optimization on MSDN.

Regular "devirtualization" (ie what the other answers allude to) can be done without profiling the app, and is pretty common.

GCC enables this optimization automatically, but the specific flag is -fdevirtualize :

Attempt to convert calls to virtual functions to direct calls. This is done both within a procedure and interprocedurally as part of indirect inlining (-findirect-inlining) and interprocedural constant propagation (-fipa-cp). Enabled at levels -O2, -O3, -Os.

from GCC Optimize Options .

If the static type is known at compile time there is no need to use the vtable, as the function to call in known anyway.

Most compilers will see this.

I would say that yes, most compilers would do this optimization. If you've profiled and it actually matters, the only way to know for sure is to check the disassembly generated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM