问题
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