首页 > 解决方案 > Can someone please explain the results returned by 'sizeof' in this code

问题描述

I don't undertand the output shown below.

I know that whenever a virtual function is present it creates a vptr but still the size printed is more than I would expect:

#include<iostream>
using namespace std; 

class Base
{
 int x;
 int y;
 int z;
public:
 virtual void fun(){}
 virtual void fun2(){}
};

class Derived:public Base
{
 public:
  void fun() override {} 
};

int main(int argc, char const *argv[])
{
  cout<<sizeof(Base)<<endl;
  cout<<sizeof(Derived)<<endl;
  cout<<sizeof(int)<<endl; 
}

24
24
4
[Finished in 0.3s]

标签: c++paddingpacking

解决方案


这是 64 位版本吗?如果是这样,sizeof Base将是:

8(vtable 指针)+(3 * 4 = 12)(成员变量)+4(填充到 8 个字节的倍数)= 24

由于Derived只派生自Base成员变量且不添加成员变量,因此其大小是相同的。

为什么要添加填充?在数组和堆栈中保持 8 字节对齐。为什么这很重要?那是一个不同的问题


推荐阅读