一、C语言中内存对齐的关键点
(1)#pragma 和 attribute((packed)) __attribute((aligned(n)))
二、C++中内存对齐的两个关键字
(1)alignof
(2)alignas
三、内存对齐实战
#include <iostream>
using namespace std;
struct s1
{
char a;
int b;
double c;
};
struct s2
{
char a;
int b;
int c;
};
//指定2字节对齐
#pragma pack(2)
struct s2
{
char a;
int b;
int c;
};
#pragma pack()
//指定8字节对齐
struct alignas(8) s3
{
char a;
int b;
int c;
};
int main(void)
{
// cout << "alignof == " << alignof(char) << endl;
// cout << "sizeof == " << sizeof(char) << endl;
// cout << "alignof == " << alignof(s1) << endl;
// cout << "sizeof == " << sizeof(s1) << endl;
// cout << "alignof == " << alignof(s2) << endl; //alignof功能是打印对齐方式,sizeof打印目标所占用的内存
cout << "sizeof == " << sizeof(s2) << endl;
getchar();
return 0;
}
四、什么情况下需要认为修改内存
(1).往大对齐是因为有时候一些硬件有一些特殊的需求,如MMU,cache等,方法alignas()
(2)往下对齐是因为有时候需要节约内测资源。方法#pragma pack()