vftable - what is this?

2019-04-09 06:41发布

问题:

What is vftable in high programming languages?

I read something like it's the address of a virtual object structure, but this is a pretty messy information

Can someone please explain it?

回答1:

It most likely stands for "Virtual Function Table", and is a mechanism used by some runtime implementations in order to allow virtual function dispatch.

Mainstream C++ implementations (GCC, Clang, MSVS) call it the vtable. C has no polymorphism. I could only speculate about other languages.


Here's what Wikipedia says on the topic:

An object's dispatch table will contain the addresses of the object's dynamically bound methods. Method calls are performed by fetching the method's address from the object's dispatch table. The dispatch table is the same for all objects belonging to the same class, and is therefore typically shared between them. Objects belonging to type-compatible classes (for example siblings in an inheritance hierarchy) will have dispatch tables with the same layout: the address of a given method will appear at the same offset for all type-compatible classes. Thus, fetching the method's address from a given dispatch table offset will get the method corresponding to the object's actual class.[1]

The C++ standards do not mandate exactly how dynamic dispatch must be implemented, but compilers generally use minor variations on the same basic model.

Typically, the compiler creates a separate vtable for each class. When an object is created, a pointer to this vtable, called the virtual table pointer, vpointer or VPTR, is added as a hidden member of this object (becoming its first member unless it's made the last[2]). The compiler also generates "hidden" code in the constructor of each class to initialize the vpointers of its objects to the address of the corresponding vtable. Note that the location of the vpointer in the object instance is not standard among all compilers, and relying on the position may result in unportable code. For example, g++ previously placed the vpointer at the end of the object.[3]

  1. Ellis & Stroustrup 1990, pp. 227–232
  2. Heading "Multiple Inheritance"
  3. CodeSourcery C++ ABI


回答2:

Vftable is not explicitly mentioned in the C++ standard, but most (if not all) implementations use it for virtual function implementation.

For each class with virtual functions the compiler creates an array of function poiners which are the pointers to the last overriden version of the virtual functions of that class. Then each object has a pointer to the vtable of its dynamic class.

See this question and its accepted answer for more illustrations

Virtual dispatch implementation details