uninitialized const(未初始化的常量)
问题描述
使用当前的 MSVC 编译器可以完美编译:
This compiles perfectly fine with the current MSVC compiler:
struct Foo
{
} const foo;
但是,使用当前的 g++ 编译器编译失败:
However, it fails to compile with the current g++ compiler:
error: uninitialized const 'foo' [-fpermissive]
note: 'const struct Foo' has no user-provided default constructor
如果我自己提供一个默认构造函数,它会起作用:
If I provide a default constructor myself, it works:
struct Foo
{
Foo() {}
} const foo;
这是 MSVC 过于宽松的另一种情况,还是 g++ 在这里过于严格?
Is this another case of MSVC being too permissive, or is g++ too strict here?
推荐答案
C++03标准:
8.5 [dcl.init] 第 9 段
如果没有为对象指定初始化器,并且对象是(可能是 cv 限定的)非 POD 类类型(或其数组),则该对象应默认初始化;如果对象是 const 限定类型,则基础类类型应具有用户声明的默认构造函数.
If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor.
从上面看 gcc 中的错误似乎是完全有效的.
From the above the error in gcc seems to be perfectly valid.
这篇关于未初始化的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:未初始化的常量
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
