且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么std :: aligned_union需要最小大小作为模板参数?

更新时间:2023-11-30 22:12:10

相关文章似乎是 N2140 。原因是,你可以过度对齐类型。给出的例子是,你可以做一个页面对齐的数据结构。

The relevant paper appears to be N2140. The reason fundamentally is that you can over-align types. The example given is that you can make a page-aligned data structure.

(我第一次有aligned_storage和aligned_union混淆,对不起)。

(I first had aligned_storage and aligned_union mixed up, sorry).

Aligned_storage在N2140中被描述为aligned_union的可能基类。 N2140还将< code> aligned_storage< N,...> 的点的实现描述为(但不要求)作为对齐的 N] 。显然你需要N。

Aligned_storage is described in N2140 as the likely base class of aligned_union. N2140 also describes (but does not mandate) the implementation of point of aligned_storage<N, ...> as a warpper of an aligned char[N]. Obviously you need N for that.

因为它是一个不重要的平凡类型;)

Because it's a non-trivial trivial type ;)

std :: aligned_union 是至少具有给定大小的POD类型,并且根据指定的类型对齐。这些类型不需要是POD类型,从中显而易见,它们不能是成员。

std::aligned_union is a POD type with at least the given size, and alignment per the types specified. Those types need not be POD types, from which it becomes obvious that they can't be members.

但是,您可以做的是使用placement new将 T [n] align_union对齐 T ,其大小至少为 sizeof(T [n])

What you can do, however, is use placement new to put a T[n] in that storage provided that the aligned_union is aligned for T and its size is at least sizeof(T[n])