作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我刚看了答案
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.
关于c++ - const 和 constexpr 最终会是一回事吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850521/
我是一名优秀的程序员,十分优秀!