How do dynamic castings work?

Say I have type A and a derived type B. When I do a dynamic conversion from A * to B *, what is a "run check" environment? How does he know that the cast is legal?
I assume that in .Net you can use attached metadata in the object header, but what happens in C ++?

+4
source share
4 answers

The exact algorithm is specfic compiler. Here's how it works according to Itanium C ++ ABI (2.9.7) standard (written after and after GCC).

A pointer to the base class is a pointer to the middle of the body of the "large" class. The body of the "big" class is assembled in such a way that any base class that your pointer points to allows you to evenly access RTTI for this "big" class, which is actually your "base" class. This RTTI is a special structure that refers to the "big" information about the class: what type it has, what bases it has and at what displacements they are.

In fact, this is the "metadata" of the class, but in a more "binary" style.

V instance; Base *v = &instance; dynamic_cast<T>(v); 

Dynamic listing takes advantage of the fact that when writing dynamic_cast<T>(v) compiler can immediately identify the metadata for the "large" class v - i.e. V ! When you write it, you think that T more output than Base , so the compiler will not be easy to throw with the base. But the compiler can immediately (at runtime) determine the most deuterated type - V - and it must then cross the inheritance graph contained in the metadata to see if it can disable V to T If possible, it just checks the offset. If it cannot or is single-valued, it returns NULL .

+3
source

Dynamic conversion is a two-step process:

  • Given the vtable of the object pointer, use the offset to restore the pointer to the full class. (After that, all adjustments from this pointer will be made.) This is the equivalent of dropping down to full class.

  • Find the field_type of the full class for the type you need, in other words, look at the list of all databases. If we find one, use the offset to adjust the pointer again. If the search in step 2 failed, return NULL.

+3
source

A dynamic listing performs a runtime check to see if it is a valid and feasible drop; it will return NULL when translation is not possible.

0
source

Submit your favorite book on RTTI.

-2
source

All Articles