vtable和虚拟指针 [英] vtable and virtual pointer

查看:51
本文介绍了vtable和虚拟指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我想了解vtable&vptr实现的内部原理,我有一些疑问.如果有人可以详细了解所有这些内容.

1:何时创建vtable和vptr?是编译时还是运行时?
2:如何打印vptr的地址和vptr的包含内容,即vtable的地址?是否可以打印这些地址.如果没有,那为什么呢?

等待快速回复.............

Hi All,

I am trying to understand the internals of vtable & vptr implementation and I have some question. If anybody can explore in details about all these.

1: When does vtable and vptr getting created? Is it compile time or at Run time?
2: how can we print the address of vptr and containt of vptr, i.e. the address of vtable? Is it possible to print these addresses. if no then why?

Waiting for quick reply .............

推荐答案

1)根据最初的原则,虚拟表始终在编译期间创建-时间.里面没有动态.它的函数调用调度是动态的,在运行时发生-多亏了虚拟表.

2)访问虚拟表指针不是一个简单的问题.首先要了解的是:在所有OOP语言中,根据用于访问对象的编译类型,可以有多个指向虚拟表的指针.通常这是相同的指针:派生类仅累加到基类的虚拟表中.由于动态强制转换,您总是会得到相同的指针.在C ++中,情况并非完全如此.如果这种情况由于多重继承而变得非常复杂.显然,不同的基类需要指向虚拟表的不同指针.在典型的实现中,它仍然是相同的虚拟表,仅从不同的角度"进行访问.我怀疑物理布局在不同的实现中非常相似,但是它们不必相同.严格来说,布局是依赖于实现的,因为Kurt正确地指出了这一点.

—SA
1) By the very first principles, virtual table is always created during compile-time. There is nothing dynamic in it. It''s function call dispatching is dynamic, happens during run-time — thanks to virtual table.

2) Accessing the virtual table pointer is not a trivial problem. First thing to understand is: in all OOP languages, there can be several different pointers pointing to virtual table, depending on compile type used for access to the object. Usually this is the same pointer: derived classes only adds up to the virtual table of the base class. You always get the same pointer as a result of dynamic cast. This is not exactly so in C++; this situation if highly complicated by multiple inheritance. Apparently different base classes needs different pointers to the virtual table. In a typical implementation, it is still the same virtual table, only accessed "from different points of view". I suspect the physical layout are very similar in different implementation, but they don''t have to be the same. Strictly speaking, the layout is implementation-dependent, as Kurt pointer our correctly.

—SA


免责声明:本主题非常针对编译器


vtable是静态成员,因此它是在编译时创建的(每个类1个),此逻辑也适用于vptrs

访问vtable有点棘手(并且非常依赖于编译器),但是可以做到:

看一下这段代码(仅适用于VC ++)

DISCLAIMER: this topic is very compiler specific


the vtable is a static member as such it created at compile time(1 per class) this logic applies to the vptrs as well

accessing the vtable is a bit tricky (and very compiler dependent) but it can be done:

Take a look at this code (for VC++ only)

aobj *temp = new aobj(); //NOTE MUST CONTAIN NON PURE VIRTUAL FUNCTION

int* vptr =  *(int**)temp; //get the  vptr

//assmebly code to make "temp" as the "this" ptr
__asm
{
  mov ecx, temp
}

 ((void (*)()) vptr[0] )(); //this will call the first function in vtable


这篇关于vtable和虚拟指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆