Const in std :: array of pointers

Why is the data type std::array differently here.

 using T = const int *; std::array<T, 4> x = { &a, &b, &c, &d }; // name: class std::array<int const *,4> x[0] = &c; // OK : non-constant pointer *x[0] = c; // Error : constant data 

compared to this?

 using T = int *; std::array<const T, 4> x = { &a, &b, &c, &d }; // name: class std::array<int * const,4> x[0] = &c; // Error : constant pointer *x[0] = c; // OK : non-constant data 

This second case is equivalent to const std::array<T, 4> (a constant pointer to mutable data). If we directly use const int * : std::array<const int*, 4> , we get the behavior of the first case.

More precisely, why using T = int*; std::array<const T, 4>; using T = int*; std::array<const T, 4>; equivalent to std::array<int*const, 4> , and not std::array<const int*, 4> ?

+7
c ++ arrays pointers const type-deduction
source share
2 answers

why using T = int*; std::array<const T, 4>; using T = int*; std::array<const T, 4>; equivalent to std::array<int*const, 4> , and not std::array<const int*, 4> ?

Since const is qualified on T , the pointer itself is not (and cannot be) qualified on pointee. Thus, const T means const pointer, not a pointer to const .

The rule is the same whether T pointer or not.

 using T = int; // const T => int const using T = int*; // const T => int* const, not int const* using T = int**; // const T => int** const, neither int* const*, nor int const** 

Pay attention to the third example, if const is qualified on pointee, const T must be int* const* , or it must be qualified at the point of order, i.e. int const** ?

+5
source share
 using T = const int *; //T is a pointer to a CONSTANT integer. std::array<T, 4> x = { &a, &b, &c, &d }; //array of PointerToConstantInteger, size=4 

Change the elements of the x array, but do not look up and try to change the value stored inside it.

 using T = int *; //T is a pointer to an integer. std::array<const T, 4> x = { &a, &b, &c, &d }; //array of CONSTANT IntegerPointer, size=4 

It is not possible to change the elements of an array x , but there is no problem in dereferencing and changing the value stored inside it.

0
source share

All Articles