C++默认情况下为什么使对象不可修改

本篇内容主要讲解“C++默认情况下为什么使对象不可修改”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++默认情况下为什么使对象不可修改”吧!

Con.1:默认情况下使对象不可修改

Reason(原因)

Immutable objects are easier to reason about, so make objects non-const only when there is a need to change their value. Prevents accidental or hard-to-notice change of value.

不可修改的对象更容易理解,因此只有在存在变更需求时才将对象定义为非常量。防止偶然或者不易察觉的情况下修改对象的值。

Example(示例)

for (const int i : c) cout << i << '\n';    // just reading: const

for (int i : c) cout << i << '\n';          // BAD: just reading
Exception(例外)

Function arguments are rarely mutated, but also rarely declared const. To avoid confusion and lots of false positives, don't enforce this rule for function arguments.

函数参数很少修改,但还是很少定义为常量类型。为了避免混淆和大量的误检出,不要对函数参数适用本规则。

void f(const char* const p); // pedantic
void g(const int i);        // pedantic

Note that function parameter is a local variable so changes to it are local.

注意函数参数是局部变量,因此对它的修改也是局部的。

Enforcement(实施建议)

  • Flag non-const variables that are not modified (except for parameters to avoid many false positives)

  • 标记没有发生变更的非常量变量(为了避免误检出需要将函数参数除外)

到此,相信大家对“C++默认情况下为什么使对象不可修改”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!