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";
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
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es22-dont-declare-a-variable-until-you-have-a-value-to-initialize-it-with