C ++ 11和C ++ 14中的constexpr(与const关键字没有区别) [英] constexpr in C++11 and C++14 (not a difference to const keyword)

查看:100
本文介绍了C ++ 11和C ++ 14中的constexpr(与const关键字没有区别)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Mike Isaacson的探索C ++ 17及更高版本中的演讲中( https ://youtu.be/-ctgSbEfRxU?t = 2907 )关于写作存在疑问:

In the "Exploring C++17 and beyond" presentation by Mike Isaacson at one point (https://youtu.be/-ctgSbEfRxU?t=2907) there is question about writing:

const constexpr ....

vs单个常量。 Mike表示,在C ++ 11中constexpr隐含const,而在C ++ 14中则不隐含。
是真的吗?
我试图找到证明,但是我做不到。

vs single const. Mike said that in C++11 constexpr implies const and in C++14 it does not. Is it true? I've tried to find prove for that but I couldn't.

我并不是在问const和constexpr之间的区别(因为很多其他问题),但是关于constexpr在两个版本的C ++标准中的区别。

I'm not asking about difference between const and constexpr (as a lot of other questions) but about difference in constexpr in two versions of C++ standard.

推荐答案

请考虑以下这段代码:

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 ,而在该标准的后续版本中不再如此。

It should compile in C++14, but give an error in C++11 as if the member function set was declared const. This is because constexpr implies const in C++11, while this is not true anymore in subsequent versions of the standard.

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

The constexpr keyword guarantees that the object will not be dynamically initialized at runtime. In case of functions, it guarantees that the function can be evaluated at compile-time. In C++11, this was confounded with "being stored in read-only memory", but this was soon recognized as an error.

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

In C++14, moreover, constexpr functions and members are much more capable. They can modify non-const objects, for instance, so they cannot be implicitly const.

这篇关于C ++ 11和C ++ 14中的constexpr(与const关键字没有区别)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆