为什么未初始化的 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 给我一个奇怪的错误 "error: field initializer is not constant"。 s2 真的不是常数吗?如果是,为什么?

为了清楚起见,我实际上在我的代码中使用了一堆空结构(用于元编程 https://github.com/porkybrain/Kvasir),所以我真的对这个特定示例很感兴趣。

更新: 代码应该编译,因为 [class.ctor]/5 读取:

The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-initializer (12.6.2) and an empty compound-statement. If that user-written default constructor would satisfy the requirements of a constexpr constructor (7.1.5), the implicitly-defined default constructor is 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 提供了解释,甚至几乎完全以您的代码为例:

A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized.(...) [ Example:

struct pixel {
    int x, y;
};
constexpr pixel ur = { 1294, 1024 };// OK
constexpr pixel origin; // error: initializer missing

—end example ]