C++核心準(zhǔn)則:如果沒有考慮修改對象的值,就將對象定義為const或...

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.
這么做之后,就不會發(fā)生因?yàn)殄e誤而修改變量值的情況。這種方式還增加了編譯優(yōu)化的機(jī)會。
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(實(shí)施建議)
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).
觀察變量是否可變,如果不是就標(biāo)記它。不幸的是,可能很難檢測什么時候一個非常量沒有修改的意圖(或者它僅僅是還沒有修改)。
原文鏈接
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
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評論
圖片
表情
