Virtual Table是如何实现的呢?
1. single inherit的简单情况
A virtual table is a static look up array that the compiler sets up at compile time.
A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.
Second, the compiler also adds a hidden pointer to the classes that have virtual functions or inherit from a base having virtual functions
Ref:
Virtual table (http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/ )
2. multiple inherit/virtual inherit的复杂情况
In gcc some more vptr are added to implementing upcast/downcast, which point to offset value in Virtual table. Refer to:
Memory Layout for Multiple and Virtual Inheritance (gcc http://www.phpcompiler.org/articles/virtualinheritance.html )
In Visual C++, virtual inherit will add a vbptr (virtual base table pointer) to each derived classes. Refer to:
C++: Under the Hood by Jan Gray; it talks about class layout techniques and the virtual function call mechanism.
(http://www.openrce.org/articles/files/jangrayhood.pdf )
C++: Under the Hood是英文的;有一个中文的站点,详细讲解了包括virtual inherit在内的各种情况的object的layout,很不错!见http://www.cnblogs.com/Binhua-Liu/archive/2010/06/16/1759019.html
本文介绍了虚拟表(Virtual Table)的概念及其实现原理。对于单一继承的情况,编译器会在编译时为每个拥有虚函数的类设置静态查找表,即虚拟表。该表中包含指向最派生函数的指针。而对于多重继承或多级继承的情况,则会通过增加额外的指针来支持上转型和下转型,如GCC编译器中增加了指向偏移值的指针,而Visual C++则引入了vbptr(虚拟基类表指针)。
890

被折叠的 条评论
为什么被折叠?



