C++ 数组初始值设定项

C++ array initializer

在 C++ 14 标准 draft 中,有两个关于数组初始化的提及(我发现):

  1. 第 8.5.1 节([dcl.init.aggr])第 2 段:

"When an aggregate is initialized by an initializer list [...]"

  1. 第 8.5.2 节([dcl.init.string])第 1 段:

"An array of narrow character type (3.9.1), char16_t array, char32_t array, or wchar_t array can be initialized by a narrow string literal, char16_t string literal, char32_t string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces (2.13.5). [...]"

因此至少有两种类型的初始化器可用于数组:初始化器列表和字符串文字。

标准是否明确提到这些是 两个选项?

Paragraph 17 of [dcl.init] 指定数组的所有可能的初始值设定项。

17 The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. If the initializer is not a single (possibly parenthesized) expression, the source type is not defined.

(17.1) If the initializer is a (non-parenthesized) braced-init-list or is = braced-init-list, the object or reference is list-initialized.

(17.2) If the destination type is a reference type, see [dcl.init.ref].

(17.3) If the destination type is an array of characters, an array of char16_­t, an array of char32_­t, or an array of wchar_­t, and the initializer is a string literal, see [dcl.init.string].

(17.4) If the initializer is (), the object is value-initialized.

(17.5) Otherwise, if the destination type is an array, the program is ill-formed.

(17.2)不适用于数组,所以选项为:

  1. 默认初始化([dcl.init]/12):int x[3];
  2. 值初始化([dcl.init]/17.4):int* x = new int[3]();
  3. 列表初始化([dcl.init]/17.1):int x[] = {1, 2, 3};int x[] {1, 2, 3};
  4. 用字符串文字初始化 ([dcl.init]/17.3):char x[] = "text";