【发布时间】: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++