简体   繁体   English

为什么添加虚拟方法会增加C ++中的类大小?

[英]Why does adding virtual method increase class size in C++?

#include <iostream>
using namespace std;

class a {
  virtual int foo() {
    return 0;
  }
};

class b {
  int foo() {
    return 0;
  }
};

int main() {
  cout << sizeof(b) << endl;
  cout << sizeof(a) << endl;
}

Output (with g++ 4.9, -O3): 输出(使用g ++ 4.9,-O3):

1
8

I assume the increase in size is due to adding a vpointer. 我认为大小的增加是由于添加了vpointer。 But I thought the compiler would see that a is not actually deriving or being derived from anything, hence there is no need to add the vpointer? 但是我认为编译器会看到a实际上不是从任何东西派生或派生的,因此不需要添加vpointer吗?

The vpointer is needed because the compiler cannot guarantee an external (eg shared) library does not use a derived type. 需要vpointer是因为编译器无法保证外部(例如,共享的)库不使用派生类型。 The existence-of-derived-class resolution happens at runtime. 派生类的解析在运行时发生。

Run-time type information. 运行时类型信息。 Any polymorphic class creates extra meta-data in the program to make things like typeof and dynamic_cast work. 任何多态类都会在程序中创建额外的元数据,以使诸如typeofdynamic_cast工作正常进行。 This is in addition to the virtual function table. 这是虚拟功能表的补充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM