"Effective C + +"
Clause 26: Delay the occurrence of variable definitions whenever possible
as long as you define a variable and its type has a constructor and destructor, then when the control flow of the program reaches the variable definition, you will have to bear the cost of the construction, and when the variable leaves the scope, you have to inherit the composition. Even if the variable is not used at all, it still costs a lot, so you should try to avoid it.
For an understanding of " delaying as long as possible ":
You should not just postpone the definition of a variable until the first moment of the variable is used, even try delaying the definition until you can give it an initial argument. If you do this, you can avoid not only constructing (refactoring) non-essential objects, but also avoiding meaningless default construction behavior. In a deeper layer, the variables are initialized with the "initial value of obvious meaning" and the purpose of the variable is also attached.
How do you choose in the loop?
Method A: Defined in the loop out widget w;for (int i = 0;i < n; i++) {w = depends on a value of I; ...} Method B: Defined in the loop for (int i = 0; i < n; i++) {Widget W (depending on a value of i); ...}
Analysis:
Procedure A: A constructor + 1 destructors + N assignment operations
Procedure B:n A constructor + N destructors
If an assignment cost of classes is less than a set of construction + analysis composition, practice A is generally more efficient. Especially when the value of n is very large. Otherwise, b might be better.
In addition, procedure a causes the scope of the name W to be larger than procedure B, which sometimes conflicts with the understandable nature of the program and ease of maintenance. So unless (1) You know the cost of the assignment is lower than the "construct + destructor", (2) you are dealing with highly efficient parts of the code. Otherwise you should choose procedure B.
Summary :
Postpone the occurrence of variable definitions as much as possible. This can increase the clarity of the program and improve the efficiency of the program.
2016-11-07 21:33:24
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1870423
"Effective C + +" clause 26: Delay the occurrence of variable definitions as far as possible