Introduction
Every construction and destruction costs, so when we design the code, we should consider the cost of construction and destruction as much as possible.
The first section delays implementation
Consider the following code:
1 voidEncryptstring&s);2 stringEncryptpassword (Conststing&password) {3 stringencrypted;4 if(xxxxx) {5 ThrowLogic_error ("xxxxxx");6 } 7encrypted =password;8 Encrypt (encrypted);9 Ten returnencrypted; One}
In the above code, encrypted will not be used if it throws an exception after it has been created. But we also have to pay for his structure and composition.
We can consider changing to this:
1 voidEncryptstring&s);2 stringEncryptpassword (Conststing&password) {3 if(xxxxx) {4 ThrowLogic_error ("xxxxxx");5 } 6 string encrypted;7encrypted =password;8 Encrypt (encrypted);9 Ten returnencrypted; One}
This avoids the destructor and construction problems above, but the default constructor of string is called on line 6th.
So we can consider revising it again:
1 voidEncryptstring&s);2 stringEncryptpassword (Conststing&password) {3 if(xxxxx) {4 ThrowLogic_error ("xxxxxx");5 } 6 stringencrypted (password);//use copy constructors to define and initialize7 Encrypt (encrypted);8 9 returnencrypted;Ten}
You can avoid the unnecessary default construction behavior.
The second section loops
The code is written a lot, the following two situations occur:
1.
1 Widget W; 2 for (int0; i < n; i++) {3 w = ... 4 ....... 5 }
2.
1 for (int0; i < n; i++) {2 Widget w (...); 3 ....... 4 }
Method 1: A constructor + 1 destructors +n an assignment operation
Method 2:n Constructor +n destructor function
If one of the assignment costs of class is less than a set of construction + analysis composition, then procedure A is more efficient. Otherwise b might be better.
Summary
1. 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.
[Effective C + +--026] Delay the occurrence of variable definitions whenever possible