天天看点

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 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​​

继续阅读