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

共 1750字,需浏览 4分钟

 ·

2020-04-25 23:21

de2ea38ebb644e8f1465bc471d83ce77.webp

ES.22: Don't declare a variable until you have a value to initialize it with

DS.22:没有合适的初始值就不要定义变


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(反面示例)

string s;
// ... no use of s here ...
s = "what a waste";
Example, bad(反面示例)
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




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

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

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



浏览 44
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报