Search code examples
c++arraysclangc++17new-operator

What is the reason for the warning: "when type is in parentheses, array cannot have dynamic size"?


I posted already a question about a GCC bug relating to dynamic memory allocation of arrays:

An error is issued by gcc relative to parsing type-id in a new expression

Now using Clang HEAD 10.0.0 I am getting the following warning:

rog.cc:9:37: warning: when type is in parentheses, array cannot have dynamic size
    int ( **a )[N3] = new ( int ( *[n1] )[N3] ); 
                          ~~        ^~        ~

When I run this demonstrative program:

#include <cstddef> 

int main() 
{ 
    const size_t N3 = 4; 
    size_t n1 = 2; 

    int ( **a )[N3] = new ( int ( *[n1] )[N3] ); 
}

What part of the standard is violated when the non-constant variable n1 is used?


Solution

  • The unparenthesized form uses a new-type-id; the parenthesized form uses a type-id. Only new-type-id allows a dynamic array bound. Plain type-id does not. Compare:

    new-type-id:
        type-specifier-seq new-declarator_opt
    
    new-declarator:
        ptr-operator new-declarator_opt
        noptr-new-declarator
    
    noptr-new-declarator:
        [ expression_opt ] attribute-specifier-seq_opt
        noptr-new-declarator [ constant-expression ] attribute-specifier-seq_opt
    

    with

    type-id:
        type-specifier-seq abstract-declarator_opt
    
    abstract-declarator:
        ptr-abstract-declarator
        noptr-abstract-declarator_opt parameters-and-qualifiers trailing-return-type
        abstract-pack-declarator
    
    ptr-abstract-declarator:
        noptr-abstract-declarator
        ptr-operator ptr-abstract-declarator_opt
    
    noptr-abstract-declarator:
        noptr-abstract-declarator_opt parameters-and-qualifiers
        noptr-abstract-declarator_opt [ constant-expression_opt ] attribute-specifier-seq_opt
        ( ptr-abstract-declarator )
    

    Note that the first production of noptr-new-declarator allows the array bound to be any expression, while the noptr-abstract-declarator production requires the bound to be a constant-expression.