C++内存对齐

一、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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值