C++核心準(zhǔn)則ES.28: 使用lambda表達(dá)式進(jìn)行變量的復(fù)雜初始化,特別...

ES.28: Use lambdas for complex initialization, especially of?const?variables
ES.28: 使用lambda表達(dá)式進(jìn)行變量的復(fù)雜初始化,特別是常量變量
Reason(原因)
It nicely encapsulates local initialization, including cleaning up scratch variables needed only for the initialization, without needing to create a needless non-local yet non-reusable function. It also works for variables that should be?const?but only after some initialization work.
這種方式漂亮地封裝了局部初始化,包括清理只在初始化過程中需要的臨時(shí)變量,而不是生成一個(gè)不必要的非局部但卻不會(huì)重用的函數(shù)。它也可以用于應(yīng)該是常量但卻需要某些初始化處理的變量初始化.
Example, bad(反面示例)
widget x; // should be const, but:
for (auto i = 2; i <= N; ++i) { // this could be some
x += some_obj.do_something_with(i); // arbitrarily long code
} // needed to initialize x
// from here, x should be const, but we can't say so in code in this style
Example, good(范例)
const widget x = [&]{
widget val; // assume that widget has a default constructor
for (auto i = 2; i <= N; ++i) { // this could be some
val += some_obj.do_something_with(i); // arbitrarily long code
} // needed to initialize x
return val;
}();
Example(示例)
string var = [&]{
if (!in) return ""; // default
string s;
for (char c : in >> c)
s += toupper(c);
return s;
}(); // note ()
If at all possible, reduce the conditions to a simple set of alternatives (e.g., an?enum) and don't mix up selection and initialization.
如果可能,將條件壓縮為一個(gè)由可選項(xiàng)(例如枚舉)構(gòu)成的簡(jiǎn)單集合并且不要將選擇和初始化混用。
Enforcement(實(shí)施建議)
Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it.
很難。最好是啟發(fā)式的。尋找沒有初始化的變量的后面跟著為其賦值的循環(huán)的情況.
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es28-use-lambdas-for-complex-initialization-especially-of-const-variables
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
