【问题标题】:Can someone please explain the results returned by 'sizeof' in this code有人可以解释这段代码中“sizeof”返回的结果吗
【发布时间】:2018-06-03 08:26:05
【问题描述】:

我不理解下面显示的输出。

我知道,只要存在虚函数,它就会创建一个 vptr,但打印的大小仍然超出我的预期:

#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
[0.3s完成]

【问题讨论】:

标签: c++ padding packing


【解决方案1】:

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

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

由于Derived 仅派生自Base 并且没有添加任何成员变量,所以它的大小是相同的。

为什么要添加填充?在数组和堆栈中保持 8 字节对齐。为什么这很重要?那是different question

【讨论】:

  • 为什么不呢?应该是什么?
  • @Yksisarvinen 动议打击“典型”:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 2015-09-14
  • 1970-01-01
  • 2018-12-17
  • 2011-08-20
  • 1970-01-01
相关资源
最近更新 更多