为什么这不起作用? (引用的大括号初始化)

Why doesn't this work? (brace-initialization of references)

#include <array>

int main()
{
    struct A
    {
        unsigned char l;
        std::array<char, 12> c;
    };

    const A a = {1, "t"}; // OK
    const A& ar = {1, "t"}; // error: invalid initialization of reference of type 'const main()::A&' from expression of type '<brace-enclosed initializer list>'
}

(gcc 8.2, -std=c++17)

This question 谈到一个 GCC 错误,但它是旧的(7 年前)。

请注意,我不关心生命周期的延长,我实际上是将临时文件直接传递给一个函数以供使用而不是存储它,但我尝试使示例变得干净。


编辑:

首先要注意的是初始化器 {1, "t"} 使用 大括号省略 来初始化子聚合 A.c 这意味着文字 "t" 被用来直接初始化 std::array 持有的内部数组。在这种情况下,这个数组看起来像 char data[12].

这简化为说 我们正在使用包含初始化成员数组 的元素的大括号列表初始化对 const A 的引用。

这在某种程度上相当于:

struct S {
    char const data[2];
};
S const& s = {"t"}; // fail for gcc

GCC 已经 bug report 了。

您已经在评论部分提供了解决方法。只需将引用初始化为:

const A& ar = A{1, "t"}