新的char实际上保证类型类型的对齐内存吗? [英] Does new char actually guarantee aligned memory for a class type?
问题描述
通过 new char [sizeof(T)]
分配一个缓冲区,保证分配的内存与 T
,其中 T
的所有成员都有自然的,实现定义的对齐方式(也就是说,您没有使用 alignas
关键字修改它们的对齐方式)。
我已经看到这个保证在几个答案周围,但我不完全清楚标准如何到达这种保证。标准的5.3.4-10给出了基本要求:基本上 new char []
必须与 max_align_t
对齐。
我缺少的是 alignof(T)
的位总是一个有效的对齐方式最大值 max_align_t
。我的意思是,它似乎很明显,但必须得到一个结构的对齐最多 max_align_t
?甚至点3.11-3说,可能支持扩展对齐,因此编译器自己决定一个类是否是一个过度对齐的类型?
我缺少的是 alignof(T)
的位总是一个有效的对齐方式,最大值为 max_align_t
。我的意思是,它似乎很明显,但必须得到一个结构的对齐最多 max_align_t
?甚至点3.11-3说,可以支持扩展对齐,因此编译器可以自己决定一个类是否是一个过对齐的类型?
正如Mankarse所说,我可以得到的最好的报价是 [basic.align] / 3 :
<具有扩展的对准要求的类型是过度对准类型。 [注意:
每个过对齐类型是或包含扩展对齐适用的类类型(可能通过非静态数据成员)。 -end note]
这似乎暗示扩展比对必须明确需要(然后传播),但不能
我宁愿更清楚地提及;对于编译器编写器来说意图是显而易见的,任何其他行为将是疯狂的,仍然...
Is allocating a buffer via new char[sizeof(T)]
guaranteed to allocate memory which is properly aligned for the type T
, where all members of T
has their natural, implementation defined, alignment (that is, you have not used the alignas
keyword to modify their alignment).
I have seen this guarantee made in a few answers around here but I'm not entirely clear how the standard arrives at this guarantee. 5.3.4-10 of the standard gives the basic requirement: essentially new char[]
must be aligned to max_align_t
.
What I'm missing is the bit which says alignof(T)
will always be a valid alignment with a maximum value of max_align_t
. I mean, it seems obvious, but must the resulting alignment of a structure be at most max_align_t
? Even point 3.11-3 says extended alignments may be supported, so may the compiler decide on its own a class is an over-aligned type?
What I'm missing is the bit which says
alignof(T)
will always be a valid alignment with a maximum value ofmax_align_t
. I mean, it seems obvious, but must the resulting alignment of a structure be at mostmax_align_t
? Even point 3.11-3 says extended alignments may be supported, so may the compiler decide on its own a class is an over-aligned type ?
As noted by Mankarse, the best quote I could get is from [basic.align]/3:
A type having an extended alignment requirement is an over-aligned type. [ Note: every over-aligned type is or contains a class type to which extended alignment applies (possibly through a non-static data member). —end note ]
which seems to imply that extended alignment must be explicitly required (and then propagates) but cannot
I would have prefer a clearer mention; the intent is obvious for a compiler-writer, and any other behavior would be insane, still...
这篇关于新的char实际上保证类型类型的对齐内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!