gpt4 book ai didi

c++ - 对未知大小数组的引用的列表初始化 : is it supposed to deduce the array size?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:28 28 4
gpt4 key购买 nike

以下代码在 Clang 中编译良好并输出 int [3] 数组的大小

#include <iostream>

int main()
{
const int (&a)[] = { 1, 2, 3 };
std::cout << sizeof a << std::endl;
}

但是,在 GCC 中,声明编译得很好,但是 sizeof a 没有:显然 GCC 拒绝“推断”数组大小并以 a 作为结尾对 const int [] 类型的引用,该类型不完整。

此类初始化的预期行为是什么?

9.3.4/3似乎是此类情况下标准的相关部分,但它本身似乎并不能最终回答这个问题。

最佳答案

标准在这一点上并不完全清楚,我认为GCC的解释很可能是WG21的意图,但我不确定。

标准的相关部分是 [dcl.array],它描述了如何确定声明中声明的类型,其中声明符包含数组形成运算符 []。 .我引用相关部分:

An array bound may also be omitted when the declarator is followed by an initializer (11.6) or when a declarator for a static data member is followed by a brace-or-equal-initializer (12.2). In both cases the bound is calculated from the number of initial elements (say, N) supplied (11.6.1), and the type of the identifier of D is “array of N T”.

这是否仅适用于数组本身的声明,或者它是否也应该适用于对数组的引用的情况并不完全,因为在解释 [dcl.ref 时必须递归地查询 [dcl.array] ](描述了 &&& 运算符)。然而,我认为后一种解释应该被拒绝,因为我们不希望初始化器在 [] 时导致推导出一个边界。更深地埋在声明符中。也就是说,考虑人为的例子:

int (*a[1])(const int (&)[]) = {0};

这里是 GCC 和 Clang agree ,我认为常识也同意,a 的类型是int (*[1])(const int (&)[]) ,而不是 int (*[1])(const int (&)[1]) :事实 a拥有初始化器不会导致推导内部数组绑定(bind)。

基于此,我认为 GCC 没有推导代码中绑定(bind)的数组是正确的,因此 a类型为 const int (&)[] .

关于c++ - 对未知大小数组的引用的列表初始化 : is it supposed to deduce the array size?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55544107/

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