First, the header file
1. #define的保护: All header files should use # define to prevent header files from being multi-contained (multiple inclusion), naming the format:
<project>_<path>_<file>_h_
To ensure uniqueness, the name of the header file should be based on the full path of the source code tree in which the project is located.
2. Header file Dependency: Use the predecessor declaration (forward declarations) to minimize the number of # include in. h files. Avoid domino effects
e.g. the header file uses the class file, but does not need to access the file declaration, the header file only needs to be pre-declared class file; No # include "File/bash/file.h" is required.
How do I use Class Foo in a header file without having to access the definition of the class?
1) Declare the data member type as foo* or foo &;
2) The function of the parameter and the return value type Foo is only declared (but does not define the implementation);
3) The type of a static data member can be declared as Foo, because the definition of a static data member is outside the class definition.
Sometimes it makes more sense to use pointer members instead of object members, however, this can reduce code readability and execution efficiency. If you just want to include the header file, do not replace it well.
3. Inline function: The function is defined as an inline function only if it is only 10 rows or less. For destructors to be treated with caution, destructors tend to look longer than their surface because there are some implicit members and base class destructors, if any, that are called! In addition, inline those functions that contain loops or switch statements are not worth the candle, unless in most cases these looping languages are never executed. The definition of a complex inline function should be placed in a header file with the suffix-inl.h.
4. Order of function parameters: input parameters in front, output parameters after (input and output). Input parameters are passed with a value pass or a constant reference, and the output parameters are passed using a very few pointers.
5. Include the name and order of the file: C library, C + + library, other library's. h, in-project. H. Avoid hiding dependencies.
Second, scope
1. Namespaces: In. cc files, advocating the use of unnamed namespaces, where the name of the appliance name namespace can be based on the project or path name, without using the use indicator.
2. Nested classes: When exposing nested classes as part of an interface, although they can be persisted directly in the global scope, it is preferable to place the declaration of the nested class in the namespace. Nested classes can only be pre-declared in the definition of a nested class. Do not define nested classes as public unless they are part of an interface.
3. Non-member functions, static member functions, and global functions: Use a non-member function or a static member function in the namespace to avoid using global functions.
1) Non-member functions should not be dependent on external variables and should be placed in a namespace as much as possible. Instead of creating a class simply to encapsulate several static member functions that do not share any static data, use a namespace.
2) functions defined in the same compilation unit, which are called directly by other compilation units, may introduce unnecessary coupling and connection dependencies, which are particularly sensitive to static member functions, either to consider extracting into a new class or to place a function in the namespace of a stand-alone library.
3) If you do need to define a non-member function and only use it in a. cc file, you can restrict its scope with no namespace or static association.
4. Local variables: Place the function variable as far as possible into the smallest scope and initialize it when declaring the variable.
5. Global variables: Class type Global variables are forbidden, the built-in type of global variables are allowed, of course, the multi-threaded code in the very number of global variables is also forbidden, never use function return value to initialize the global variables.
1) If you must use a global variable of class type, use single-piece mode
2) for global string constants, use C-style strings instead of STL strings;
3) Static member variables are treated as global variables, so they cannot be class types!
Summary: The use of scopes, in addition to the name of pollution, readability, mainly to reduce the coupling, improve the efficiency of compilation and execution.
Third, class
1. Do not make too many logical-related initializations in the constructor, and possibly use the init () method to centralize the initialization of meaningful data.
The problems that are caused by performing operations in the constructor are:
1) The constructor is not easy to report errors and cannot use exceptions.
2) Failure of the operation causes the object initialization to fail, causing an indeterminate state.
3) Call virtual function within the constructor, the call will not be distributed to the subclass implementation, even if there is no subclass implementation, the future is still hidden.
4) If someone creates a global variable of that type (although it violates the rules mentioned in the previous section), the constructor will be called before Main (), potentially destroying the implied assumptions in the constructor.
2. The default constructor provided by the compiler does not initialize the variable, and if other constructors are defined, the compiler is no longer available and requires the encoder to provide the default constructor itself;
3. To avoid implicit conversions, you need to declare a single-argument constructor as explicit (explicit), except that, in rare cases, a copy constructor may not be declared as explicit; A class that is deliberately used as a transparent wrapper for other classes.
4. To avoid copying constructors, the misuse of assignment operations and the compiler's automatic generation, you can now declare it private and do not need to implement it; Use the copy constructor only when you need to copy a class object in your code, and you should use disallow_copy_and_assign when copying.
5. Use structs only when they are used as data sets;
6. Combination > Implementation Inheritance > Interface inheritance > Private inheritance, Subclass overloaded virtual functions also declare the virtual keyword, although the compiler allows not to do so;
7. Avoid the use of multiple inheritance, when used, in addition to a base class containing the implementation, the other accumulation is pure interface;
8. The interface class class name is interface suffix, in addition to provide with the implementation of the virtual destructor, static member functions, the other is pure virtual function, do not define non-static data members, do not provide a constructor, provided, declared as protected;
9. To reduce complexity, try not to repeat the operator, template, standard class in the use of the document description;
10. The access function is generally inline in the header file;
11. Declaration Order:public->protected->private;
12. function body as short as possible, compact, single function.
Iv. features of C + +
1. For smart pointers, safety first, convenient second, as far as possible localized;
2. The reference shape participates in the const, otherwise the pointer parameter is used;
3. The use of function overloading should be clear and easy to read;
4. In view of the easy misuse, the use of default function parameters is forbidden (debatable);
5. Prohibit the use of variable-length arrays;
6. Reasonable use of friends;
7. To facilitate code management, prohibit the use of exceptions (debatable);
8. Prohibit the use of rtti, otherwise re-design code;
9. Use C + + style type conversion, except unit test do not use dynami_cast;
10. Use flow also printf+read/write,it is a problem;
11. Can use the pre-increment/decrement without the post-increment/decrement;
12.const can use, advocate const in front;
13. Use a certain size type, do not use the unsigned type except the bit group;
14. When formatting output and structure alignment, note the system differences between 32 and 64 bits;
15. Try to avoid using macros except string and connection;
16. Integer with 0, real number with 0.0, pointer with null, character (string) with ' "";
17. Use sizeof (varname) instead of sizeof (type);
18. Use only the approved libraries in boost.
Five, naming rules
1. General rules: do not arbitrarily abbreviate. In addition to the function name can be appropriate for the verb, the other naming as far as possible to use clear and understandable nouns;
2. Macros, enumerations, etc. use all caps + underscores;
3. Variables (including classes, struct member variables), files, namespaces, access functions, etc. use all lowercase + underscores, class member variables end with an underscore, and global variables start with g_;
4. Common functions, types (including classes and structs, enumeration types), constants, etc. use case-by-case blending, without underscores;
5. Refer to existing or similar naming conventions.
Vi. notes
1. With regard to the annotation style, many C + + programmers prefer the line comment, the C programmer or the block comment is still a single time, or in the file header large paragraph of the comments when the use of block annotations;
2.TODO;
3. Appropriate indentation;
VII. format
1. Line width in principle not exceeding 80 columns;
2. Try not to use non-ASCII characters, if used, refer to the UTF-8 format (especially under Unix/linux, Windows can consider wide characters), try not to string constants into the code, such as independent out of the resource file, this is not only a style problem;
3.unix/linux under the unconditional use of space, msvc words using tab also understandable;
4. Function parameters, logical conditions, initialization list, or all parameters and function names on the same line, or all parameters side by branch;
5. Except that the opening brace of the function definition can be placed outside the beginning of the line, including function/class/struct/enum declaration, the opening brace of various statements at the end of the row, all the closing curly braces are independent;
6../-> operator before and after the space,*/& do not leave before and after, one can, on the left to the right according to the preferences of everyone;
7. Preprocessing directives/namespaces do not apply additional indentation, class/struct/enum/function/statement using Indentation;
8. Initialize with = or () According to personal preference, unity is good;
9.return do not add ();
10. Horizontal/Vertical Stay white do not abuse, how easy to read how to come.
Viii. exceptions to the rules
1.windows Code
1) Do not use the Hungarian nomenclature, using the Google naming convention, including the use of the. cc extension for source files;
2) Windows defines many synonyms for the original built-in types, such as DWORD, handle, and so on, which are completely acceptable or even encouraged when invoking the Windows API, but still try to use the original C + + type, for example, using the const TCHAR * rather than LPCTSTR;
3) When compiling with Microsoft Visual C + +, set the warning level to 3 or higher and treat all warnings as errors;
4) do not use #pragma once; as a containment protection, use the C + + standard to include protection, the file path containing the protection contains the top level of the project tree;
5) do not use any nonstandard extensions, such as #pragma and _declspec, to allow the use of _ _declspec (dllimport) and _ _declspec (dllexport), except as a last resort. However, macros such as DllImport and dllexport must be used so that others can easily abandon these extensions when sharing the code.
On Windows, there are only a few rules that can occasionally be non-compliant:
1) Often we prohibit the use of multiple inheritance, but multiple inheritance can be used when using COM and ATL/WTL classes, and multiple implementations can be used in order to execute COM or ATL/WTL classes and their interfaces;
2) Although exceptions should not be used in the code, exceptions are widely used in ATL and some stll (including STL for Visula C + +), when using ATL, you should define _atl_no_exceptions to mask exceptions, and you should examine whether you also block out STL exceptions if you do not block , the compiler exception can be turned on, note that this is only to compile the STL, you still do not write the code with exception handling;
3) typically each source file in each project contains a header file named StdAfx.h or precompile.h for easy header file precompilation, in order to make the code easier to share with other projects, avoid explicitly including this file (except for precompile.cc), using compiler Options/ F1 to automatically include;
4) usually named Resource.h, and contains only the macro resource header file, do not have to adhere to this style guide.
Google C + + programming style guide