C++核心准则Con.5:对于可以在编译时计算的值,使用constexpr进行声明

时间:2022-07-23
本文章向大家介绍C++核心准则Con.5:对于可以在编译时计算的值,使用constexpr进行声明,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Con.5: Use constexpr for values that can be computed at compile time

Con.5:对于可以在编译时计算的值,使用constexpr进行声明

Reason(原因)

Better performance, better compile-time checking, guaranteed compile-time evaluation, no possibility of race conditions.

更好的性能,更好的编译检查,保证编译时计算,不存在竞争条件。

Example(示例)

double x = f(2);            // possible run-time evaluation
const double y = f(2);      // possible run-time evaluation
constexpr double z = f(2);  // error unless f(2) can be evaluated at compile time
Note(注意)

See F.4.

参见:F.4

Enforcement(实施建议)

  • Flag const definitions with constant expression initializers.
  • 标记使用常量表达式初始化的常量定义。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#con5-use-constexpr-for-values-that-can-be-computed-at-compile-time