前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则DS.22:没有合适的初始值就不要定义变量

C++核心准则DS.22:没有合适的初始值就不要定义变量

作者头像
面向对象思考
发布2020-04-26 12:08:56
4730
发布2020-04-26 12:08:56
举报
文章被收录于专栏:C++核心准则原文翻译

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.

可读性。限制变量可用的范围。不要冒设定前使用的风险。初始化通常比赋值更高效。

Example, bad(反面示例)

代码语言:javascript
复制
string s;
// ... no use of s here ...
s = "what a waste";
Example, bad(反面示例)
代码语言:javascript
复制
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存在一个代价不高的默认初始化,这段代码问题不大。否则,程序员可能特别想知道是否通过条件迷宫的所有路径都被覆盖了。如果不是,我们就遇到了一个设定前使用的错误。这是一个维护陷阱。

For initializers of moderate complexity, including for const variables, consider using a lambda to express the initializer; see ES.28.

对于中等复杂度初始化器,包括常量,考虑使用lambda表达式实现。参见ES.28

Enforcement(实施建议)
  • Flag declarations with default initialization that are assigned to before they are first read.
  • 标记包含默认初始化操作却在第一次使用之前赋值的情况。
  • Flag any complicated computation after an uninitialized variable and before its use.
  • 标记任何定义了未初始化变量又在它被使用之前进行了复杂处理的qi

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es22-dont-declare-a-variable-until-you-have-a-value-to-initialize-it-with

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-04-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example, bad(反面示例)
  • Enforcement(实施建议)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档