0
点赞
收藏
分享

微信扫一扫

C++核心准则ES.25:如果没有考虑修改对象的值,就将对象定义为const或者constexpr


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​​

 

 

觉得本文有帮助?欢迎点赞并分享给更多人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

举报

相关推荐

0 条评论