考虑结构:
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中的描述性错误消息。 .
关于c++ - POD 结构体的值初始化是 constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31937646/