RTTI and polymorphism implementation mechanism

xiaoxiao2021-03-06  102

C RTTI and polymorphism implementation mechanism

RTTI is Dynamic_cast or TypeID, is only valid for the reference and pointer.

Assume that a polymorphic inheritance system is implemented:

Class Base

{

PUBLIC:

Virtual void fun ();

}

Class deer

Base * pp = new deerived ();

Derived * pp2 = Dynamic_cast (pp);

PP-> Fun ();

DELETE PP;

Let's take a look at how RTTI implements: Derived * pp2 = Dynamic_cast (pp);

When this statement is performed, first find the memory pointed to by the PP, remove the contents of the four bytes of the middle of this memory, which is the value of VPTR, then find the memory pointing by VPTR, stored in VTBL, and VTBL An element is the type information of the PP pointing to the entity (which can be used to explain the contents of the PP pointing). At this point, you can decide Dynamic_CAST (PP) whether it returns NULL or the conversion is successful.

Realization of polymorphism: PP-> Fun ();

The position of the FUN function pointer in VTBL is determined in the compile period, because the contents and formats of the VBTL are basically determined after the virtual function declaration of the Base class.

The principle is similar to the same. First, find the memory pointing by the PP, take it out of the four bytes of the head in this memory, which is the value of VPTR, then find the memory pointing to the VPTR, and stores VTBL, and the second element of VTBL is VPTR [ 1] The function pointer of the function that needs to be called.

note:

(1) VTBL of each class is scheduled in the compile period, but until the running period knows the memory address occupied by a VBTL.

(2) The function of the function pointer in each VTBL is determined in the compile period, but the value of the function pointer is determined at the runtime, because only the time of the running period will know the address stored in the memory space. . You can also understand each function as a Singleton class.

(3) VPTR is inserted from the compiler into the Class definition, generally as the first member of the class.

(4) VPTR is initialized in the constructor (this code is also the compiler), so the value of the VPTR is determined at the runtime period. It can be understood this way: vptr = vtbl.createInstance (); VTBL is actually a Singleton class. That is, a class corresponds to a VTBL, all objects that are changed, use the same VTBL.

转载请注明原文地址:https://www.9cbs.com/read-123984.html

New Post(0)