为什么结构的大小需要是任何结构成员的最大比对的倍数 [英] why does size of the struct need to be a multiple of the largest alignment of any struct member

查看:54
本文介绍了为什么结构的大小需要是任何结构成员的最大比对的倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解在结构的成员之间发生的填充,以确保各个类型的正确对齐.但是,为什么数据结构必须是最大成员对齐的倍数?我不知道最后是否需要填充.

I understand the padding that takes place between the members of a struct to ensure correct alignment of individual types. However, why does the data structure have to be a multiple of alignment of largest member? I don't understand the padding is needed at the end.

参考: http://en.wikipedia.org/wiki/Data_structure_alignment

推荐答案

好问题.考虑这种假设类型:

Good question. Consider this hypothetical type:

struct A {
    int n;
    bool flag;
};

因此,类型为A的对象应占用5个字节(int用于4个字节,bool用于1个字节),但实际上它需要8个字节.为什么?

So, an object of type A should take five bytes (four for the int plus one for the bool), but in fact it takes eight. Why?

如果使用以下类型,则会看到答案:

The answer is seen if you use the type like this:

const size_t N = 100;
A a[N];

如果每个A只有五个字节,则a[0]将对齐,但a[1]a[2]和大多数其他元素将对齐.

If each A were only five bytes, then a[0] would align but a[1], a[2] and most of the other elements would not.

但是为什么对齐甚至很重要?原因有很多,所有原因都与硬件有关.原因之一是最近/经常使用的内存被缓存在CPU芯片上的缓存行中,以便快速访问.小于缓存行的对齐对象始终适合一行(但请参见下面的有趣注释),但是未对齐的对象可能跨越两行,从而浪费了缓存.

But why does alignment even matter? There are several reasons, all hardware-related. One reason is that recently/frequently used memory is cached in cache lines on the CPU silicon for rapid access. An aligned object smaller than a cache line always fits in a single line (but see the interesting comments appended below), but an unaligned object may straddle two lines, wasting cache.

实际上,还有更多的基本硬件原因,这与字节寻址数据在32位或64位数据总线上向下传输的方式有关,与高速缓存行完全不同.失准不仅会阻塞总线,导致额外的获取(如前所述),而且还会迫使寄存器在输入字节时对其进行移位.更糟糕的是,失准会混淆优化逻辑(至少,英特尔的优化手册指出)的确如此,尽管我对这最后一点一点都不了解).因此,从性能的角度来看,未对准是非常严重的.

There are actually even more fundamental hardware reasons, having to do with the way byte-addressable data is transferred down a 32- or 64-bit data bus, quite apart from cache lines. Not only will misalignment clog the bus with extra fetches (due as before to straddling), but it will also force registers to shift bytes as they come in. Even worse, misalignment tends to confuse optimization logic (at least, Intel's optimization manual says that it does, though I have no personal knowledge of this last point). So, misalignment is very bad from a performance standpoint.

出于这些原因,通常值得浪费填充字节.

It usually is worth it to waste the padding bytes for these reasons.

更新:下面的注释都很有用.我推荐他们.

Update: The comments below are all useful. I recommend them.

这篇关于为什么结构的大小需要是任何结构成员的最大比对的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆