如何数组用C ++对准相比包含一个类型? [英] How is an array aligned in C++ compared to a type contained?

查看:129
本文介绍了如何数组用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];

无论尺寸,可以有两个阵列之间没有任何额外的填充值 A [0] A [1] ,否则这违反了 contiguosly分配的要求。

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.

等价的,我们知道,(字符*)及一个[1] ==(字符*)及一个[0] +的sizeof(A [0])的sizeof(A [0])==的sizeof(T [尺寸])==尺寸*的sizeof(T)。由于这适用于任何尺寸它必须能够放置 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天全站免登陆