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 个字节


- 如何提取 __VA_ARGS__? 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- GDB 不显示函数名 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01