c++ - POD 结构体的值初始化是 constexpr?

标签 c++ c++11 constexpr default-constructor value-initialization

考虑结构:

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_1LiteralType 。因此以下内容是有效的并且可以编译:

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/

相关文章:

c++ - 使用 constexpr 或 struct 进行元编程

c++ - clang 和 gcc 中的 Constexpr 复合赋值运算符

c++ - 如果我在不同的类中包含一个基类,该基类的派生类是否也包含在内

c++ - 从动态索引中选择一个 constexpr 索引

c++ - 泛化一个函数

c++ - C++11成员函数第一个参数的类型

c++ - 如何确保在运行时永远不会调用 constexpr 函数?

c++ - 为什么我的线程执行在 CPU 内核之间跳跃?

c++ - set::find 和 <algorithm> find 之间的性能差异

c++ - 用托管类包装 C++ DLL