【问题标题】:What's the real difference between "constinit" and "constexpr"? [duplicate]“constinit”和“constexpr”之间的真正区别是什么? [复制]
【发布时间】:2020-10-08 04:28:52
【问题描述】:
constexpr int f() { return 0; }
int g() { return 0; }

constexpr auto c1 = f(); // OK
constinit auto c2 = f(); // OK

constexpr auto d1 = g(); // ill-formed
constinit auto d2 = g(); // ill-formed

int main() {}

如上面的代码所示,我找不到constinitconstexpr 之间的任何区别。

constinitconstexpr 之间的真正区别是什么?


更新:

相关的What is constinit in C++20?没有明确说明constinitconstexpr的区别。

【问题讨论】:

  • @E_net4thedupefinder,您链接中的答案并没有明确说明constinitconstexpr 之间的区别。
  • 是的,确实如此。第一个答案详细说明了constexpr 的含义以及constinit 如何不暗示大部分内容。

标签: c++ constexpr semantics c++20 constinit


【解决方案1】:

constinit 变量是常量初始化的,但它不能在常量表达式中使用,甚至不能自动常量。您的main 可以合法地包含此行

c2 = 2; 

是的,初始化后可以修改。

【讨论】:

  • 来自 cppreference: "constexpr 要求对象必须具有静态初始化和 常量销毁 并使对象具有 const 限定,但是 constinit 可以不强制要求持续破坏const-qualification。” 就我而言,你能告诉我这个持续破坏是什么意思吗? constexpr 是如何强制执行此操作的,而 constinit 不是。
  • @AccessDenied - 我不能。据我所知,这是只出现在 cppreference 上的东西,因此很可能是由编辑该条目的人编造出来的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2010-09-10
  • 2018-06-12
相关资源
最近更新 更多