const 和 constexpr 最终会是一回事吗?

Will const and constexpr eventually be the same thing?

我刚刚阅读了

的答案

const vs constexpr on variables

并且正在观看这个 Google Tech Talk about C++11/14 features ,其中据说,好吧,constexpr 在未来可能不需要函数,因为编译器会进化以自行解决。最后,我知道 Java 编译器和 JVM 努力找出类(或任何变量可能)在构造后是不可变的 - 没有你明确这么说 - 并根据这一事实进行各种邪恶的优化。

那么,问题来了:const 和 constexpr 的命运最终会是一回事吗?也就是说,即使编译器不能保证进行运行时初始化等,它最终是否会尽可能(基本上)这样做?当这种情况发生时,其中一个关键字不会是多余的吗? (就像内联正在成为,也许)?

不,两者都不会取代另一个,它们的作用不同。 Bjarne Stroustrup 在他的 C++ FAQ 中告诉我们,constexpr 不是 const 的替代品,并概述了每个功能的不同作用:

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.