How does std::array initializer work for char's?
Class std::array
is an aggregate. In this statement:
std::array<char, strlen("hello world!") + 1> s = {"hello world!"};
list initialization is used. As the first and only element of this instantiation of the class std::array
is a character array it may be initialized with string literals.
It would be more correctly to use sizeof
operator instead of function strlen
:
std::array<char, sizeof( "hello world!" )> s = {"hello world!"};
Also you could write
std::array<char, sizeof( "hello world!" )> s = { { "hello world!" } };
because the character array in turn is an aggregate.
According to the C++ Standard
8.5.2 Character arrays [dcl.init.string]
1 An array of narrow character type (3.9.1),
char16_t
array,char32_t
array, orwchar_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.14.5). Successive characters of the value of the string literal initialize the elements of the array.[ Example:
char msg[] = "Syntax error on line %s\n";