constexpr in C++11 and C++14 (not a difference to const keyword) [duplicate]

吃可爱长大的小学妹 提交于 2019-12-06 09:18:42

Consider this piece of code:

struct T { 
  int x;

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

constexpr T t = { 42 };

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

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!