I just read the answer to
const vs constexpr on variables
and am watching this Google Tech Talk about C++11/14 features , in which it is said that, well, constexpr might not be necessary in the future when it comes to functions, since compilers will evolve to figure it out on their own. Finally, I know that Java compilers and JVMs work hard to figure out that classes (or any variable maybe) are immutable after construction - without you explicitly saying so - and doing all sorts of wicked optimization based on this fact.
So, here's the question: Is the fate of const and constexpr to eventually be the same thing? That is, even though a compiler is not guaranteed to do runtime initialization etc., will it not eventually do so whenever possible (basically)? And when that happens, won't one of the keywords be redundant? (Just like inline is becoming, maybe)?
All constexpr variables are const . A variable can be declared with constexpr , when it has a literal type and is initialized. If the initialization is performed by a constructor, the constructor must be declared as constexpr .
const can only be used with non-static member function whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.
The primary difference between const and constexpr variables is that the initialization of a const variable can be deferred until run time. A constexpr variable must be initialized at compile time.
In C++11, constexpr member functions are implicitly const.
No, neither one will replace the other, they have different roles. Bjarne Stroustrup tells us in his C++ FAQ that constexpr is not a replacement for const and outlines the different roles of each feature:
Please note that constexpr is not a general purpose replacement for const (or vise versa):
- const's primary function is to express the idea that an object is not modified through an interface (even though the object may very well be modified through other interfaces). It just so happens that declaring an object const provides excellent optimization opportunities for the compiler. In particular, if an object is declared const and its address isn't taken, a compiler is often able to evaluate its initializer at compile time (though that's not guaranteed) and keep that object in its tables rather than emitting it into the generated code.
- constexpr's primary function is to extend the range of what can be computed at compile time, making such computation type safe. Objects declared constexpr have their initializer evaluated at compile time; they are basically values kept in the compiler's tables and only emitted into the generated code if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With