C++核心准则ES.6:将循环变量和条件变量定义在限定范围内
共 1778字,需浏览 4分钟
·
2020-04-16 23:22
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
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!