Size of class with virtual function adds extra 4 bytes(具有虚函数的类的大小增加了额外的 4 个字节)
问题描述
class NoVirtual {
int a;
public:
void x() const {}
int i() const { return 1; }
};
class OneVirtual {
int a;
public:
virtual void x() const {}
int i() const { return 1; }
};
class TwoVirtuals {
int a;
public:
virtual void x() const {}
virtual int i() const { return 1; }
};
int main() {
cout << "int: " << sizeof(int) << endl;
cout << "NoVirtual: "
<< sizeof(NoVirtual) << endl;
cout << "void* : " << sizeof(void*) << endl;
cout << "OneVirtual: "
<< sizeof(OneVirtual) << endl;
cout << "TwoVirtuals: "
<< sizeof(TwoVirtuals) << endl;
return 0;
}
输出为:
非虚拟:4
无效*:8
OneVirtual:16
两个虚拟:16
NoVirtual: 4
void* : 8
OneVirtual: 16
TwoVirtuals: 16
问题是:
由于 OneVirtual 和 TwoVirtuals 类具有虚函数,类的大小应为 sizeof(int) + sizeof(void*) 即 12 字节.但大小打印为 16 字节.
Since OneVirtual and TwoVirtuals class have virtual function, size of class should be sizeof(int) + sizeof(void*) i.e. 12bytes. But size is printed as 16bytes.
谁能解释一下原因?
推荐答案
我假设你是在 64 位机器上编译,因为 int 的大小是 4 字节.对于 64 位机器,指针大小通常是 8 字节,int 大小是 4 字节.满足 数据对齐要求 以节省读取周期编译器添加了额外的 4 个字节(填充),因此结果是 16 个字节,而实际需要的大小是 12 个字节.
I assume you are compiling on 64bit machines since size of int is 4bytes.Typically for 64bit machines pointer size will be 8 bytes and int size is 4 bytes.To satisfy Data Alignment requirement to save read cycles compiler adds extra 4 bytes(padding) hence result is 16bytes where as actual required size is 12 bytes.
这篇关于具有虚函数的类的大小增加了额外的 4 个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有虚函数的类的大小增加了额外的 4 个字节
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
