为什么未初始化的constexpr变量不是常量
why is an uninitialized constexpr variable not constant?
我不确定这是编译器错误还是误解了constexpr:
struct S{};
constexpr S s1{};
constexpr S s2;
struct test{
static constexpr auto t1 = s1;
static constexpr auto t2 = s2; //error here
};
GCC 4.8给了我一个奇怪的错误"错误:字段初始值设定项不是常量"。s2真的不是常数吗?如果是,为什么?
为了清楚起见,我实际上在代码中使用了一堆空结构(用于元编程https://github.com/porkybrain/Kvasir)所以我对这个具体的例子很感兴趣。
更新:代码应该编译,因为[class.ctor]/5
读取:
隐式定义的默认构造函数执行类的初始化集,该初始化集将由用户为该类编写的默认构造函数来执行,该类没有ctor初始值设定项(12.6.2)和空的复合语句。如果用户编写的默认构造函数满足
constexpr
构造函数(7.1.5)的要求,那么隐式定义的默认构造函数就是constexpr
。
由于S
只是一个空结构,因此隐式定义的默认构造函数是空的,因此满足constexpr
的要求。
所以在这里,您要处理的是编译器的不完美,您必须以某种方式解决这个问题。
老答案:
Clang发出更合理的错误信息:
main.cpp:3:13: error: default initialization of an object of const type 'const S'
requires a user-provided default constructor
constexpr S s2;
^
[dcl.constexpr]/9提供了解释,甚至几乎完全是您的代码示例:
对象声明中使用的
constexpr
说明符将对象声明为常量。此类对象应具有文字类型,并且应进行初始化。(…)示例:
struct pixel {
int x, y;
};
constexpr pixel ur = { 1294, 1024 };// OK
constexpr pixel origin; // error: initializer missing
-结束示例]
相关文章:
- 通过多个头文件使用常量变量
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 非常量变量只读位置的赋值
- 使用大量已知常量变量的正确方法
- 无法在具有常量变量大小的类中创建堆栈分配数组
- 这些语句是否等效(静态变量、常量变量和泛型)
- 包含常量变量并包含在多个文件中的标头的链接错误
- 我们如何修改常量变量的值
- 如何在模板类中设置静态常量变量
- 为什么常量变量是模板特殊化所必需的,而不是常量
- 如何在函数中传递常量变量?
- 定义常量变量的最佳方法
- C++ 声明常量变量,但推迟其初始化?
- 如何初始化具有常量变量的结构数组
- 使用常量变量作为维度将矩阵声明为类成员时出现编译器错误
- 使用指针 c++ 更改常量变量
- c++ 类中的静态常量变量和常量变量在存储方面是否有区别
- 为什么 lambda 对象中的局部变量是常量变量?
- 使用常量变量作为数组的大小
- 为许多类可能需要的所有常量变量制作独立的头文件是否是一种很好的做法?