将创建多少个vptrs? [英] How many vptrs will be created?

查看:90
本文介绍了将创建多少个vptrs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上课



I have class

class abc
{

public: int a;
       virtual void fun1();
};

class b: public abc
{
  public: int b;
          virtual void fun2();
};

int main()
{
   abc obj1,obj2,obj3;
   return 0;
}



这里我为类abc创建了3个对象,所以这里将创建多少个vptrs?


here i created 3 objects for class abc, so here how many vptrs will be created?

推荐答案

Id取决于你如何计算它们。如果你指的是虚函数表的指针,重要的是要理解:每个类需要一个指针(下面我没有提到多重继承),但你必须在实例必须使用虚拟的地方有一个这样的指针的副本table,调用虚函数,使用后期绑定机制将调用分派给正确的实现。



但是唯一指针值的数量不超过类的数量。还要记住,你可以拥有许多没有vtable的课程。



另一方面,除非你不使用多重继承,否则这是真的(不是你的情况)虽然如此)



有些事情(很多人都不太了解)是当你输入某些类实例的某些运行时类型编译时类型,在一般情况下,指针被移位,存在多重继承。发生这种情况是因为,在C ++中,vtables的片段组合为继承的结果。对于单继承,新方法只是附加到表中,但是具有多重继承,您必须将来自不相关源的vtable放在一起。这只是一个理解它的暗示。



-SA
Id depends how you count them. If you mean pointers to the virtual function table, it's important to understand: you need one pointer per class (without multiple inheritance I'll mention below), but you have to have a copy of such pointer everywhere the instance has to use the virtual table, which is needed to call virtual functions, to dispatch the call to right implementation, using the late binding mechanism.

But the number of unique pointer values is no more than the number of classes. Remember also that you can have many classes not having vtable at all.

From the other hand, this is true unless you don't use multiple inheritance (not your case though).

One thing (poorly understood by many) is that when you type cast some runtime type of some class instance to some different compile-time type, the pointer is shifted, in general case, in presence of multiple inheritance. This happens because, in C++, the fragments of vtables combine as the result of inheritance. For single inheritance, new methods are just appended to the table, but with multiple inheritance, you have to put together vtables from unrelated sources. This is just a hint to understanding it.

—SA


我的赌注是没有 - 当没有可观察的程序输出时,为什么编译器会生成任何代码?
My bet is none - why would the compiler generate any code when there's no observable output of the program?


这篇关于将创建多少个vptrs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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