C++核心準則ES.6:將循環變量和條件變量定義在限定範圍內

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<Circle*>(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<int, string> 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

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章