c++ lambda表达式_C++核心准则ES.28: 使用lambda表达式进行变量的复杂初始化

8cf3d9237d785396544dd23be65f69ea.png

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


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

e898eb5c58b7df15600dcec2846cfdac.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值