定义变量放在循环立马_C++核心准则ES.6:将循环变量和条件变量定义在限定范围内...

6474e0c0642d610f4ef42b77e63b7dfe.png

ES.6: Declare names in for-statement initializers and conditions to limit scope

ES.6:将循环变量和条件变量定义在限定范围内

Reason(原因)

Readability. Minimize resource retention.

可读性。最小化资源占用。

Example(示例)

void use(){    for (string s; cin >> s;)        v.push_back(s);    for (int i = 0; i < 20; ++i) {   // good: i is local to for-loop        // ...    }    if (auto pc = dynamic_cast(ps)) {   // good: pc is local to if-statement        // ... deal with Circle ...    }    else {        // ... handle error ...    }}

Enforcement(实施建议)

  • Flag loop variables declared before the loop and not used after the loop
  • 标记在循环之前定义循环变量而在循环之后没有使用的情况。
  • (hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose.
  • (困难)标记在循环之前定义循环变量,然后在循环之后用于无关目的的情况。

C++17 and C++20 example(C++17和C++20示例)

Note: C++17 and C++20 also add if, switch, and range-for initializer statements. These require C++17 and C++20 support.

注意:C++17和C++20也增加了if,switch,和范围for初始化语句。下面的代码需要C++17和C++20支持。

map mymap;if (auto result = mymap.insert(value); result.second) {    // insert succeeded, and result is valid for this block    use(result.first);  // ok    // ...} // result is destroyed here

C++17 and C++20 enforcement (if using a C++17 or C++20 compiler)

C++17和C++20实施建议(如果使用C++17或者C++20编译器)

  • Flag selection/loop variables declared before the body and not used after the body
  • 标记在选择/循环体之前定义选择/循环变量而在选择/循环体之后没有使用的情况。
  • (hard) Flag selection/loop variables declared before the body and used after the body for an unrelated purpose.
  • (困难)标记在选择/循环体之前定义选择/循环变量,然后在选择/循环体之后用于无关目的的情况。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es6-declare-names-in-for-statement-initializers-and-conditions-to-limit-scope


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

08bf302c470ea5b22d2d933bfc0293b0.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值