POD 结构的值初始化是一个 constexpr?

Value initialization of POD struct is a constexpr?

考虑结构:

struct mystruct { };

这是否总是有效的:

constexpr mystruct mystructInstance = mystruct();

即POD的值初始化是constexpr?同样,如果结构定义为:

struct mystruct { ~mystruct(); };

最后,这个呢:

struct mystruct { mystruct(); ~mystruct(); };

我还没有将 ctr 声明为 constexpr,但是是否有任何隐式推导规则可以保证这一点?

requirements for constexpr variables 是:

A constexpr variable must satisfy the following requirements:

  • its type must be a LiteralType.
  • it must be immediately constructed or assigned a value.
  • the constructor parameters or the value to be assigned must contain only literal values, constexpr variables and functions.
  • the constructor used to construct the object (either implicit or explicit) must satisfy the requirements of constexpr constructor. In the case of explicit constructor, it must have constexpr specified.

给定你的 3 个结构:

struct mystruct_1 { };
struct mystruct_2 { ~mystruct_2(); };
struct mystruct_3 { mystruct_3(); ~mystruct_3(); };

mystruct_1 是一个 LiteralType。所以以下是有效的并且可以编译:

constexpr mystruct_1 mystructInstance_1 = mystruct_1();

mystruct_2 而不是 一个 LiteralType 因为它有一个非平凡的析构函数。 因此以下内容无效且无法编译:

constexpr mystruct_2 mystructInstance_2 = mystruct_2();

同样适用于 mystruct_3,此外它不是 aggregate 并且不提供 constexpr 构造函数。 所以下面的也是无效的,编译失败:

constexpr mystruct_3 mystructInstance_3 = mystruct_3();

您还可以查看此 online demo 中的描述性错误消息。