今天上班时,在与同事讨论数据字节对齐时,在谈到如果结构体中单独包含一个bool类型的成员时,这个结构体的大小是多少?那时第一直觉就是,虽然bool类型的大小是1个字节,但编译器默认按4个字节对,所以单独包含一个bool类型,结构体大小应该是4个字节。后来同事亲手试验了一下,想不到竟然是1个字节大小。
因些自己就亲手写个几个结构体进行试验,以下是在VS2003进行默认编译的,列举如下:
1.
struct TEST
{
bool bMember1;
}
结果: sizeof(TEST) = 1;
2.
struct TEST
{
bool bMember1;
int nMember2;
}
结果: sizeof(TEST) = 8;
3.
struct TEST
{
bool bMember1;
int nMember2;
bool bMember3;
}
结果: sizeof(TEST) = 12;
4.
struct TEST
{
bool bMember1;
bool bMember3;
int nMember2;
}
结果: sizeof(TEST) = 8;
5.
struct TEST
{
int nMember2;
bool bMember1;
bool bMember3;
}
结果: sizeof(TEST) = 8;
6.
struct TEST
{
bool bMember1;
WORD wMember2;
bool bMember3;
}
结果: sizeof(TEST) = 6;
7.
struct TEST
{
WORD wMember2;
bool bMember3;
bool bMember1;
}
结果: sizeof(TEST) = 4;
8.
struct TEST
{
bool bMember3;
bool bMember1;
WORD wMember2;
}
结果: sizeof(TEST) = 4;
9.
struct TEST
{
bool bMember3;
bool bMember1;
__int64 n64Member2;
}
结果: sizeof(TEST) = 16;
10.
struct TEST
{
bool bMember3;
__int64 n64Member2;
bool bMember1;
}
结果: sizeof(TEST) = 24;
11.
struct TEST
{
__int64 n64Member2;
bool bMember1;
bool bMember3;
}
结果: sizeof(TEST) = 16;
12.
struct TEST
{
bool bMember1;
WORD wMember4;
bool bMember3;
int nMember5;
__int64 n64Member2;
}
结果: sizeof(TEST) = 24;
由上可见 结构体或者类的自身对齐值是其成员中自身对齐值最大的那个值。
本文最后附带关于字节对齐网上一篇写得不错的文章: