C++核心准则Con.4:如果一个对象在构建之后值不会改变,使用const定义它

时间:2022-07-23
本文章向大家介绍C++核心准则Con.4:如果一个对象在构建之后值不会改变,使用const定义它,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Con.4: Use const to define objects with values that do not change after construction

Con.4:如果一个对象在构建之后值不会改变,使用const定义它

Reason(原因)

Prevent surprises from unexpectedly changed object values.

防止对象值被意外修改的情况。

Example(示例)

void f()
{
    int x = 7;
    const int y = 9;

    for (;;) {
        // ...
    }
    // ...
}

As x is not const, we must assume that it is modified somewhere in the loop.

由于x没有定义为常量类型,我们必须假设它可能在循环的某处被修改。

Enforcement(实施建议)

  • Flag unmodified non-const variables.
  • 标记不会被修改的非常量。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#con4-use-const-to-define-objects-with-values-that-do-not-change-after-construction