Chapter 2 other programming experience11.1 use const to improve the robustness of functionsWhen you see the const keyword, C ++ programmers may first think of const constants. 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 parametersIf 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 input parameters: u if the input parameters adopt "pointer transfer", adding const can prevent accidental changes to the pointer and play a protective role. For example, the stringcopy function is void stringcopy (char * strdestination, const char * strsource), where 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. U 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 have relatively low efficiency. 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 have to summarize the usage of the "const &" modifier input parameters, as shown in table 11-1-1.
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 parameters11.1.2 use const to modify the return value of the FunctionU if const 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 returned value can only be assigned to the same type pointer with const modifier. For example, the function const char * getstring (void); the following statement will show a compilation error: char * STR = getstring (); the correct usage is const char * STR = getstring (); u if the return value of a function adopts the "value transfer mode", because the function copies the return value to an external temporary storage unit, adding 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 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 ". The Return Value of the U function is not used in the case of "reference transfer". This method is generally only used in the class assignment function to implement chained expression. For example, Class {... A & operate = (const A & other); // value assignment function}; A, B, C; // A, B, C is the object of... A = B = C; // normal chained value assignment (A = B) = C; // an abnormal chained value assignment. If it is valid, add the return value of the value assignment function to const, 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 functionsAny 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 {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. The attempt to call the 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 efficiencyThe 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. LRule 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. L[Rule 11-2-2]It focuses on improving the overall efficiency of the program, supplemented by improving the local efficiency. LRules 11-2-3]When optimizing the program's efficiency, you should first identify the "bottleneck" that limits the efficiency, and do not optimize the program in irrelevant aspects. LRule 11-2-4]Optimize the data structure and algorithm before optimizing the Execution Code. LRule 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. LRules 11-2-6]Do not pursue compact code because compact Code cannot generate efficient machine codes.11.3 some useful suggestions2.[11-3-1 is recommended.]Be careful when writing errors occur for operators that are visually hard to distinguish. We often mistakenly write "=" as "= ", symbols such as "|", "&", "<=", and "> =" are also prone to "1 loss" errors. However, the compiler may not automatically point out such errors. 2.[11-3-2 is recommended.]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. 2.[11-3-3 is recommended.]Be careful when the initial value or default value of the variable is incorrect or the accuracy is insufficient. 2.[Recommended 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. 2.[11-3-5 is recommended.]Beware of overflow or underflow of variables, and the subscript of the array is out of bounds. 2.[11-3-6 is recommended.]Be careful if you forget to write the error handling program. Be careful if the error handling program itself is incorrect. 2.[11-3-7 is recommended.]Beware of file I/O errors. 2.[11-3-8 is recommended.]Avoid writing highly skillful code. 2.[11-3-9 is recommended.]Do not design a comprehensive and flexible data structure. 2.[11-3-10 is recommended.]If the original code quality is good, try to reuse it. But do not fix bad code and rewrite it. 2.[11-3-11 is recommended.]Try to use standard library functions. Do not "invent" existing library functions. 2.[Recommended 11-3-12]Do not use variables that are closely related to specific hardware or software environments. 2.[Recommended 11-3-13]Set the compiler selection item to the strictest possible state. 2.[Recommended 11-3-14]If possible, use tools such as PC-lint and logist for code review.References[Cline]Marshall P. Cline and Greg a. lomow, C ++ FAQs, Addison-Wesley, 1995[Eckel]Bruce Eckel, thinking in C ++ (C ++ programming ideology, translated by Liu zongtian), Mechanical Industry Press, 2000[Maguire]Steve Maguire, writing clean code (essence of programming, translated by 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[Summit]Steve summit, C Programming FAQs, Addison-Wesley, 1996 |
|
|