考虑这样一个类b,依次包含一个虚指针、char、类a、int、double数组
struct a {
char c;//1+7
double d;//8
};//16
struct b {
char c;
a s;
int i;
double d[3];
virtual ~b() {}
};
按照道理来讲,虚指针vptr占用4字节,然后char c 占用1个字节,再补3个字节,使得a类的开始偏移量是a类最大成员double d的整数倍,然后a s占用16字节,int i占用4个字节,再补4个字节,使得double d[3]开始的位置是8的整数倍,最会double d[3]占用24个字节,最终就是4+(1+3)+16+(4+4)+(8*3)=56个字节,但是实际上是64个字节。
为什么呢?打开类b的一个对象的内存分配看看:
int main() {
b test;
test.c = ' ';
test.i = 1;
test.s.c = ' ';
test.s.d = 4;
test.d[0] = (test.d)[1] = (test.d)[2] = 2;
b *T= &test;
cout << sizeof b << endl;
}