天天看點

C++核心準則ES.22:沒有合适的初始值就不要定義變量

ES.22: Don't declare a variable until you have a value to initialize it with

ES.22:沒有合适的初始值就不要定義變量

Reason(原因)

Readability. Limit the scope in which a variable can be used. Don't risk used-before-set. Initialization is often more efficient than assignment.

可讀性。限制變量可用的範圍。不要冒設定前使用的風險。初始化通常比指派更高效。

Example, bad(反面示例)

string s;
// ... no use of s here ...
s = "what a waste";      

Example, bad(反面示例)

SomeLargeType var;   // ugly CaMeLcAsEvArIaBlE

if (cond)   // some non-trivial condition
    Set(&var);
else if (cond2 || !cond3) {
    var = Set2(3.14);
}
else {
    var = 0;
    for (auto& e : something)
        var += e;
}

// use var; that this isn't done too early can be enforced statically with only control flow      

This would be fine if there was a default initialization for SomeLargeType that wasn't too expensive. Otherwise, a programmer might very well wonder if every possible path through the maze of conditions has been covered. If not, we have a "use before set" bug. This is a maintenance trap.

如果SomeLargeType存在一個代價不高的預設初始化,這段代碼問題不大。否則,程式員可能特别想知道是否通過條件迷宮的所有路徑都被覆寫了。如果不是,我們就遇到了一個設定前使用的錯誤。這是一個維護陷阱。

For initializers of moderate complexity, including for const variables, consider using a lambda to express the initializer; see ES.28.

對于中等複雜度初始化器,包括常量,考慮使用lambda表達式實作。參見ES.28

Enforcement(實施建議)

  • Flag declarations with default initialization that are assigned to before they are first read.
  • 标記包含預設初始化操作卻在第一次使用之前指派的情況。
  • Flag any complicated computation after an uninitialized variable and before its use.
  • 标記任何定義了未初始化變量又在它被使用之前進行了複雜處理的qi

原文連結

​​https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es22-dont-declare-a-variable-until-you-have-a-value-to-initialize-it-with​​

繼續閱讀