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

安稳与你 提交于 2020-01-02 07:09:56

问题


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 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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/42298214/constexpr-in-c11-and-c14-not-a-difference-to-const-keyword

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