gpt4 book ai didi

c++ - const 传播到 std::array of pointers

转载 作者:可可西里 更新时间:2023-11-01 18:36:42 29 4
gpt4 key购买 nike

为什么是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

和这里相比?

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

第二种情况相当于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>

最佳答案

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

因为 constT 上合格,指针本身,它不是(也不可能)在指针对象上是合格的。所以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**

注意第三个例子,如果const在受教育者身上有资格,const T应该是 int* const* ,或者它应该在 pointee 的 pointee 上限定,即 int const**

关于c++ - const 传播到 std::array of pointers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39333417/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com