Why is std::array's data type being instantiated 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 here?
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> (constant pointers to non-constant data).
If we use const int * directly: std::array<const int*, 4> we get first case behavior.
So more precisely, why is using T = int*; std::array<const T, 4>; equivalent to std::array<int*const, 4> and not std::array<const int*, 4>?
why is
using T = int*; std::array<const T, 4>;equivalent tostd::array<int*const, 4>and notstd::array<const int*, 4>?
Because const is qualified on T, the pointer itself, it's not (and couldn't be) qualified on the pointee. So const T means const pointer, not pointer to const.
The rule is same, whether T is 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**
Note the 3rd example, if const is qualified on the pointee, const T should be int* const*, or it should be qualified on the pointee of pointee, i.e. int const**?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With