与包含的类型相比,C++ 中的数组如何对齐? [英] How is an array aligned in C++ compared to a type contained?

查看:38
本文介绍了与包含的类型相比,C++ 中的数组如何对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有某种类型的 T 必须是 N 字节对齐.现在我声明一个 T 类型的数组:

Suppose I have some type T that has to be N bytes aligned. Now I declare an array of type T:

T array[size];

数组是否具有与 T 类型相同的对齐要求,或者它是否有任何其他对齐要求?

Will the array have the same alignment requirements as type T or will it have any other alignment requirements?

推荐答案

是的,对齐要求必须相同.显然,T 的数组必须至少像单个 T 一样严格对齐,否则其第一个成员将无法正确对齐.数组不能比其元素类型更严格地对齐的事实来自标准第 8.3.4 节,该节说数组是连续分配的元素子对象.考虑这个数组数组:

Yes, the alignment requirements must be the same. Obviously an array of T must be aligned at least as strictly as a single T otherwise its first member would not be properly aligned. The fact that an array cannot be more strictly aligned than its element type follows from the standard section 8.3.4 which says that arrays are contiguously allocated element subobjects. Consider this array of arrays:

T a[2][size];

无论size 的值是多少,a[0]a[1] 这两个数组之间都不能有额外"的填充> 否则这违反了连续分配要求.

Whatever the value of size, there can be no "extra" padding between the two arrays a[0] and a[1] otherwise this violates the contiguosly allocated requirement.

等价地,我们知道 (char*)&a[1] == (char*)&a[0] + sizeof(a[0])sizeof(a[0]) == sizeof(T[size]) == size * sizeof(T).由于这适用于任何 size,因此必须可以将 T 数组放置在任何地址处,该数组适合单个 T 对象(给定足够的地址空间).

Equivalently, we know that (char*)&a[1] == (char*)&a[0] + sizeof(a[0]) and sizeof(a[0]) == sizeof(T[size]) == size * sizeof(T). As this holds for any size it must be possible to place an array of T at any address which is suitably aligned for a single T object (given adequate address space).

这篇关于与包含的类型相比,C++ 中的数组如何对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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