温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-11-24 11:43:01 来源:亿速云 阅读:243 作者:iii 栏目:大数据

本篇内容主要讲解“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++默认情况下为什么使对象不可修改”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI