现在的位置: 首页 > 综合 > 正文

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

2012年10月22日 ⁄ 综合 ⁄ 共 620字 ⁄ 字号 评论关闭

编译器对结构在编译过程中会优化对齐,由于编译器的内存对齐,当一个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))的作用(阻止对制定结构的优化)

抱歉!评论已关闭.