【问题标题】:constexpr in C++11 and C++14 (not a difference to const keyword) [duplicate]C ++ 11和C ++ 14中的 constexpr (与 const 关键字没有区别)[重复]
【发布时间】:2017-07-06 23:54:59
【问题描述】:

在 Mike Isaacson (https://youtu.be/-ctgSbEfRxU?t=2907) 的“探索 C++17 及以后”演讲中,有一个关于写作的问题:

const constexpr ....

vs 单个常量。 Mike 说在 C++11 中 constexpr 意味着 const 而在 C++14 中则没有。 这是真的吗? 我试图找到证明,但我做不到。

我不是在问 const 和 constexpr 之间的区别(与许多其他问题一样),而是关于两个 C++ 标准版本中 constexpr 的区别。

【问题讨论】:

  • 在 C++11 中,成员函数上的 constexpr 意味着该成员函数的常量。在 C++14 中已删除此含义。
  • @dyp:我不关注。一个常量成员函数将有 const 关键字尾随参数列表,而不是在这个问题之前 (const constexpr)。我错过了什么?
  • Difference between constexpr and const? 的答案中,示例是constexpr const int* NP = &N;,您需要两者,因为它们会影响声明的不同部分。这在语言版本之间没有改变。
  • @IInspectable 没错,const constexpr 不会影响成员函数的常量。然而,这是我所知道的 C++11 和 C++14 之间关于 constness 的唯一区别。
  • 在 C++11 中:第 7.1.5/8 节:“非构造函数的非静态成员函数的 constexpr 说明符声明该成员函数为 const。”在 C++14 中没有这样的声明,

标签: c++ c++11 c++14 constexpr


【解决方案1】:

考虑这段代码:

struct T { 
  int x;

  constexpr void set(int y) {
    x = y;
  }
};

constexpr T t = { 42 };

int main() {
  t.set(0);
  return 0;
}

它应该在 C++14 中编译,但在 C++11 中出现错误,好像成员函数 set 被声明为 const。这是因为 constexpr 在 C++11 中暗示了 const,而在标准的后续版本中不再如此。

constexpr 关键字保证对象不会在运行时动态初始化。对于函数,它保证可以在编译时评估函数。在 C++11 中,这与“存储在只读内存中”相混淆,但很快就被识别为错误。

此外,在 C++14 中,constexpr 函数和成员功能更加强大。例如,它们可以修改非const 对象,因此它们不能隐含为const

【讨论】:

  • 为什么投反对票?
  • 可能是因为它实际上并没有在 C++14 中编译:错误:将 'const T' 作为 'this' 参数传递会丢弃限定符 [-fpermissive]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 2012-08-15
  • 1970-01-01
  • 2011-09-30
  • 2014-07-30
  • 2012-12-16
相关资源
最近更新 更多