C ++: what does "T const * []" mean?

  • What does "T const * []" mean as a type parameter means?
  • What is the difference compared to "T * []"?
  • And as a final question: why can't I pass "T * []" to a function that requires "T const * []" as a parameter?

Thank you for your help.

Tobias

+6
source share
2 answers

As a type in general, it is an array of pointers to the constant T. Try putting the name in it:

T const *x[]; 

and apply the usual rules: [] binds tighter than *, therefore an array. Then * means that its array of pointers, and finally, they all point to a constant T. (As usual, const changes everything that is to its left.)

As a parameter, of course, the type of the array is converted to the type of the pointer, so we get a pointer to a pointer to the constant T. This can also be written:

 T const ** 

If you release const, you will get:

 T ** 

this is not the same as T const** .

And the reason you cannot pass T** or T*[] to the first form is to prevent things like:

 void f(int const* p1[]; int const* p2) { p1[0] = *p2; } int const x = 10; int* px[1]; f(px, &x); *px[0] = 20; // Where does this write? 

The fact that declarations are written using [] is misleading in this case because the rules for pointers to pointers apply.

+4
source

This is an array of pointers to constant objects of type T (i.e., the pointer can change, but you cannot call the non-const function or change the unchangeable data element on these objects). T * [] is an array of pointers to non-constant objects. You cannot pass T * [] to a function requiring T const * [], as this will invalidate the const const pointers.

See here for more details.

+3
source

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


All Articles