有没有在C ++ 11零大小的std ::阵列的一个原因? [英] Is there a reason for zero sized std::array in C++11?
问题描述
考虑下面的一块code,这是一个由C ++编译器11完全可以接受的:
Consider the following piece of code, which is perfectly acceptable by a C++11 compiler:
#include <array>
#include <iostream>
auto main() -> int {
std::array<double, 0> A;
for(auto i : A) std::cout << i << std::endl;
return 0;
}
根据标准§23.3.2.8 [零大小的数组的]:
1
阵应为特殊情况下支持ñ== 0
。
1
Array shall provide support for the special caseN == 0
.
2
在的情况下,N == 0
,开始()==结束()==独特
值。结果的返回值
数据()
是unspeci网络版。
2
In the case that N == 0
, begin() == end() == unique
value. The return value of
data()
is unspecified.
3
电子FF调用的等前()
或回()
的零大小的数组是理解过程网络定义。
3
The effect of calling front()
or back()
for a zero-sized array is undefined.
4
成员函数掉期()
应具有noexcept-Fi无线特定阳离子相当于
noexcept(真)
。
4
Member function swap()
shall have a noexcept-specification which is equivalent to
noexcept(true)
.
正如上面显示的,零大小的的std ::阵列
是在C ++ 11完全允许的,符合零大小的数组(例如, INT A [0];
),在那里它们被明确禁止的,但它们是由未定义行为的成本一些编译器(如GCC)允许的。
As displayed above, zero sized std::array
s are perfectly allowable in C++11, in contrast with zero sized arrays (e.g., int A[0];
) where they are explicitly forbidden, yet they are allowed by some compilers (e.g., GCC) in the cost of undefined behaviour.
考虑到这种矛盾,我有以下问题:
Considering this "contradiction", I have the following questions:
-
为什么C ++委员会决定允许零大小的
的std ::阵列
S'
是否有任何有价值的用途?
Are there any valuable uses?
推荐答案
如果你有一个泛型函数它是坏如果函数随机打破了特殊参数。例如,假设你可以有一个模板函数,它 N
随机元素组成的向量:
If you have a generic function it is bad if that function randomly breaks for special parameters. For example, lets say you could have a template function that takes N
random elements form a vector:
template<typename T, size_t N>
std::array<T, N> choose(const std::vector<T> &v) {
...
}
没有的,所以如果这会导致不确定的行为或编译器错误,如果 N
由于某种原因,原来是零。
Nothing is gained if this causes undefined behavior or compiler errors if N
for some reason turns out to be zero.
对于原始数组的限制背后的原因是,你不想类型的 sizeof的牛逼== 0
,这将导致与指针运算组合奇怪的效果。零元素的数组将有大小为零,如果您不添加任何特殊规则吧。
For raw arrays a reason behind the restriction is that you don't want types with sizeof T == 0
, this leads to strange effects in combination with pointer arithmetic. An array with zero elements would have size zero, if you don't add any special rules for it.
但的std ::阵列&LT;&GT;
是类和类总是有大小&GT; 0.所以,你不会遇到这些问题的std ::阵列&LT;&GT;
,没有模板参数的任意限制了一致的接口为preferable
But std::array<>
is a class, and classes always have size > 0. So you don't run into those problems with std::array<>
, and a consistent interface without an arbitrary restriction of the template parameter is preferable.
这篇关于有没有在C ++ 11零大小的std ::阵列的一个原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!