C++標準ライブラリの固定長配列型std::array<T, N>
では、要素数ゼロN == 0
が明示的に許容される。一方で、C++言語組込の配列型においては要素数ゼロが許容されない。*1
C++11 8.3.4/p1, 23.3.2.8より一部引用。
In a declaration
T D
whereD
has the form
D1
[
constant-expressionopt]
attribute-specifier-seqoptand the type of the identifier in the declaration
T D1
is "derived-declarator-type-listT
", then the type of the identifier ofD
is an array type; if the type of the identifier ofD
contains theauto
type-specifier, the program is ill-formed. T is called the array element type; this type shall not be a reference type, the (possibly cv-qualified) typevoid
, a function type or an abstract class type. If the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero. The constant expression specifies the bound of (number of elements in) the array. If the value of the constant expression isN
, the array hasN
elements numbered0
toN-1
, and the type of the identifier ofD
is "derived-declarator-type-list array ofN T
". (snip)
1
array
shall provide support for the special caseN == 0
.
2 In the case thatN == 0
,begin() == end() ==
unique value. The return value ofdata()
is unspecified.
3 The effect of callingfront()
orback()
for a zero-sized array in undefined.
4 Member functionswap()
shall have a noexcept-specification which is equivalent tonoexcept(true)
.
2003年当時の提案文書N1479 III. Design Decisions より引用(下線部は強調)。
Empty arrays
Consideration should be given to the case where N == 0. For traditional arrays this is an error that should be diagnosed by the compiler. It would be reasonable to retain this behaviourAn alternative offerred by the proposal is to partially specialize the template on the case N == 0, such that it has no internal state,
empty() == true
, andbegin() == end() == 0
.This solution preferred by the proposal removes a potential error from library use. This may be particularly valuable when writing generic code parameterized on N. However, it is a change of behaviour compared to the traditional C array.
関連URL