ES.25: Declare an object const or constexpr unless you want to modify its value later on
ES.25:如果沒有考慮修改對象的值,就将對象定義為const或者constexpr
Reason(原因)
That way you can't change the value by mistake. That way may offer the compiler optimization opportunities.
這麼做之後,就不會發生因為錯誤而修改變量值的情況。這種方式還增加了編譯優化的機會。
Example(示例)
void f(int n)
{
const int bufmax = 2 * n + 2; // good: we can't change bufmax by accident
int xmax = n; // suspicious: is xmax intended to change?
// ...
}
Enforcement(實施建議)
Look to see if a variable is actually mutated, and flag it if not. Unfortunately, it may be impossible to detect when a non-const was not intended to vary (vs when it merely did not vary).
觀察變量是否可變,如果不是就标記它。不幸的是,可能很難檢測什麼時候一個非常量沒有修改的意圖(或者它僅僅是還沒有修改)。
原文連結
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es25-declare-an-object-const-or-constexpr-unless-you-want-to-modify-its-value-later-on