std::array 在 libc++ 中的大小和对齐方式是根据类型 T 来确定的。

huangapple go评论137阅读模式
英文:

Why is std::array<T,0> sized and aligned according to T in libc++?

问题

In libc++, std::array<T,0>的特化版本具有一个成员(const) char 数组,该数组根据T进行对齐和大小调整(source)。我想知道这个实现的原因,因为这个成员(__elems_)似乎没有在任何地方被使用。相比之下,libstdc++使用一个空成员,而Microsoft STLT不可默认构造时使用一个空成员(否则,它会创建一个单元素数组)。

差异的实时演示:https://godbolt.org/z/1o167na6z

英文:

In libc++, the specialization of std::array&lt;T,0&gt; has a member (const) char array, which is aligned and sized according to T (source). I wonder what is the reason for this implementation since this member (__elems_) does not seem to be used anywhere. For comparison, libstdc++ uses an empty member, and Microsoft STL uses an empty member if T is not default-constructible (otherwise, it creates a single-element array).

Live demo of the difference: https://godbolt.org/z/1o167na6z

答案1

得分: 10

std::array 允许具有零大小,但底层的 C 数组不能为零大小。因此,实现将需要一些特殊情况来处理这种情况。

标准未规定此实现必须是什么,或者对行为施加了很多限制,调用 front()back() 是未定义行为。有一个约束是 array.begin() == array.end()。由于没有太多约束,您可以预期不同的实现将使用不同的解决方法。

Libc++ 最初使用了一个单元素数组,但这对于非默认可构造类型不起作用。为了保持 ABI 兼容性,这个实现被替换为相同大小的 char 数组

英文:

std::array is allowed to have a zero size but the underlying c arrays can't be zero-sized. Therefore the implementations will need some special case to handle this.

The standard doesn't specify what this implementation must be or really place many constraints on the behaviour, calling front() or back() is undefined behaviour. There is one constraint that array.begin() == array.end(). As there are not many constraints you'd expect different implementations to use different workarounds for it.

Libc++ originally used a single element array but this doesn't work with non-default constructible types. In order to maintain ABI compatibility this was replaced with a char array of the same size.

huangapple
  • 本文由 发表于 2023年5月11日 16:27:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定