C++核心準(zhǔn)則DS.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.
可讀性。限制變量可用的范圍。不要冒設(shè)定前使用的風(fēng)險。初始化通常比賦值更高效。
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存在一個代價不高的默認(rèn)初始化,這段代碼問題不大。否則,程序員可能特別想知道是否通過條件迷宮的所有路徑都被覆蓋了。如果不是,我們就遇到了一個設(shè)定前使用的錯誤。這是一個維護(hù)陷阱。
For initializers of moderate complexity, including for?const?variables, consider using a lambda to express the initializer; see?ES.28.
對于中等復(fù)雜度初始化器,包括常量,考慮使用lambda表達(dá)式實現(xiàn)。參見ES.28
Enforcement(實施建議)
Flag declarations with default initialization that are assigned to before they are first read.
標(biāo)記包含默認(rèn)初始化操作卻在第一次使用之前賦值的情況。
Flag any complicated computation after an uninitialized variable and before its use.
標(biāo)記任何定義了未初始化變量又在它被使用之前進(jìn)行了復(fù)雜處理的qi
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es22-dont-declare-a-variable-until-you-have-a-value-to-initialize-it-with
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
