c++ - 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]
解决方案
这是 64 位版本吗?如果是这样,sizeof Base
将是:
8(vtable 指针)+(3 * 4 = 12)(成员变量)+4(填充到 8 个字节的倍数)= 24
由于Derived
只派生自Base
成员变量且不添加成员变量,因此其大小是相同的。
为什么要添加填充?在数组和堆栈中保持 8 字节对齐。为什么这很重要?那是一个不同的问题。
推荐阅读
- r - 有没有办法将 if 语句与过滤功能结合起来?
- html - 背景:url(),背景图像:url()不起作用
- python - 从另一个 .py 文件方法停止 apscheduler 作业
- sqlite - 仅当将函数应用于字段时才能从 sql 查询中获取结果。它是 Poco::Data 的错误吗?
- javascript - Javascript:停止使用 clearInterval 时的 setInterval Timer 无法再次重新启动
- hyperledger-fabric - 访问和更新资源的关系字段
- android - 小时之间是小时范围吗?
- python - 如何始终在一行中打印更新的变量
- php - 从 mysql _query 转换为 mysqli_query
- python - 如何使用“CSV,阅读器”获取文件中的数据?