-->

C++ vtable resolving with virtual inheritance

2019-05-19 05:40发布

问题:

I was curious about C++ and virtual inheritance - in particular, the way that vtable conflicts are resolved between bass and child classes. I won't pretend to understand the specifics on how they work, but what I've gleamed so far is that their is a small delay caused by using virtual functions due to that resolution. My question then is if the base class is blank - ie, its virtual functions are defined as:

virtual void doStuff() = 0;

Does this mean that the resolution is not necessary, because there's only one set of functions to pick from?

Forgive me if this is an stupid question - as I said, I don't understand how vtables work so I don't really know any better.

EDIT

So if I have an abstract class with two seperate child classes:

    A
   / \
  /   \
 B     C

There is no performance hit when calling functions from the child classes compared to say, just a single inheritance free class?

回答1:

There is no hit for calling nonvirtual functions in the child class. If you're calling an overridden version of your pure virtual function as in your example, then the virtual penalty may still exist. In general it's difficult for compilers to optimize away the use of the virtual table except under very specific circumstances, where it knows the exact by-value type of the object in question (from context).

But seriously don't worry about the overhead. It's going to be so little that in practice you will almost certainly never encounter a situation where it's the part of code causing performance bottlenecks. Use virtual functions where they make sense for your design and don't worry about the (tiny) performance penalty.



回答2:

I don't know what "one set of functions" you are talking about. You have two derived classes - B and C - with each having its own set of virtual functions. So, you have at least two sets, even if all functions in A are pure.

The virtual dispatch occurs when the compiler does not know the dynamic type of the object it is working with. For example, if your have a pointer A *p, it can point to an object of type B or type C. If the compiler does not know what is the actual type of the object p is pointing to, it will have to use virtual dispatch in order to call virtual functions through p.

P.S. There's no "virtual inheritance" in your example. The term virtual inheritance in C++ has its own meaning. And you are not talking about virtual inheritance here.



回答3:

The 'double dispatch' hit only occurs when the method is virtual. If the derived method is not virtual, there is no performance hit.