【问题标题】:Why this ill formed program compiles fine in g++? [duplicate]为什么这个格式不正确的程序在 g++ 中编译得很好? [复制]
【发布时间】:2015-06-15 14:19:11
【问题描述】:

我在here 上阅读了关于 C++ 中的默认初始化。它说:

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

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

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 扩展还是其他什么?

所以,我认为上述程序编译成功的原因是 struct 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 是具有至少一个数据成员的 const 限定类型,则它 必须是具有用户提供的默认构造函数的类类型。

如果我错了并且理解不正确,请纠正我。

【问题讨论】:

标签: c++ c++11 initialization g++


【解决方案1】:

C++ 标准对此非常清楚,来自 [dcl.init]:

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

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

【讨论】:

  • @meet 显然是 GCC 中的错误。 BTW Clang rejects this code.
  • @meet 因为 GCC 选择不遵循这个特定规则。见bug 57820
猜你喜欢
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
相关资源
最近更新 更多