Judge - 4 months ago 40

C++ Question

Why is

`std::array`

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

If we use

`const int *`

`std::array<const int*, 4>`

So more precisely, why is

`using T = int*; std::array<const T, 4>;`

`std::array<int*const, 4>`

`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**`

?