Will const and constexpr eventually be the same thing?

人盡茶涼 提交于 2019-12-10 15:24:38

问题


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)?


回答1:


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.


来源:https://stackoverflow.com/questions/27850521/will-const-and-constexpr-eventually-be-the-same-thing

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