虚拟功能表指针在对象中的位置 [英] location of virtual function table pointer in object

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

问题描述

据我了解,virtual函数指针表在对象中的位置取决于编译器.
将指针放在对象的开头还是结尾是否有任何利弊?反之亦然?

As I understand, the location of the virtual function pointer table in an object is compiler dependent.
Are there any pros/cons of placing this pointer at the beginning of the object vs at the end or vice-versa?

推荐答案

虚拟函数表的存在仅依赖于编译器(但是所有编译器都依赖),并且也不要求位置...在所有编译器中我知道细节,vptr存储在对象的开头.原因是它提供了统一的位置.考虑一个类层次结构:

The mere existence of a virtual function table is compiler dependent (but all compilers do), and the location is not mandated either... In all compilers of which I know the details, the vptr is stored in the beginning of the object. The reason is that it provides a uniform location. Consider a class hierarchy:

struct base {
   T data;
   virtual void f();
};
struct derived : base {
   T1 data;
   virtual void g();
};

如果vptr存储在对象的末尾,那么对于完全类型为base的对象,它会在sizeof(T)个字节之后.现在,当您拥有完整类型为derived的对象时,base子对象的布局必须与完整的base对象的布局兼容,因此vptr仍必须为sizeof(T)字节在对象内部,该对象位于derived对象的中间(从开头开始为sizeof(T),在结束之前为sizeof(T1)).因此它将不再位于对象的 end .

If the vptr was stored at the end of the object, then it would be after sizeof(T) bytes for an object of complete type base. Now when you have an object of complete type derived, the layout of the base sub object must be compatible with the layout of a complete base object, so the vptr would still have to be sizeof(T) bytes inside the object, which would be somewhere in the middle of the derived object (sizeof(T) from the beginning, sizeof(T1) before the end). So it would no longer be at the end of the object.

此外,给定一个this指针,虚拟调用需要通过vtable进行间接调用,该表基本上是取消引用vptr,添加偏移量并跳转到存储在其中的内存位置.如果vptr存储在对象的末尾,则对于每个虚拟调用,在取消引用vptr之前,都会在this中添加一个额外的内容.

Additionally, given a this pointer, a virtual call requires an indirection through the vtable, which basically is dereferencing the vptr, adding an offset and jumping to the memory location stored there. If the vptr was stored at the end of the object, for each virtual call there would be an extra addition to this before dereferencing the vptr.

这篇关于虚拟功能表指针在对象中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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