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
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!