Chapter 2 other programming experience
11.1 use const to improve the robustness of functions
See the const keyword, C ++ProgramThe first thought may be the const constant. This is not a good conditioned reflection. If you only know that the constant is defined with const, it is equivalent to using gunpowder only to make firecrackers. The greater charm of const is that it can modify the parameters, return values, and even the definition bodies of functions.
Const is the abbreviation of constant, which means "constant. All things modified by const are protected by force, which can prevent unexpected changes and improve program robustness. Therefore, many c ++ programming book suggestions: "Use const whenever you need ".
11.1.1 use const to modify function parameters
If a parameter is used for output, No matter what data type it is, or whether it uses "pointer transmission" or "reference transmission", it cannot be modified by const, otherwise, the output function is lost.
Const can only modify the input parameters:
* If the input parameter uses "pointer passing", adding const can prevent accidental changes to the pointer and play a protective role.
For example, the stringcopy function:
Void stringcopy (char * strdestination, const char * strsource );
Strsource is the input parameter and strdestination is the output parameter. After the const modifier is added to strsource, if the statements in the function body attempt to modify the content of strsource, the compiler will indicate an error.
If the input parameter uses "value transfer", because the function will automatically generate a temporary variable for copying this parameter, the input parameter does not need to be protected, so do not add const modification.
For example, do not write the void func1 (int x) function as void func1 (const int X ). Similarly, do not write the void func2 (A) function as void func2 (const ). A is the custom data type.
For parameters of non-Internal data types, functions declared like void func (A) are destined to be more efficient.
Bottom. Because a temporary object of type A is generated in the function body for copying parameter A, the construction, replication, and destructor of the temporary object will consume time.
To improve efficiency, you can change the function declaration to void func (A & A) because "reference transfer" only uses the parameter alias and does not need to generate a temporary object. However, the void func (A & A) function has a disadvantage: "reference transfer" may change parameter A, which is not expected. It is easy to solve this problem by adding the const modifier, so the function eventually becomes void func (const A & ).
Similarly, should void func (int x) be rewritten to void func (const Int & X) to improve efficiency? It is completely unnecessary because the internal data type parameters do not have a structure or structure process, and replication is also very fast. The efficiency of "value transfer" and "reference transfer" is almost the same.
The problem is so lingering that I had to summarize the usage of the "const &" modifier input parameter, as shown in the table.
For non-Internal data type input parameters, the "value transfer" method should be changed to "const reference transfer" to improve efficiency. For example, change void func (A) to void func (const A & ).
For internal data type input parameters, do not change the "value transfer" method to "const reference transfer ". Otherwise, the function can not improve the efficiency, but also reduce the comprehensibility of the function. For example, void func (int x) should not be changed to void func (const Int & X ).
Table 11-1-1 "const &" modifies the rules of input parameters
11.1.2 use const to modify the return value of the Function
If the const modifier is added to the return value of a function in the "pointer passing" mode, the content of the function return value (that is, the pointer) cannot be modified. The return value can only be assigned to the same type pointer with the const modifier.
For example, Function
Const char * getstring (void );
The following statement causes a compilation error:
Char * STR = getstring ();
Which of the following statements is true?
Const char * STR = getstring ();
If the function return value adopts the "value transfer mode", because the function copies the return value to an external temporary storage unit, adding the const modifier has no value.
For example, do not write the int getint (void) function as const int getint (void ).
Similarly, do not write function a geta (void) as const A geta (void), where A is the custom data class.
Type.
If the returned value is not an internal data type, it is indeed highly efficient to rewrite function a geta (void) to const A & geta (void. At this time, you must be careful to find out whether the function is to return a copy of an object or only return an alias. Otherwise, the program will fail. See section 6.2 "return value rules ".
There are not many cases where function return values are passed by reference. This method is generally only used in class assignment functions to achieve chained expression.
For example
Class
{...
A & operate = (const A & other); // value assignment function
};
A A, B, C; // A, B, C is the object of
...
A = B = C; // normal chained assignment
(A = B) = C; // The chain assignment is invalid, but valid.
If you add const to the return value of the value assignment function, the content of the returned value cannot be modified. In the preceding example, statement a = B = C is still correct, but statement (a = B) = C is invalid.
11.1.3 const member functions
Any function that does not modify data members should be declared as the const type. If the const member function is accidentally modified or other non-const member functions are called, the compiler will point out an error, which will undoubtedly improve the robustness of the program.
In the following program, the stack-like member function getcount is only used for counting. Logically, getcount should be the const function. The compiler will indicate errors in the getcount function.
class Stack
{< br> Public:
void push (int elem);
int POP (void );
int getcount (void) const; // const member function
PRIVATE:
int m_num;
int m_data [100];
};
Int Stack: getcount (void) const
{
+ + M_num; // compilation error. An attempt is made to modify the data member m_num.
Pop (); // compilation error in an attempt to call a non-const Function
Return m_num;
}
The const member function declaration looks strange: the const keyword can only be placed at the end of the function declaration, probably because it is occupied elsewhere.
11.2 improve program efficiency
The time efficiency of a program refers to the running speed, and the space efficiency refers to the memory or external storage occupied by the program.
Global Efficiency refers to the efficiency taken into account from the perspective of the entire system, and local Efficiency refers to the efficiency taken into account from the perspective of modules or functions.
[Rule 11-2-1] Do not blindly pursue program efficiency, but try to improve program efficiency while satisfying quality factors such as correctness, reliability, robustness, and readability.
[Rule 11-2-2] mainly improves the global efficiency of the program and improves the local efficiency.
[Rules 11-2-3] when optimizing program efficiency, we should first identify the "bottleneck" that limits efficiency.
Important optimization.
[Rule 11-2-4] First optimizes the data structure andAlgorithmAnd then optimize the execution.Code.
[Rules 11-2-5] Sometimes time efficiency and space efficiency may be opposite. At this time, we should analyze the more important and make appropriate trade-offs. For example, you need to spend more memory to improve performance.
[Rules 11-2-6] Do not pursue compact code, because compact Code does not produce efficient machine code.
11.3 some useful suggestions
[11-3-1] Be careful when the operators that are not visually easy to distinguish are written incorrectly.
We often mistakenly write "=" as "= ", such symbols as "│", "&", "<=", and "> =" are also prone to "1 loss" errors. However, the compiler may not automatically point out such errors.
[11-3-2] variables (pointers and arrays) should be initialized in time after they are created to prevent the uninitialized variables from being used as the right value.
[11-3-3] Be careful when the initial value or default value of the variable is incorrect or the accuracy is insufficient.
[11-3-4] beware of data type conversion errors. Try to use explicit data type conversion (to let people know what happened), and avoid the compiler from quietly performing implicit data type conversion.
[11-3-5] beware of overflow or underflow of variables. The subscript of the array is out of bounds.
[11-3-6] Be careful if you forget to write the error handling program, and be careful if the error handling program itself is incorrect.
[11-3-7] beware of file I/O errors.
[11-3-8] avoid writing highly skillful code.
[11-3-9] Do not design a comprehensive and flexible data structure.
[11-3-10] if the quality of the original code is good, try to reuse it as much as possible. But do not fix bad code and rewrite it.
[11-3-11] Try to use standard library functions. Do not "invent" existing library functions.
[11-3-12] Do not use variables closely related to specific hardware or software environments.
[11-3-13] set the compiler option to the strictest state.
[11-3-14] if possible, use tools such as PC-lint and logiscript for code review.
references
[Cline] MARSHALL p. cline and Greg. lomow, C ++ FAQs, Addison-Wesley, 1995
[Eckel] Bruce Eckel, thinking in C ++ (C ++ programming ideology, Liu zongtian, etc ), mechanical Industry Press, 2000
[Maguire] Steve Maguire, writing clean code (translated by the essence of programming and Jiang jingbo), Electronic Industry Press,
1993
[Meyers] Scott Meyers, valid tive C ++, Addison-Wesley, 1992
[Murry] Robert B. murry, C ++ strategies and tactics, Addison-Wesley, 1993