我使用上面的代码打印出了基类和派生类的大小.我正在64位计算机上运行代码.我计算机的输出是
I used the above code to print out the size of the base class and derived class. I am running the code in a 64 bit machine. The output from my computer is
150 150 size: Base1:16 size: Derived:16我还尝试使用sizeof(int)打印出int的大小,它是4.
I also tried to print out the size of int by using sizeof(int), it's 4.
我有以下问题:
推荐答案
对于Base1类的大小,它应包含指向vtable的vptr和一个整数data1.为什么在我的机器上,它的大小为16而sizeof(int)为4.
For the size of Base1 class, it should contain a vptr points to the vtable and an integer data1. Why its size is 16 while sizeof(int) is 4 in my machine.
填充,以确保Base1处于必需连续的数组中时,正确对齐8字节指针.
Padding to ensure proper alignment of the 8-byte pointers when Base1s are in a necessarily-contiguous† array.
†C ++标准要求数组元素在内存中是连续的,并计算索引为 i 的元素的内存地址,并将数组的基地址加 i 乘以元素大小
† the C++ Standard requires that array elements be contiguous in memory, and calculates the memory address of an element at index i and the array's base address plus i times the element size
对于派生类,它应该具有从Base1类继承的数据和一个附加整数.它应该比Base1类更大,为什么它们相同?
For the derived class, it should have the data inherited from Base1 class and an additional integer. It should have bigger size than Base1 class, why they are the same?
已为额外的int成员回收了填充.您可以通过输出d,&d->data1,&d->derivedData来观察此情况.
The padding's been reclaimed for the extra int member. You can observe this by outputting d, &d->data1, &d->derivedData.
除了这些的大小,派生类中的vptr是什么?派生类中的vptr是否会覆盖从Base1类继承的vptr?
Besides the size of these, what's the vptr in Derived class? Will the vptr in Derived class override the vptr inherited from the Base1 class?
在使用指向虚拟调度表的指针的实现(我知道的每个编译器,但C ++标准均未强制使用),Derived类的构造函数和析构函数将覆盖"vptr"-前者编写了指针到构造函数主体在Derived的VDT 之后运行,后者在构造函数主体运行之前将Base VDT 的指针还原到在对象的正式生存期之前或之后调用对象的Derived成员函数.
In implementations using pointers to virtual dispatch tables (every compiler I know of, but it's not mandated by the C++ Standard), the Derived class constructor(s) and destructor overwrites the "vptr" - the former writing a pointer to Derived's VDT after the constructor body runs, the latter restoring the pointer to the Base VDT before the destructor body runs (this ensures you don't invoke Derived member functions on an object before or after its official lifetime).
更多推荐
C ++中基类对象和派生类对象的大小
发布评论