const传播到std ::指针数组

Jud*_*dge 7 c++ arrays pointers const type-deduction

为什么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
Run Code Online (Sandbox Code Playgroud)

相比这里?

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
Run Code Online (Sandbox Code Playgroud)

第二种情况等同于const std::array<T, 4>(对非常数数据的常量指针).如果我们const int *直接使用:std::array<const int*, 4>我们得到第一个案例行为.

更确切地说,为什么using T = int*; std::array<const T, 4>;相当于std::array<int*const, 4>和不相同std::array<const int*, 4>

son*_*yao 5

为什么using T = int*; std::array<const T, 4>;相当于std::array<int*const, 4>和不相同std::array<const int*, 4>

因为指针本身const是合格的T,所以它不是(并且不能)在指针上合格.所以const T意味着const指针,而不是指针const.

规则是相同的,无论是否T是指针.

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**
Run Code Online (Sandbox Code Playgroud)

注意第三个例子,如果const在指针对象上是合格的,const T应该是int* const*,或者它应该在pointee的指针上合格,即int const**