为什么将vptr作为第一个条目存储在具有虚函数的类的内存中? [英] Why is vptr stored as the first entry in the memory of a class with virtual functions?

查看:90
本文介绍了为什么将vptr作为第一个条目存储在具有虚函数的类的内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某些编译器,如果类具有虚函数,则可以使用其对象的第一个字节的地址访问其vptr.例如,

For some compilers, if a class has virtual functions then its vptr can be accessed with the address of the first byte of its object. For instance,

class Base{
public:
    virtual void f(){cout<<"f()"<<endl;};
    virtual void g(){cout<<"g()"<<endl;};
    virtual void h(){cout<<"h()"<<endl;};
};

int main()
{   
   Base b;

   cout<<"Address of vtbl:"<<(int *)(&b)<<endl;

   return 0;
}

我知道它取决于不同的编译器行为.由于在某些情况下vptr被存储为第一个条目,这样做的好处是什么?这是否有助于提高性能,或者仅仅是因为使用& b可以更轻松地访问vbtl?

I know that it is dependent on different compiler behaviors. Since there is the case where vptr is stored as the very first entry, what is the advantage of doing this? Does that help improve performance or simply because it's easier to access vbtl using &b?

推荐答案

这是一个实现细节,但实际上很多实现都可以做到这一点.

It's an implementation detail but indeed many implementations do this.

这是相当有效和方便的.假设您需要为给定对象调用虚函数.您有一个指向该对象和虚拟函数索引的指针.您需要以某种方式找到应该针对该对象使用该索引调用的函数.好的,您只需访问指针后面的前sizeof(void*)个字节并找到vtable所在的位置,然后访问vtable的必要元素以获取函数地址.

It's rather efficient and convenient. Suppose you need to call a virtual function for a given object. You have a pointer to that object and the virtual function index. You need to somehow find which function should be called with that index and for this object. Okay, you simply access the first sizeof(void*) bytes behind the pointer and find where the vtable resides, then access the necessary element of vtable to fetch the function address.

您可以为每个对象的vtable"或其他内容存储一个单独的映射,但是如果您决定要将vptr存储在对象内,则使用前一个字节,而不是最后一个字节或任何其他位置是合理的因为通过这种方法,一旦有了指向对象的指针,您便知道在哪里可以找到vptr,而无需额外的数据.

You could store a separate map of "vtable for each object" or something but if you decide that you want to store the vptr inside the object then it's only logical to use the first bytes, not the last bytes or any other place because with this approach you know where to find the vptr once you have a pointer to the object, no extra data required.

这篇关于为什么将vptr作为第一个条目存储在具有虚函数的类的内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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