编译器优化对齐(字节对齐)

编译器对结构在编译过程中会优化对齐,由于编译器的内存对齐,当一个char变量独立存在时,会分配一个int大小的空间,当两个char连续存在时,会给两个char分配一个int大小的空间.

class CMemoryTest
{
int a;
char b;
int c;
char d;
};
class CMemoryTest1
{
int a;
char b;
char d;
int c;
};
class CMemoryTest2
{
int a;
char b;
char d;
char e;
char f;
int c;
};
class CMemoryTest3
{
int a;
char b;
int c;
char d;
}__attribute__((packed));
int main()
{
cout<<"MemoryTest"<<sizeof(CMemoryTest)<<endl;
cout<<"MemoryTest1"<<sizeof(CMemoryTest1)<<endl;
cout<<"MemoryTest2"<<sizeof(CMemoryTest2)<<endl;
cout<<"MemoryTest3"<<sizeof(CMemoryTest3)<<endl;
}

结果:

MemoryTest   16
MemoryTest1 12
MemoryTest2 12

MemoryTest3 10

在这种内存对齐机制下,内存访问的粒度为int。同时也可以看到__attribute__((packed))的作用(阻止对制定结构的优化)

原文地址:https://www.cnblogs.com/dongzhiquan/p/2322394.html