Compiler error when defining an array using typeof and decltype

A) This works:

int main() {
    int * a = new int[5];
    delete[] a;
    return 0;
}

B) These errors:

int main() {
    int * a = new typeof(*a)[5];
    delete[] a;
    return 0;
}

with error: invalid types 'int [int]' for array index

C) This works:

int main() {
    int * a = new typeof(a)[5];
    delete[] a;
    return 0;
}

I cannot understand why B fails, because after the extension, the instruction should look like this:

int *a = new int[5];

because typeof(*a)- int.

Here is an experiment with decltype:

D) This does not work:

int main() {
    int * a = new decltype(a)[5];
    delete[] a;
    return 0;
}

with an error: cannot convert 'int **' to 'int *' during initialization. This is expected if decltype (a) is int *, so it matches incorrectly int *a = new int*[5];.

E) But this does not work:

int main() {
    int * a = new decltype(*a)[5];
    delete[] a;
    return 0;
}

with an error: the new cannot be applied to the reference type

Thus, whether it be a GCC extension or a standard C ++ 11 function, both do not work in all cases, taking into account my expectations.

+4
2

++ 11, , .

- , decltype. , gcc typeof, , B) , C) D) E) .

D) , decltype , a. a - . , . id-, decltype . a int*. new decltype(a)[5]; int*. a int**, int*.

E) , decltype , *a. (T) int. *a . id- a. *a lvalue. lvalue decltype T&, T . , decltype(*a) int&. , new decltype(*a)[5] .

():

§ 7.1.6.2 [dcl.type.simple]

  1. , , decltype () :

-   ID- ( 5.2.5), decltype () , , func- ,

-   , x, decltype () & &, T ;

-   , lvalue, decltype () &, T ;

-   , decltype ()

:

int * a = new std::remove_pointer<decltype(a)>::type[5];

:

int * a = new std::remove_reference<decltype(*a)>::type[5];

, . , , decltype , . , , auto:

auto a = new int[5];
+2

* a - int typeof

int *a = new int[5];

, 5 ,

, :

typeof(new typeof(int *)[5])a;

 int * a = new typeof(*a)[5];
+1

Source: https://habr.com/ru/post/1615745/


All Articles