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

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

DS.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

 


 

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

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

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