简体   繁体   English

有人可以解释这段代码中'sizeof'返回的结果吗

[英]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: 我知道,只要存在虚函数,它都会创建一个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
24 24
4 4
[Finished in 0.3s] [以0.3秒完成]

Is this a 64 bit build? 这是64位版本吗? If so, sizeof Base would be: 如果是这样,则sizeof Base将是:

8 (vtable pointer) + (3 * 4 = 12) (member variables) + 4 (pad to multiple of 8 bytes) = 24 8(vtable指针)+(3 * 4 = 12)(成员变量)+ 4(填充至8字节的倍数)= 24

Since Derived derives only from Base and adds no member variables, its size is the same. 由于“ Derived仅从Base Derived而未添加任何成员变量,因此其大小相同。

Why is padding added? 为什么要添加填充? To maintain 8-byte alignment in arrays and on the stack. 在数组中和堆栈上保持8字节对齐。 Why is that important? 为什么这么重要? That's a different question . 这是一个不同的问题

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

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