英文:
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 STL在T
不可默认构造时使用一个空成员(否则,它会创建一个单元素数组)。
差异的实时演示:https://godbolt.org/z/1o167na6z
英文:
In libc++, the specialization of std::array<T,0>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论