< high quality C + + Programming Guide >

Source: Internet
Author: User
Tags case statement compact constant definition error handling function definition naming convention

Chapter 1th Structure of the document
1. Copyright and version of the statement
2. Structure of the header file
"Rule 1-2-1" in order to prevent the header file from being repeatedly referenced, a preprocessing block should be generated with the IFNDEF/DEFINE/ENDIF structure.
"Rule 1-2-2" uses the #include <filename.h> format to refer to the header files of the standard library (the compiler will start searching from the standard library directory).
"Rule" uses the #include "filename.h" format to refer to the header file of a nonstandard library (the compiler will start searching from the user's working directory).
The "recommendation 1-2-1" header file contains only "declarations" and no "definitions".
"Recommendation 1-2-2" does not advocate the use of global variables, try not to appear in the header file such as extern int value declarations.
3. Define the structure of the file
4. The role of the header file
5. Directory Structure

The 2nd chapter the layout of the program
1. Blank line
"Rule 2-1-1" adds a blank line after each class declaration and after the end of each function definition.
"Rule 2-1-2" in a function body, logical IBO on the closely related statements are not empty lines, other places should be separated by empty lines.
2. Line of code
The "rule 2-2-1" line of code only does one thing, such as defining only a variable, or just writing a single statement.
"Rule 2-2-2" if, for, while, do, and so on the statement from the row, the execution statement must not follow immediately thereafter.
Recommendation 2-2-1 initializes the variable (nearest principle) as much as possible while defining the variable.
3. Spaces within the line of code
Leave a blank after the "rule 2-3-1" keyword.
Do not leave spaces after the "rule 2-3-2" function name, followed by the left Parenthesis ' ('), as distinguished from the keyword.
"Rule 2-3-3" ' (' back immediately, ') ', ', ', '; ' Move forward, followed by a blank space.
"Rule 2-3-4" ', ' after which you want to leave spaces, such as function (x, y, z).
"Rule 2-3-5" assignment operator, comparison operator, arithmetic operator, logical operator, bit field operator, such as "=", "+ =" ">=", "<=", "+", "*", "%", "&&", "| |", "<<", "^" Wait for the two-dollar operator before and after the space should be added.
"Rule 2-3-6" unary operators such as "!", "~", "+ +", "--", "&" (address operator) are not preceded by spaces.
"Rule 2-3-7" such as "[]", ".", "and" such operators before and after the space is not added.
"Recommendation 2-3-1" for statements with long expressions and if statements, some spaces, such as for (i=0; i<10; i++) and if ((a<=b) && (C<=d)), can be suitably removed for the sake of compactness.
4. Align
The delimiter ' {' and '} ' of the ' rule 2-4-1 ' program should have a single row and be in the same column, with the statement that references them left-justified.
Code blocks within the "rule 2-4-2" {} are left-aligned at the right-hand side of ' {'.
5. Long line splitting
The maximum length of the "rule 2-5-1" code line should be within 70 to 80 characters.
The "rule 2-5-2" long expression is split into a new line at the low-priority operator, and the operator is placed at the top of the new line (so that the operator is highlighted).
6. The position of the modifier
"Rule 2-6-1" should have modifiers * and & close to variable names.
7. Notes
The "rule 2-7-1" comment is a "hint" to the code, not a document. The notes in the program are not distracting and the comments are too many to dazzle. There are fewer tricks to note.
"Rule 2-7-2" if the code is clear, you do not have to comment.
The "rule 2-7-3" side writes the code side comment, modifies the code simultaneously modifies the corresponding annotation, guarantees the annotation and the code consistency. Comments that are no longer useful are to be deleted.
The "rule 2-7-4" comment should be accurate and understandable, preventing comments from being two semantic.
"Rule 2-7-5" try to avoid abbreviations in comments, especially those that are not commonly used.
The location of the "rule 2-7-6" comment should be adjacent to the code described, which can be placed above or to the right of the code and not placed below.
"Rule 2-7-8" when the code is relatively long, especially when there are multiple nesting, it should be at the end of some paragraphs to be released, easy to read.
8. Layout of Classes
There are two main ways to layout a class:
(1) write the private type of data in front, and write the function of the public type behind. Programmers who use this layout argue that the design of the class is "data-centric" and focuses on the internal structure of the class.
(2) Write the function of the public type in front, and write the data of the private type behind. Programmers in this format argue that the design of a class is "behavior-centric", with a focus on what interfaces (or services) a class should provide.

3rd Chapter naming rules
1. Common rules
The "rule 3-1-1" identifier should be intuitive and can be spelt, and hopefully the text will be understood without having to "decode" it.
The length of the "rule 3-1-2" identifier should conform to the "Min-length && max-information" principle
The rule 3-1-3 naming convention is as consistent as possible with the style of the operating system or development tool being used.
A similar identifier that is only case sensitive is not present in the "Rule 3-1-4" program.
The exact same local and global variables are not present in the "Rule 3-1-5" program, although the scope of the two is different and there is no syntax error, but it can be misleading.
The name of the "rule 3-1-6" variable should use "noun" or "adjective + noun".
The name of the "rule 3-1-7" global function should use "verb" or "verb + noun" (moving-in phrase).
"Rule 3-1-8" uses the correct antonyms group to name variables with mutually exclusive meanings or functions that have opposite actions.
"Recommendation 3-1-1" Try to avoid the number of digits in the name, such as Value1,value2, unless the number is logically required. This is to prevent the programmer from slacking off, and not to give up the name to make meaningless names.
2. Simple Windows Application Naming conventions
The "rule 3-2-1" class name and function name are combined with words that begin with uppercase letters.
The "rule 3-2-2" variable and argument are combined with a word that starts with a lowercase letter.
The "rule 3-2-3" constants are all capitalized letters, with underscores for dividing words.
The "rule 3-2-4" static variable is prefixed with S_ (representing static).
"Rule 3-2-5" if a global variable is required, prefix the global variable with g_ (representing global).
The data members of the "rule 3-2-6" class are prefixed with m_ (for member), which prevents the data member from having the same name as the parameter of the member function.
"Rule 3-2-7" to prevent conflicts in some of the identifiers and other repositories in a software library, you can add prefixes that reflect the nature of the software for a variety of identifiers.
3. Simple UNIX Application Naming conventions

4th expression and basic statement
1. Operator precedence
"rule 4-1-1" if the operators in the line of code are more numerous, parentheses determine the order in which the expressions are operated, avoiding the use of the default precedence.
2. Compound expression
"rule 4-2-1" do not write complex expressions that are too complicated.
Rule 4-2-2 do not have multi-purpose compound expressions.
Rule 4-2-3 do not confuse a compound expression in a program with a "true mathematical expression".
3.if Statement
"rule 4-3-1" does not compare Boolean variables directly with True, false, or 1, 0. The
rule 4-3-2 should use the integer variable with "= =" or "! = "Compare directly with 0. The
"rule 4-3-3" cannot use a floating-point variable with "= =" or "! = "Compared to any number. The
"rule 4-3-4" should use the pointer variable "= =" or "! = "Compared to NULL.
4. Efficiency of the Loop statement
"recommendation 4-4-1" in multiple loops, if possible, the longest loop should be placed in the outermost layer, and the shortest loop will be placed on the outer layer to reduce the number of times the CPU crosses the loop.
Recommendation 4-4-2 If there is a logical judgment in the loop and the number of loops is large, it is advisable to move the logical judgment out of the loop body. The
5.for statement's loop control variable
"rule 4-5-1" cannot modify the loop variable in the For loop body to prevent the for loop from losing control.
Recommendation 4-5-1 recommends that the value of the loop control variable for the For statement be used as the "half open half closed interval" notation.
6.switch Statement
"rule 4-6-1" do not forget to break at the end of each case statement, otherwise it will cause multiple branches to overlap (unless multiple branches are intentionally overlapping).
Rule 4-6-2 do not forget the last default branch.
7.goto Statements

5th Chapter Constants
1. Why constants are required
If you do not use constants, fill in the numbers or strings directly in the program:
The readability (comprehensible) of the program becomes worse;
Enter the same number or string in many places of the program without writing errors;
If you want to modify a number or string, it will change in many places, both cumbersome and error prone.
"Rule 5-1-1" try to use meaning-intuitive represented to represent numbers or strings that will appear more than once in a program.
2.const and #define的比较
Const Benefits:
Const constants have data types, and macro constants do not have data types;
Some integrated debugging tools can debug const constants, but cannot debug macro constants.
"Rule 5-2-1" uses only const constants in C + + programs without using macro constants, that is, const constants completely replace macro constants.
3. Constant definition Rules
"Rule 5-3-1" need to be exposed to the constant in the header file, do not need to be exposed to the external constants in the definition file header.
"Rule 5-3-2" if a constant is closely related to other constants, you should include this relationship in your definition, rather than giving some orphaned values.
4. Constants in a class
Use enumerated constants in the class to implement constants that are constant throughout the class.

6th Chapter Function Design
1. Rules for parameters
The "rule 6-1-1" parameter should be written in a complete, not easy-to-write parameter type and omit the parameter name. If the function has no arguments, it is filled with void.
The "rule 6-1-2" parameter should be named appropriately and the order should be reasonable.
"Rule 6-1-3" if the parameter is a pointer and is only used for input, you should add a const to the type to prevent the pointer from being accidentally modified in the function body.
"Rule 6-1-4" if the input parameter passes the object as a value, it should be passed in a "Const &" way, which saves the construction and destruction of the temporary object, thus improving efficiency.
"Recommendation 6-1-1" to avoid the function has too many parameters, the number of parameters as far as possible to control within 5.
"Recommendation 6-1-2" Try not to use parameters of type and number uncertainties.
2. Rules for returning values
"Rule 6-2-1" do not omit the type of the return value.
The name of the "rule 6-2-2" function is semantically non-conflicting with the return value type.
"Rule 6-2-3" do not mix the normal values and the error flags back together. The normal value is obtained with an output parameter, and the error flag is returned with a return statement.
"Recommendation 6-2-1" Sometimes the function does not originally need to return a value, but in order to increase flexibility, such as support chain expression, you can append the return value.
"Recommendation 6-2-2" If the return value of a function is an object, there are occasions when "pass by reference" replaces "value passing" to improve efficiency. Some situations can only be passed with "value" and not "referenced", otherwise an error occurs.
3. Rules for internal implementation of functions
"Rule 6-3-1" in the function body "entrance", the validity of the parameters are checked.
"Rule 6-3-2" checks the correctness and efficiency of the return statement at the "exit" of the function body.
If the function return value is an object, consider the efficiency of the return statement.
Return String (S1 + s2), which means "create a temporary object and return it." The compiler creates and initializes the temporary object directly to the external storage unit, eliminating the cost of copying and destruction and improving efficiency.
String Temp (s1 + s2); return temp; means "first create a local object temp and return its results"
4. Other recommendations
The "Suggest 6-4-1" function has a single function and does not design multipurpose functions.
The "recommendation 6-4-2" function body is small in size, as much as possible within 50 lines of code.
"Recommendation 6-4-3" try to avoid functions with "memory" function.
"Recommendation 6-4-4" Not only checks the validity of input parameters, but also examines the validity of variables entering the function body through other means, such as global variables, file handles, and so on.
The return value of "recommendation 6-4-5" for error handling must be clear, making it difficult for users to ignore or misunderstand the error condition.
5. Using assertions
"Rule 6-5-1" uses assertions to catch illegal situations that should not occur. Do not confuse the difference between the illegal situation and the wrong situation, the latter being inevitable and must be dealt with.
"Rule 6-5-2" at the entrance of the function, use assertions to check the validity of the parameters (legitimacy).
"Recommendation 6-5-1" When writing a function, repeat the examination and ask: "What assumptions do I intend to make?" Once the assumptions have been determined, the assumptions are checked using assertions.
"Recommendation 6-5-2" The general textbook encourages programmers to make error-proof designs, but keep in mind that this style of programming may conceal errors. If the "impossible" thing does happen when the error-proof design is in progress, use an assertion to alarm.
6. Comparison of references to pointers

7th Chapter Memory Management
1. How to Allocate memory
Allocate from a static storage area.
Created on the stack.
Allocated from the heap, also known as dynamic memory allocation.
2. Common memory errors and their countermeasures
After "rule 7-2-1" has requested memory with malloc or new, you should immediately check that the pointer value is NULL. Prevents the use of memory with a pointer value of NULL.
"Rule 7-2-2" do not forget to assign an initial value to both arrays and dynamic memory. Prevents memory that is not initialized from being used as the right value.
"Rule 7-2-3" avoids array or pointer subscript out of bounds, especially beware of "more than 1" or "1 less" operations.
"Rule 7-2-4" the request and release of dynamic memory must be paired to prevent a memory leak.
After "rule 7-2-5" has freed memory with free or delete, the pointer is immediately set to NULL to prevent the "wild pointer" from being produced.
3. Comparison of pointers to arrays
Arrays are either created in a static store (such as a global array) or created on a stack.
When an array is passed as an argument to a function, the array is automatically degraded to a pointer of the same type.
4. The pointer parameter is how the memory is passed
If the parameter of the function is a pointer, do not expect to use the pointer to apply dynamic memory.
The compiler always makes a temporary copy of each parameter of the function, the copy of the pointer parameter P is _p, and the compiler causes _p = p.
5.free and delete What's wrong with the pointer?
6. Will the dynamic memory be released automatically?
When the pointer dies, it does not mean that the memory it refers to is automatically freed.
The memory is freed and does not indicate that the pointer is extinct or is a null pointer.
7. Eliminate "wild hands"
Reason:
Pointer variables are not initialized.
Pointer P is not set to null after the free or delete.
Pointer manipulation goes beyond the scope of the variable.
8. Why New/delete with Malloc/free?
New/delete is not a library function, it is a operator.
Operator NEW: Dynamic memory allocation and initialization can be done.
Operator Delete: The ability to clean up and free memory work.
9. What about memory exhaustion?
(1) Determine if the pointer is null, and if so, terminate the function with the return statement immediately.
(2) Determine if the pointer is null, and if so, use Exit (1) to terminate the entire program operation immediately.
(3) Set exception handling functions for new and malloc
Key points of use of 10.malloc/free
Key points of use of 11.new/delete
12. Some experience
The more you fear the pointer, the more you use the pointer. Not using pointers correctly is definitely not a qualified programmer.
The habit of "using the debugger to track programs" must be developed in order to discover the nature of the problem.

8th advanced Features of C + + functions
1. The concept of function overloading
distinguishes overloaded functions by only arguments and not by the difference in return value types.
What happens if a C + + program calls a C function that has already been compiled? The
assumes that a C function is declared as follows:
void foo (int x, int y);
The function is compiled by the C compiler in the library with the name _foo, while the C + + compiler produces names like _foo_int_int to support function overloading and type-safe connections. The C + + program cannot directly invoke the function because the compiled name is different. C + + provides a C connection to swap the specified symbol extern "C" to resolve this problem.
Beware of implicit type conversions causing overloaded functions to produce ambiguity
2. Overloading, overwriting, and hiding of member functions
3. Default value of the parameter
the default value of the rule 8-3-1 parameter can only appear in the declaration of the function, not in the definition body.
Rule 8-3-2 If the function has more than one argument, the parameter can only be asked by default, otherwise it will cause the function call statement to absurd.
4. Operator overloading
Operator rule
All unary operators recommend overloading as member functions
= () []-only overloads for member functions
+ = =/= *= &= |= ~=%= >>= <<= recommended overloads For member functions
all other operators recommend overloading to global functions
5. Function inline
Caution inline:
If the code in the function body is longer, using inline will result in a higher memory consumption cost.
If there is a loop in the function body, the time to execute the function body code is greater than the cost of the function call.
6. Some experiences

The 9th Chapter class's constructors, destructors and assignment functions
1. The origin of constructors and destructors
2. Initialization table of constructors
Constructor initialization table usage rules:
If the class has an inheritance relationship, the derived class must call the constructor of the base class in its initialization table.
Const constants of a class can only be initialized in the initialization table.
Member objects of non-intrinsic data types should be initialized with an initialization table to achieve greater efficiency.
3. Sequence of construction and destruction
The order in which member objects are initialized is completely unaffected by their order in the initialization table, determined only by the order in which the member objects are declared in the class.
4. Example: constructor and destructor for class string
5. Do not underestimate copy constructors and assignment functions
If you do not actively write copy constructors and assignment functions, the compiler will automatically generate default functions in a "bit copy" manner. If the class contains pointer variables, then the two default functions imply an error.
A copy constructor is called when an object is created, and an assignment function can only be called by an object that already exists.
6. Example: copy constructor and assignment function for class string
7. Lazy way to handle copy constructors and assignment functions
You simply declare copy constructors and assignment functions as private functions without writing code.
8. How to implement the basic functions of a class in a derived class
When writing assignment functions for derived classes, be careful not to forget to re-assign values to the data members of the base class.
9. Some experience

Chapter 10th inheritance and combination of classes
1. Inheritance
"Rule 10-1-1" if Class A and Class B are irrelevant, it is not possible to have B inherit the functionality and properties of a in order to make B more functional.
"Rule 10-1-2" if logically B is "a" (a kind of) of a, then B is allowed to inherit the functions and properties of a.
2. Combination
"Rule 10-2-1" if logically A is a "part" of B, then B is not allowed to derive from a, but to combine B with a and other things.

11th Chapter Other Programming experience
1. Using const to improve the robustness of functions
Const can modify the function's arguments, return values, and even the definition body of the function. The const-modified items are protected against accidental changes and can improve the robustness of the program.
For input parameters of non-intrinsic data types, the "value passing" method should be changed to "const reference passing" in order to improve efficiency. For example, void Func (a a) is changed to void func (const a &a).
For input parameters of an internal data type, do not change the "value passing" method to "Const reference pass". Otherwise, it can not achieve the purpose of improving efficiency, but also reduces the comprehensible function. For example, void func (int x) should not be changed to void func (const int &x).
Any function that does not modify a data member should be declared as a const type.
2. Improving the efficiency of the process
"Rule 11-2-1" do not blindly pursue the efficiency of the program, should be satisfied with the correctness, reliability, robustness, readability and other quality factors under the premise of trying to improve the efficiency of the program.
"Rule 11-2-2" to improve the overall efficiency of the program-based, improve local efficiency as a supplement.
"Rule 11-2-3" in optimizing the efficiency of the program, you should first identify the "bottleneck" to limit efficiency, do not optimize in the insignificant.
"Rule 11-2-4" optimizes the data structure and algorithm before optimizing the execution code.
"Rule 11-2-5" sometimes time efficiency and space efficiency may be antagonistic, at this time should be analyzed which is more important, make the appropriate compromise.
"Rule 11-2-6" do not pursue compact code, because compact code does not produce efficient machine code.
3. A number of useful recommendations
"Recommendation 11-3-1" Beware of writing errors on visually indistinguishable operators.
The "Recommended 11-3-2" variables (pointers, arrays) should be initialized immediately after they are created to prevent the uninitialized variables from being used as rvalue values.
"Recommendation 11-3-3" Beware of variable initial value, default error, or insufficient precision.
"Recommendation 11-3-4" Beware of errors in data type conversions. Try to use explicit data type conversions (let people know what's going on), and avoid letting the compiler quietly make implicit data-type conversions.
"Recommendation 11-3-5" Beware of variable overflow or underflow, array subscript out of bounds.
"Recommendation 11-3-6" Beware of forgetting to write error handlers, and beware of errors in the error handlers themselves.
"Recommendation 11-3-7" Beware of file I/O errors.
"Recommendation 11-3-8" avoids writing very high-skilled code.
"Recommendation 11-3-9" Do not design a data structure that is exhaustive and flexible.
"Recommendation 11-3-10" If the original code quality is better, try to reuse it. But don't fix bad code, you should rewrite it.
"Recommendation 11-3-11" Use standard library functions as much as possible, and do not "invent" library functions that already exist.
"Recommendation 11-3-12" Try not to use variables that are closely related to a specific hardware or software environment.
"Recommendation 11-3-13" Sets the compiler's selection to the strictest state.
"Recommendation 11-3-14" Use tools such as Pc-lint and Logiscope for code review, if possible.

< high quality C + + Programming Guide >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.