Judge Judge - 3 months ago 28
C++ Question

const propagation to std::array of pointers

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>
?

Answer

why is using T = int*; std::array<const T, 4>; equivalent to std::array<int*const, 4> and not std::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**?