g++ bug report

Oscar Fuentes ofv@wanadoo.es
Sat Jun 9 13:23:00 GMT 2001


On 09 Jun 2001 15:34:02 -0300, Alexandre Oliva <aoliva@redhat.com>
wrote:

>On Jun  9, 2001, Oscar Fuentes <ofv@wanadoo.es> wrote:
>
>> G++ fails to compile this valid code:
>
>>   MyClass **p;
>>   *p = new (MyClass*)[10];
>
>Why do you think this is valid?  *p is indeed a MyClass*, whereas `new
>(MyClass*)[10]' will return a pointer to the first element of the
>array of MyClass*s, i.e., a MyClass**.

KAI, Borland and Comeau compiles.

Quoting James Kanze in comp.lang.c++.moderated thread "{delete p; p =
NULL; }" on 1 June 2001 09:15:28 -0400


<3B174B41.9967FB3B@dresdner-bank.com>

>The statement is legal according to the standard, But it doesn't do
>what the author probably expected.  There are two possible syntax for
>a new expression:
>
>    ::[opt] new new-placement[opt] new-type-id new-initializer[opt]
>    ::[opt] new new-placement[opt] ( type-id ) new-initializer[opt]
>
>A new-type-id cannot begin with a parentheses, so if the first is to
>be used, the contents of the (...) can only be a new-placement.  Which
>it isn't, since in a new-placement, the contents of (...) must be an
>expression-list, and "MyClass*" cannot be parsed as an expression
>list.
>
>That leaves the second.  And the second works, because "MyClass*" can
>be parsed as a type-id (see 8.1).  However, in this case, the new
>expression ends at the closing ')'; the [10] is not part of it, but
>rather a subscript operator.  The resulting expression is still legal;
>a pointer (returned by the new expression) is a legal first argument
>of a subscript operator, and an int (10) is a legal second argument.
>The expression is the equivalent of
>
>    *p = *((new MyClass*) + 10)
>
>The new expression allocates one MyClass*, and returns a pointer to it
>(a MyClass**).  It then adds 10 to the pointer, and dereferences it;
>the results have type MyClass*.  Of course, the result of adding 10 to
>a pointer to a single object is undefined behavior, so you wouldn't
>want to do this in real code.

Regards




More information about the Gcc-bugs mailing list