C ++程序中的虚拟表和虚拟指针数 [英] Number of Virtual tables and Virtual Pointers in a C++ Program

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

问题描述

假设我们有以下程序:

class A
{     public:
      virtual fun(){};
};
class B:public A
{     public:
     virtual fun(){};
};
int main()
{
     A a1;
     B b1;
 }

我的问题是多少 vtables

My question is how many vtables and how many vptrs will be created, when we run this program?

推荐答案

它严重依赖于实现,但通常你会得到一个vtable对象每个类有任何虚拟函数(类没有虚拟函数或基础不需要它们),一个vptr每个对象的类一个vtable(指向类的vtable)。

Its heavily implementation dependent, but generally you'll get one vtable object per class that has any virtual functions (classes with no virtual functions or bases don't need them), and one vptr per object of a class with a vtable (pointing at the class's vtable).

如果你有多个继承和虚拟基类,情况会变得更复杂 - 这可以通过多种方式实现。一些实现使用额外的vtable每附加基类(所以你最终得到一个vtable每基类每个类),而其他人使用一个单独的vtable与额外的信息。这可能会导致每个对象需要多个vptr。

Things get more complex if you have multiple inheritance and virtual base classes -- which can be implemented many ways. Some implementations use an addition vtable per additional base class (so you end up with a vtable per base class per class), while others use a single vtable with extra info in it. This may result in needing multiple vptrs per object.

B中的 virtual 关键字是不相关的 - 如果函数在基类中是虚拟的,它将在派生类中是虚拟的。

The virtual keyword in B is irrelevant -- if the function is virtual in the base class, it will be virtual in the derived classes regardless.

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

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