C++ alignof和alignas

一、什么是alignof和alignas

alignas用来指定对象的对齐字节数。效果和__attribute__((aligned(n)))一样

alignof用来查看对象的对齐字节数。用法类似于sizeof

二、实验

使用alignas修改结构体的对齐字节数,然后用alignof查看是否设置成功。

同时,与__attribute__((aligned(n))) 进行对比。

#include <iostream>

using namespace std;

struct alignas(1) student1
{
	char a;
	int b;
	float c;
};

struct alignas(16) student2
{
	char a;
	int b;
	float c;
};

struct student3
{
	char a;
	int b;
	float c;
}__attribute__((aligned(1)));

struct student4
{
	char a;
	int b;
	float c;
}__attribute__((aligned(16)));


int main()
{
	cout << alignof(student1) << endl;  //alignas(1)
	cout << alignof(student2) << endl;	//alignas(16)
	cout << alignof(student3) << endl;	//__attribute__((aligned(1)))
	cout << alignof(student4) << endl;	//__attribute__((aligned(16)))
	return 0;
}

在这里插入图片描述
结论:
alignas__attribute__((aligned(n)))的作用完全一样。
但是,它们都只能放大对齐的字节数,而不能缩减。要是我想将对齐的字节数设置为1,该怎么办?


可以使用#pragma pack(n)来设置

#include <iostream>

using namespace std;

#pragma pack(1)
struct  student1
{
	char a;
	int b;
	float c;
};
#pragma pack()



int main()
{
	cout << alignof(student1) << endl;  

	return 0;
}

末尾记得加上#pragma pack(),表示设置默认的对齐方式。

三、最后

感觉alignas是对__attribute__((aligned(n)))的一种简化,让程序更加清爽。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值