4

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.

zap
  • 133
  • 9
  • 5
    In C++11, constexpr on member functions implies the constness of that member function. This implication has been removed in C++14. – dyp Feb 17 '17 at 12:45
  • @dyp: I don't follow. A constant member function would have the `const` keyword trailing the argument list, not preceding it as in this question (`const constexpr`). What am I missing? – IInspectable Feb 17 '17 at 12:52
  • In the answer over here [Difference between constexpr and const?](http://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const) the example is `constexpr const int* NP = &N;`, and you need both because they affect different parts of the declaration. That hasn't changed between language versions. – Bo Persson Feb 17 '17 at 13:08
  • @IInspectable That is true, `const constexpr` would not affect the constness of a member function. However, it is the only difference regarding constness that I'm aware of between C++11 and C++14. – dyp Feb 17 '17 at 13:13
  • 1
    In C++11: §7.1.5/8: "A constexpr specifier for a non-static member function that is not a constructor declares that member function to be const." In C++14 there is no such statement, – Alex P. Feb 18 '17 at 15:39

1 Answers1

0

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.

gigabytes
  • 3,104
  • 19
  • 35