为什么这个格式错误的程序在 g++ 中编译得很好

Why this ill formed program compiles fine in g++?

本文关键字:g++ 编译 很好 程序 格式 错误 为什么      更新时间:2023-10-16

我在这里阅读了有关C++默认初始化的信息。它说:

如果 T 是常量限定类型,则它必须是具有 用户提供的默认构造函数。

该链接上给出的示例是(我只显示了与我的问题相关的程序语句,其他我省略了):

struct T1 {};
int main()
{
    const T1 nd;    //  error: const class type with implicit ctor
}

但它在 gcc 4.8.1 和 4.9.2 上编译得很好。我也用-std=c++14选项编译了它,但它仍然可以编译。这是 gcc 扩展还是别的什么?

所以,我认为成功编译上述程序背后的原因是结构 T1 中没有成员。因此,在这种情况下,此处不会发生默认初始化。但是,如果我添加一个数据成员,例如:

struct T1 { int a; };
int main()
{
    const T1 nd;    //  error: const class type with implicit ctor
}

然后编译器给出相应的错误消息,如下所示:

6 11 [Error] uninitialized const 'a' [-fpermissive]
2 8 [Note] 'const struct T1' has no user-provided default constructor
3 8 [Note] and the implicitly-defined constructor does not initialize 'int T1::a'

那么,声明不应该这样写吗?

如果 T 是具有至少一个数据成员的常量限定类型,则 必须是具有用户提供的默认构造函数的类类型。

如果我错了,请纠正我并理解错误的东西。

C++标准对此

非常清楚,来自 [dcl.init]:

如果程序调用 const 限定类型的对象的默认初始化 TT应为类类型 使用用户提供的默认构造函数。

所以 gcc 在这方面是不合规的,cpp 偏好是正确的。