using intArray = int[];
int (&a) [4] = intArray{1, 2, 3, 4};
This is not allowed since it's illegal to bind a non-const lvalue reference to a temporary (rvalue). Both g++ 4.9.1 and clang 3.4.2 barks back with errors; it compiles fine when a
is const
qualified
int const (&a) [4] = intArray{1, 2, 3, 4};
However, when I do this
int &x = intArray{1, 2, 3, 4} [1];
both compilers compile it fine without an error. Digging the standard (draft N3337) for this, §5.2.1 Subscripting
says
1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type. The result is an lvalue of type “T.” The type “T” shall be a completely-defined object type. The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2 A braced-init-list shall not be used with the built-in subscript operator.
If I go with 1 then I don't see why the standard allows temporary arrays to be constructed since subscripting an element in it would give out an lvalue i.e. I can get a lvalue from a temporary which contradicts the original notion of temporaries can only be bound to const lvalue references or rvalue references.
If I go with 2 then why do the compilers not throw an error when I'm doing
{1, 2, 3, 4}[1]
?