C++核心準則ES.28: 使用lambda表達式進行變量的複雜初始化,特別是常量變量

ES.28: Use lambdas for complex initialization, especially of const variables

ES.28: 使用lambda表達式進行變量的複雜初始化,特別是常量變量

 

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.

這種方式漂亮地封裝了局部初始化,包括清理只在初始化過程中需要的臨時變量,而不是生成一個不必要的非局部但卻不會重用的函數。它也可以用於應該是常量但卻需要某些初始化處理的變量初始化.

 

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.

如果可能,將條件壓縮爲一個由可選項(例如枚舉)構成的簡單集合並且不要將選擇和初始化混用。

 

Enforcement(實施建議)

Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it.

很難。最好是啓發式的。尋找沒有初始化的變量的後面跟着爲其賦值的循環的情況.

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es28-use-lambdas-for-complex-initialization-especially-of-const-variables

 


 

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

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

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