Virtual bases are very different from ordinary bases. Remember that "virtual" means "determined at runtime" -- thus the entire base subobject must be determined at runtime.
Imagine that you are getting a B & x
reference, and you are tasked to find the A::a
member. If the inheritance were real, then B
has a superclass A
, and thus the B
-object which you are viewing through x
has an A
-subobject in which you can locate your member A::a
. If the most-derived object of x
has multiple bases of type A
, then you can only see that particular copy which is the subobject of B
.
But if the inheritance is virtual, none of this makes sense. We don't know which A
-subobject we need -- this information simply doesn't exist at compile time. We could be dealing with an actual B
-object as in B y; B & x = y;
, or with a C
-object like C z; B & x = z;
, or something entirely different that derives virtually from A
many more times. The only way to know is to find the actual base A
at runtime.
This can be implemented with one more level of runtime indirection. (Note how this is entirely parallel to how virtual functions are implemented with one extra level of runtime indirection compared to non-virtual functions.) Instead of having a pointer to a vtable or base subobject, one solution is to store a pointer to a pointer to the actual base subobject. This is sometimes called a "thunk" or "trampoline".
So the actual object C z;
may look as follows. The actual ordering in memory is up to the compiler and unimportant, and I've suppressed vtables.
+-+------++-+------++-----++-----+
|T| B1 ||T| B2 || C || A |
+-+------++-+------++-----++-----+
| | |
V V ^
| | +-Thunk-+ |
+--->>----+-->>---| ->>-+
+-------+
Thus, no matter whether you have a B1&
or a B2&
, you first look up the thunk, and that one in turn tells you where to find the actual base subobject. This also explains why you cannot perform a static cast from an A&
to any of the derived types: this information simply doesn't exist at compile time.
For a more in-depth explanation, take a look at this fine article. (In that description, the thunk is part of the vtable of C
, and virtual inheritance always necessitates the maintenance of vtables, even if there are no virtual functions anywhere.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…