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

网友投稿 922 2022-10-13

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

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

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

ES.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 CaMeLcAsEvArIaBlEif (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​​

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:程序员英语进阶
下一篇:FxBlog- 开源博客程序
相关文章

 发表评论

暂时没有评论,来抢沙发吧~