Google's C ++ code specifications

Google's C ++ code specifications

First, the header file

 

(One)Order function parameters

  C / C ++ function parameters are divided into two kinds of input and output parameters, the input parameters may also output (Note: value is modified). Input parameters are usually values ​​or constant reference (const references), the output parameter Ring Input / output parameter is the number of pointers (non-const pointers). Sort of parameter, all input parameters in the output parameter before. Do not just because it is a newly added parameters, it will be placed in the final, but should still be placed before the output parameters. It is not necessary to follow the rule input / output dual parameter (usually type / structure variables) mixed therein, will make it difficult to comply with the rules.

  Personal experience: This rule is very important, write your own code, the time may not have much feeling, but the feeling is particularly evident when reading someone else's code. If the code in this specification to write, in some ways, this code has a "self-comment" feature, you will be more relaxed when looking at the code. Doom3 code mentioned specification, "Use 'const' as much as possible", the meaning is the same. Of course, in addition to const easy to read, there is a very important thing is to prevent coding errors, once modified const variables in the program, the compiler will report an error, thus reducing the likelihood of manual errors, it is particularly important!

 

(two)It contains the names and order of the file

  The order includes standardization can enhance readability and avoid hidden dependence (hidden dependencies, Note: Hidden rely mainly refers to the file compiled included), the order is as follows: C library, C ++ library, .h other libraries, .h within the project .

  Header within the project structure arranged according to the project should the source tree, and avoid the use of UNIX file path (the current directory) and .. (parent directory). 

       For example, google-awesome-project / src / foo / internal / fooserver.cc comprises the following sequence:

 1 #include "foo/public/fooserver.h" // 优先位置 
 2   
 3   #include <sys/types.h> 
 4   #include <unistd.h> 
 5  
 6   #include <hash_map> 
 7   #include <vector> 
 8  
 9   #include "base/basictypes.h" 
10   #include "base/commandlineflags.h" 
11   #include "foo/public/bar.h"

Note that the corresponding header file must first contain, thus avoiding dependence hide, hide-dependent problems do not understand can go to Google, the Internet has a lot of information. In addition, the order includes "C ++ programming ideas" in reference to the contrary, from the particular to the general, but one thing is the same specification and Google Code, that is the corresponding header file is included first. For hidden dependency problems, it was only the habit of the corresponding header put the first one, ever wondered why, now learned ......

 

 

two,Scope

 

(One)Global Variables

  class types of global variables is prohibited, built-in types of global variables is allowed, of course, very multi-threaded code number of global variables is prohibited. Never use the return value of the function to initialize global variables.

  Unfortunately, the global variables constructor, destructor, and calls the initialization sequence of operations is defined only partially, there is generated each time may vary, resulting in difficult to find bug. Therefore, prohibiting the use of class types of global variables (including the STL string, vector and so on), because their initialization order can cause problems. No built-in types and constructors structure composed of a built-in type can be used, if you must use the global variable of type class, use singleton pattern.

 

 

three,C ++ class

 

(One)Responsibilities constructor

  Constructor initializes only those moot, if possible, use the Init () method is initialized to meaningful concentration (non-trivial) data.

  Personal experience: This approach can avoid some bug appeared from the beginning, or easier to solve some bug. Constructors + Init () function initializes the way compared to the method using only constructor to the computer for them there is no difference, but people make mistakes, which is a standardized code in a way to avoid some man-made wrong, this is particularly important in development.

 

(two)Copy constructor

  Only need to copy a class of objects in code when using the copy constructor, DISALLOW_COPY_AND_ASSIGN use this macro does not need to copy (on the contents of the macro, you can search the Internet, I do not write here). Implicit copy of C ++ objects that cause a lot of performance issues and bugs roots. Copy constructor reduces code readability, compared passed by reference, tracking objects passed by value is more difficult to modify an object's place becomes elusive.

  Personal feelings: on the one and similar purposes, in order to avoid human error! Copy constructor could have been programmed for the convenience of the programmer, but there may be a pit, in order to avoid such problems, it is not necessary to use DISALLOW_COPY_AND_ASSIGN copy, so you need to call when the copy constructor will error, reduce human error possibilities. C # and Java in this regard to do better, although not as good as C ++ performance, but the probability of human error is reduced a lot. Of course, using a predetermined code specification, C ++ pits can be reduced to some extent.

 

(three)inherit

  Although C ++ inheritance is useful, but in the actual development, as much as possible with a combination of less inheritance, do not understand to see GoF's "Design Patterns".

  But redefine derived virtual function in a derived class explicitly stated as being virtual. This one is for the sake of convenience to read, although from a linguistic point of view, it declared virtual in the base class, subclass can no longer declare the function is virtual, but this way of reading the code who need to retrieve all the ancestors of the class to determining whether the function is a virtual function o (╯ □ ╰) o.

 

(four)Multiple Inheritance

  Although allowed, but only to achieve a base class, the base class is the interface to the other, and so to a JAVA same. These things in C # and JAVA are improved to address the problem directly from the grammar. C ++ high flexibility, it is also a troublesome issue can only be filled pit by code specifications.

 

(Fives)interface

  Virtual base class Interface suffix must be easy to read. Ease of reading.

 

(six)Overload operator

  Except for a few specific cases, do not overload operator! ! ! "==" and instead of "=" operation and CopyFrom Euqals function, which is more intuitive, not prone to error.

  Personal experience: to see this one, I was a bit surprised when learning C ++, saying overloaded operators God God Ma Ma benefits, why are not overloaded operator said it? He carefully read the document, it does have a point, lead to bug reflected in its specific document that may arise. In practice, because C ++ pit too much, had to put this "useful" to get rid of things, because they can not find a bug, O is a very painful thing.

 

(Seven)Declaration order

  1) typedefs and enums in;
  2) constant;
  3) Constructor;
  4) destructor;
  5) member function, including a static member function;
  6) data member, containing static data members.
  Macro DISALLOW_COPY_AND_ASSIGN placed private: Following the block, as the class of the last part.

 

 

three,Other features of C ++

 

(One)Reference parameters

  Function parameter list, all references must be in const!

  Personal experience: This is done to prevent misunderstandings caused by reference, because the reference is a value in grammar, there are pointers significance. Although relatively easy to use reference, but the expense of some aspects of its properties, in exchange for the convenience of management software, is still very worthwhile.

 

(two)The default parameters

  Prohibit the use of function default parameters!

  Personal experience: to see this time feel a little unworthy, in fact, default parameters still feel very good use. Of course, from another point of view, to use C ++, do not be afraid of this little trouble, because if the use of these features can not find the cause of the bug, it will lose more time.

 

(three)abnormal

  Do not use C ++ exceptions.

  This I do not understand, perhaps because there is no C # and Java so perfect it ...... After all, C # and Java inside abnormal or good stuff for its exception mechanism.

 

(four)flow

  In addition to logging, do not use the stream, instead of using printf like.

  This is a fact, there is some controversy, of course, most people think the code consistency is more important, so I chose to printf, concrete can see the original document.

 

(Fives)use const

  You have to use const in any case possible.

  This rule like this one, code specifications Doom3's also mentioned in this article. There are two advantages to do so, it is to prevent a procedural error, as amended const type variable will complain; the other is easy to read, making the code "from comments." Although there are disadvantages to do so, of course, in general, more good than harm.

 

 

four,Naming Convention

 

  1, the general rule: Do not arbitrarily abbreviation, if ChangeLocalValue writing ChgLocVal if there are conditions to the original, the ModifyPlayerName writing MdfPlyNm too much, except as may be appropriate to the function name outside the verb, to make use of other names in clear and understandable terms; 

  2, macros, and other enumeration using all caps + underline; 

  3, variables (including class, structure members variable), files, namespaces, and other access functions to use all lowercase underlined +, class member variables end underlined, the beginning of global variables g_; 

  4, the general functions, types (including classes and structures, enumerated type), constants, etc. mixed case, without underscores; 

  Use this naming convention makes the code a certain degree of "self-Notes" feature, for others to read, but also to facilitate their subsequent modifications. Of course 3,4 points may also use other naming convention, as long as the team can be unified.

 

Fives,format 

 

  1, the line width in principle, more than 80, the 22-inch display are accounted finished, how can not be justified;

  2, try not to use non-ASCII characters, if used, the reference UTF-8 format (especially in UNIX / Linux, Windows, can be considered wide characters), try not to string constants coupled to a tag, such separate the resource file , returning just a matter of style;

  3, under UNIX / Linux unconditional use spaces, MSVC, then use the Tab is understandable; (I have not used Linux, do not understand why the unconditional use the space under Linux)

  4, function parameters, logic conditions, initialization list: either all the parameters and function names on the same line, or all the parameters side by side branches;

  5, in addition to the function definition left brace may be placed outside of the line, including the function / class / junction diode / enumeration declaration, a left brace at the line end of the various statements, all right brace separate line;

  6. / -> before and after the operator Ji leave a space, * / & do not have to stay around, a can, right to the left according to individual preferences;

  7, the pre-command / namespace without using an additional indentation, type / structure / enumeration / function / statement indentation;

  8, initialization = or () depending on personal preference, like unity;

  9, return do not add ();

  10, the horizontal / vertical blank Do not abuse, how to how to read. 

 


 


 

Three kinds of naming program (Hungarian notation, camel nomenclature, Pascal nomenclature)

 

Three popular nomenclature

There are four current industry nomenclature: nomenclature hump, Hungarian notation, Pascal nomenclature and underscores nomenclature, of which the first three are more popular nomenclature.

 

 

1. Hungarian:

 

Beginning with the letter variable types of abbreviation, acronym in English or English with the rest of the variables, and the first letter of each word is capitalized.

 

Example: 

  1.  
    iMyAge int;  // int type I is the abbreviation.
  2.  
    cMyName char [ 10]; // C is the abbreviation of type char. 
  3.  
    fManHeight float; // F is an abbreviation of type float.

Hungary named variables are widely used in such an environment, like in Microsoft Windows, Windows programming used (also including macro) are naming Hungarian notation, this technique is named by a competent Microsoft programmer Charles - Simon Nigeria (Charles Simonyi) presented

Hungarian notation before the variable names by lowercase letters with the corresponding identification symbols prefixed scope variables identified, these types may be a plurality of symbols simultaneously, the order is m_Low (member variables), then the pointer, and then simple data types, then the other.

For example: m_lpszStr, Pointer to a variable to represent a long pointer to a string of characters at the end of the member 0 

Hungarian notation is key: identifier names that begin with one or more lowercase letters as a prefix; prefix after the first letter of a word is capitalized or more combinations of words, a word to indicate the use of variables 

 

Hungarian prefix method commonly used in lowercase letters:

+ + Type attribute described. Lowercase property typically + _:

g_: global variable
m_: class member variables
s_: Static variables
c_: Constants

Type prefix Types of
a    Array (Array)  
b    Boolean value (Boolean)  
by    Byte (Byte)  
c    Signed char (Char), cCount start with c
cb    Unsigned char (Char Byte, not many people use)  
cr    Color reference value (COLORREF)  
d    double dDeta begin with d
f    float begin with f fAvg 
cx,cy    Coordinate difference (length shortint)  
w    Word, unsigned int (WORD) wCount beginning with w
dw    Double Word, unsigned long int (DWORD) dwBroad start with dw
fn    function  
h    Handle (handle)  
i    Int int, iCount start with i
n    short int n beginning with short integer nStepCount
l    Long Int l long integer with the beginning of lSum
lp    Long Pointer  
m_    Members of the class  
for example,    Near Pointer  
p    Pointer  
s    String type, beginning with s sFileName
sz    To make null-terminated string type (String with Zero End),
   with \ sz string beginning with the end of the szFileName 0

 

 

2. camel nomenclature (small camel nomenclature):

 

Small hump method (Method CAMEL): the first word begins with a lowercase letter; first letter of the second word is capitalized, or starting from the second word, the first letter of each word are uppercase behind, i.e., a small hump style nomenclature: the first letter of the first word lowercase, behind other word capitalized.

Variable identification method for general use small hump.

ex: 
int myAge; 
char myName[10]; 
float manHeight;

 

Small camel naming convention (lowercase first letter of the first word, the first letter of all subsequent word is capitalized): firstName, camelCase

Large camel naming conventions (the first letter of all words in uppercase): FirstName, CamelCase

 

Here is the same functions are identified by underlined and camel nomenclature method named:

printEmployeePaychecks (); break ---- each logical function name Camel nomenclature has marked with a capital letter
print_employee_paychecks (); break each logical function names underlined ---- method has a underline mark.

 

 

3 Pascal nomenclature (large camel nomenclature):

 

Pascal nomenclature (Pascal method) known as a large hump of formula nomenclature. Compared small hump law, the first letter of the law big hump of the first word is also capitalized the first letter of each word is capitalized. That camel nomenclature is the first letter lowercase, and Pascal nomenclature is capitalized

(Pascal method) commonly used for the class names, function names, attributes, namespaces.

Method large hump (Camel the Upper Case) EX: 
int MyAge; 
char MyName [10]; 
a float ManHeight;
public class databaseuser

 

 

4. underscore naming convention

 

Underline popular method is the use in such an environment UNIX / LIUNX, and the GNU C language code with the advent of very common 

 

 

5. Name the rule Summary:

 

MyData is an example of a named Pascal.
And myData is a camel nomenclature, it is the first letter of the first word lowercase, followed by the word capitalized, looks like a camel.
And iMyData is a Hungarian notation, it lowercase i illustrate its type, and the back of the same name Pascal, indicates the use of the variable.

 

Typically each language has its own Coding Style, such as C / C ++ and python are underlined, java and go hump.

So, for nomenclature to which you can write code using personal style, but also can use a different naming convention used in combination.

Such as: Camel + underscore (int temperature_Sensor;)



End said:

Benpian C ++ specification reference from: https://blog.csdn.net/freeking101/article/details/78930381 

If wrong, please point out.

Guess you like

Origin www.cnblogs.com/ZAsmn/p/11441904.html