C++核心準(zhǔn)則ES.6:將循環(huán)變量和條件變量定義在限定范圍內(nèi)

ES.6: Declare names in for-statement initializers and conditions to limit scope
ES.6:將循環(huán)變量和條件變量定義在限定范圍內(nèi)
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
標(biāo)記在循環(huán)之前定義循環(huán)變量而在循環(huán)之后沒有使用的情況。
(hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose.
(困難)標(biāo)記在循環(huán)之前定義循環(huán)變量,然后在循環(huán)之后用于無關(guān)目的的情況。
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
標(biāo)記在選擇/循環(huán)體之前定義選擇/循環(huán)變量而在選擇/循環(huán)體之后沒有使用的情況。
(hard) Flag selection/loop variables declared before the body and used after the body for an unrelated purpose.
(困難)標(biāo)記在選擇/循環(huán)體之前定義選擇/循環(huán)變量,然后在選擇/循環(huán)體之后用于無關(guān)目的的情況。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es6-declare-names-in-for-statement-initializers-and-conditions-to-limit-scope
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
