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(示例)
代码语言:javascript复制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