Google Code Specification

English version: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

Chinese version: http://zh-google-styleguide.readthedocs.org/en/latest/google-cpp-styleguide/

Google c++ coding standard: http://blog.csdn.net/xiexievv/article/details/50972809

There is an electronic PDF online, you can download it. . . (Electronic version download address: https://pan.baidu.com/s/1i3gc7lF)

    Google C++ 编码规范很早就已经公开了,李开复也在其微博上公开分享:”我认为这是地球上最好的一份C++编程规范,没有之一,建议广大国内外IT研究使用。“

    Google C++ Style Guide是一份不错的C++编码指南,下面是一张比较全面的说明图,可以在短时间内快速掌握规范的重点内容。不过规范毕竟是人定的,记得活学活用。

Consistency is also very important. If the new code you add in a file is far from the original code style, it will destroy the overall beauty of the file itself and affect reading, so try to avoid it.
Some items often have exceptions, such as the following, so this picture cannot replace the document. If you have time, please read the PDF carefully.

异常在测试框架中确实很好用

RTTI在某些单元测试中非常有用

在记录日志时可以使用流
操作符重载 不提倡使用,有些STL 算法确实需要重载operator==时可以这么做。

Note: The original image is larger, it is clearer to open it in a new tab or save it locally

insert image description here

head File

function parameter order

C/C++ function parameters are divided into input parameters and output parameters, and sometimes input parameters are also output (note: when the value is modified). Input parameters are generally passed by value or const references, and output parameters or input/output parameters are non-const pointers. When sorting parameters, put all input parameters before output parameters. Don't put it last just because it's a newly added parameter, it should still come before the output parameter. This is not a rule that must be followed, the mix of input/output parameters (usually class/struct variables) can make the rules difficult to follow.

Personal experience: This rule is very important. You may not feel much when you write your own code, but it is especially obvious when you read other people's code. If the code is written according to this specification, from a certain point of view, this code has the function of "self-commenting", so it will be easier to look at the code. Doom3's code specification mentions that "Use 'const' as much as possible" has the same meaning. Of course, in addition to being easy to read, const is also very important to prevent coding errors. Once the const variable is modified in the program, the compiler will report an error, which reduces the possibility of manual errors, which is particularly important!

Include file names and order

Standardizing the order of inclusion can enhance readability and avoid hidden dependencies (note: hidden dependencies mainly refer to the compilation of included files), the order is as follows: C library, C++ library, .h in other libraries, .h in the project .

The header files in the project should be arranged according to the project source code directory tree structure, and avoid the use of UNIX file paths. (current directory) and ... (parent directory).

For example, google-awesome-project/src/foo/internal/fooserver.cc is included in the following order:
  #include “foo/public/fooserver.h” // precedence
  
  #include <sys/types.h>
  #include <unistd.h>

#include <hash_map>
  #include

#include “base/basictypes.h”
  #include “base/commandlineflags.h”
  #include “foo/public/bar.h”

Note that the corresponding header file must be included first, so as to avoid hidden dependencies. If you do not understand the problem of hidden dependencies, you can go to Google. There are many information on the Internet. In addition, the order of inclusion mentioned in "C++ Programming Ideas" is just the opposite, from special to general, but one thing is the same as the Google code specification, that is, the corresponding header file is the first inclusion. For the problem of hidden dependencies, I used to habitually put the corresponding header file first. I didn't think about why, but now I'm learning...

scope

global variable

Global variables of class type are prohibited, global variables of built-in type are allowed, and of course non-constant global variables in multithreaded code are also prohibited. Never initialize global variables with function return values.

Unfortunately, the order in which the constructor, destructor, and initialization operations of global variables are called is only partially specified, and may change from generation to generation, making it difficult to find bugs. Therefore, it is forbidden to use global variables of class type (including STL strings, vectors, etc.), because their initialization order may cause problems. Built-in types and structures without constructors composed of built-in types can be used. If you must use global variables of class type, please use the singleton pattern.

C++ class

Constructor's Responsibilities

Only those initializations that have no practical significance are performed in the constructor. If possible, use the Init() method to centrally initialize data that is meaningful (non-trivial).

Personal experience: This approach can avoid some bugs from the beginning, or solve some bugs more easily. Compared with the method of constructor + Init() function initialization, there is no difference to the computer, but people make mistakes. This code specification avoids some artificial intelligence to some extent. Error, this is especially important in development.

copy constructor

Use the copy constructor only when you need to copy an object of a class in the code, and use the DISALLOW_COPY_AND_ASSIGN macro when you don't need to copy (the content of this macro can be found on the Internet, I won't write it here). Implicit copying of objects in C++ is the source of many performance problems and bugs. Copy constructors reduce code readability, it is more difficult to keep track of objects passed by value than by reference, and it becomes elusive where objects are modified.

Personal experience: Similar to the purpose of the previous item, in order to avoid human error! The copy constructor was originally designed to facilitate programmer programming, but it may become a pit. In order to avoid such problems, use DISALLOW_COPY_AND_ASSIGN when copying is not required, so that an error will be reported when the copy constructor needs to be called, reducing human errors. possibility. C# and Java do better in this regard. Although the performance is not as good as C++, the probability of human error is greatly reduced. Of course, using a certain code specification can reduce the pits of C++ to a certain extent.

inherit

Although the inheritance of C++ is very useful, in actual development, try to use as much combination as possible and use less inheritance. If you don't understand, go to GoF's "Design Patterns".

However, when redefining a derived virtual function, explicitly declare it as virtual in the derived class. This article is for the convenience of reading. Although from a syntax point of view, virtual is declared in the base class, subclasses can no longer declare the function as virtual, but in this way, people who read the code need to retrieve all ancestors of the class to Determines whether the function is a virtual function o(╯□╰)o.

multiple inheritance

Although it is allowed, only one base class has an implementation, and the other base classes are interfaces, which is the same as JAVA. These things have been improved in both C# and JAVA to solve the problem directly from the syntax. The flexibility of C++ is too high, and it is also a troublesome problem. It can only be filled by code specification.

interface

The virtual base class must be suffixed with Interface for easy reading. Easy to read.

overloaded operator

Except in a few specific cases, do not overload operators! ! ! "==" and "=" are replaced by Euqals and CopyFrom functions, which are more intuitive and less error-prone.

Personal experience: I was a little surprised when I saw this article. When I was learning C++, I said that overloading operators has magical benefits. Why do I say no to overloading operators now? After reading his documentation carefully, what he said really makes sense. See its specific documentation for possible bugs. In practical applications, because there are too many pits in C++, we have to get rid of this "easy-to-use" thing, because it is a very painful thing to find a bug and not find it.

Declaration order

1)typedefs和enums;

2) constant;

3) Constructor;

4) Destructor;

5) Member functions, including static member functions;

6) Data members, including static data members.

The macro DISALLOW_COPY_AND_ASSIGN is placed after the private: block as the last part of the class.

Other C++ Features

reference parameter

In the function parameter list, all references must be const!

Personal experience: This is to prevent misunderstandings caused by references, because references are syntactically values, but have the meaning of pointers. Although the reference is easier to use, it is worth sacrificing some of its features in exchange for the convenience of software management.

Default parameter

The use of function default parameters is prohibited!

Personal experience: When I saw this, I felt a little bit of a waste of food because of choking. In fact, the default parameters seem to be quite easy to use. Of course, from another point of view, if you want to use C++, don't be afraid of this little trouble. If you use these features to cause bugs that you can't find, you will lose more time.

abnormal

Don't use C++ exceptions.

I don't understand this, maybe because its exception mechanism is not as perfect as C# and Java... After all, exceptions are still very useful in C# and Java.

flow

Aside from logging, don't use streams, use something like printf instead.

This one is actually somewhat controversial. Of course, most people think that code consistency is more important, so choose printf, and you can refer to the original document for details.

Use of const

Use const wherever possible.

I like this rule, and it is also mentioned in the code specification of Doom3. This has two advantages, one is to prevent program errors, because modifying variables of const type will report errors; the other is to facilitate reading and make the code "self-comment". While there are downsides to doing so, of course, overall the pros outweigh the cons.

naming convention

1. General rule: Don’t abbreviate it arbitrarily. If it is excusable to say that ChangeLocalValue is written as ChgLocVal, it is too much to write ModifyPlayerName as MdfPlyNm. Except that the function name can be appropriately used as a verb, other names should use clear and easy-to-understand nouns as much as possible;

2. Use all uppercase + underscore for macros, enumerations, etc.;

3. Variables (including class and structure member variables), files, namespaces, access functions, etc. use all lowercase + underscores, class member variables end with an underscore, and global variables begin with g_;

4. Common functions, types (including classes and structures, enumeration types), constants, etc. use mixed case, without underscores;

Using this naming convention, you can make the code have a certain degree of "self-comment" function, which is convenient for others to read, and it is also convenient for you to modify it later. Of course, other naming conventions can also be used for points 3 and 4, as long as the team is unified.

Format

1. In principle, the line width should not exceed 80 columns, and it is impossible to justify the full 22-inch display screen;

2. Try not to use non-ASCII characters. If you use them, refer to the UTF-8 format (especially under UNIX/Linux, you can consider wide characters under Windows), try not to couple string constants into the code, such as separate resource files , it's not just a matter of style;

3. Spaces are used unconditionally under UNIX/Linux, and it is understandable to use Tab in MSVC; (I have never used Linux, so I don’t know why spaces are used unconditionally under Linux)

4. Function parameters, logical conditions, initialization list: either all parameters and function names are placed on the same line, or all parameters are side by side and separate lines;

5. In addition to the opening curly braces of function definitions, which can be placed at the beginning of the line, including function/class/structure/enumeration declarations, the opening curly braces of various statements are placed at the end of the line, and all closing curly braces are on a separate line;

6. There is no space before and after the ./-> operator, */& don't leave both before and after, just one, left to right depends on everyone's preference;

7. Preprocessing directives/namespaces do not use additional indentation, and classes/structures/enumerations/functions/statements use indentation;

8. Initialize = or () according to personal preference, just unify;

9. Do not add () to return;

10. Don't abuse the horizontal/vertical white space, how to read it easily.

write at the end

In general, this set of code specifications is quite good. There are not only specifications to prevent bugs caused by the wrong use of some features of C++, but also related specifications for code writing to make it easier to read. It is recommended that children who engage in C++ have a look. Look. Of course, specific teams should have specific code specifications, and there may be some differences in code style; in terms of not using some features of C++ (such as not using C++ exceptions, and prohibiting the use of function default parameters), it should be carried out according to the specific situation. It is a compromise, and you should not copy the code specification; but the specification of "not coupling string constants into the code" is something everyone must abide by.

Reprinted: https://blog.csdn.net/freeking101/article/details/78930381 It is convenient to learn by yourself, thanks to the blogger

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324494229&siteId=291194637