c++ 内存对齐

内存对齐的大小是多少?

按照吉良吉影所说:

此外还有编译器的默认对齐值,一般默认对齐值为4(结构体的实际对齐值会取结构体对齐值和编译器默认对齐值中较小的那一个)。

只要没设置,一般是4了。

内存对齐的规律到底是什么?

看了知乎专栏微软页面等各种文章,其实他们总结的规律都难以背诵。在我看来,变量对齐的应当遵循这一条原则:

尽量避免变量本可以放在一个word中,却被分割放到两个word里,使得读取变量时要多读一个word。

举个例子:

  • 设一个word是4字节,一个double占8字节,就应当放在两个word里面,而不应该放到三个
  • 设一个int是4字节,就应当放到1个而非分割到2个word里面。
#include <iostream>
using namespace std;

struct Pin {
	int x;
	char y;
	short z;
};

struct Foo {
	int x;
	char y;
	char z;
};

struct Bar{
	int x;
	char y;
	char z;
	char c1;
	char c2;
};


int main()
{

	cout << "Pin" << endl;
	cout << sizeof(int) << " " << sizeof(char) << " " << endl;
	cout << alignof(Pin) << " " << sizeof(Pin) << endl;

	cout << "Foo" << endl;
	cout << sizeof(int) << " " << sizeof(char) << " " << endl;
	cout << alignof(Foo) << " " << sizeof(Foo) << endl;

	cout << "Bar" << endl;
	cout << sizeof(int) << " " << sizeof(char) << " " << endl;
	cout << alignof(Bar) << " " << sizeof(Bar) << endl;
	return 0;
}

输出结果发现,三种结构体占用内存相等。因为三种结构体x成员之后的成员,比如y、z等,都不需要分割放到两个word中,可以码在一个word里
输出结果

alignof的作用? 如cppreference所说,alignof会输出对应类型的对齐字节数(是对齐方式,不是指结构大小)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值