Learning notes: Google C + + programming style guide

Source: Internet
Author: User
Tags bit set function prototype

Directory:
One, the head file ... ..... .... ..... ..........................
Second, scope ..... ..... ..... ..... ..... ..... ...................
Third, C + + class ... ..... ..... ..... ........................
Four, smart pointers and other C + + features ....... .....
v. Naming conventions.............................................
Six, code comments ..... ..... ..... ....... ...................
Seven, the format ... ..... .... ..... ........ ........................

First, the header file
1. #define保护
#ifndef Foo_bar_baz_h_
#define Foo_bar_baz_h_
...
#endif//Foo_bar_baz_h_
2. Header file dependencies
When a header file is included, a new dependency is introduced, and the code is recompiled as long as the header file is modified.
Therefore, as little as possible to include the header file, using the pre-declaration can reduce the header file contains, such as:
The header file uses the class file, but does not need to access the file's declaration, the header file only needs to be pre-declared class file, without the # include "File/base/file.h".
Use the pointer member *foo to override the object member Fooso that you do not have to access the definition of the class.
do not rely on the definition if you can rely on the declaration.
3. Inline functions
A function is defined as an inline function only if it is only 10 rows or less.
When the function body is relatively small, inline the function can make the target code more efficient. For access functions and some other short key execution functions.
4.-inl.h file
The definition of a complex inline function should be placed in a header file with the suffix named-inl.h.
The-inl.h file can also be used for definition of function templates, which makes the template definition more readable.
-inl.h, like other header files, requires a # define protection.
5. function parameter Order
When defining a function, the order of the parameters is: input parameters are before, output parameters are behind.
input parameter General or constant reference (const references), output parameter or input/output parameter is a very few pointer (Non-const pointers).
6. Name and order of the included files
The order is as follows:c Libraries, C + + libraries, other libraries. h, within the project. H。
C System files
C + + system files
Other Library header files
Header files in this project

Second, scope
1. Namespaces
Namespaces divide the global scope into distinct, named scopes, which effectively prevent naming conflicts for global scopes.
An unnamed namespace can be used in a *.cc file;
The *.h file can only be usedNamed namespaces, you cannot use unnamed namespaces;
It is best not to use the using indicatorTo make sure that all names under the namespace are working correctly.
2. Nested Classes
You can define another class in one class, and a nested class is also called a member class.
It is useful when nested (member) classes are used only in nested classes (enclosing class), placing them in nested class scopes as
A class with the same name as a member of a nested class does not contaminate other scopes. Class Foo {
Private
Bar is a member class nested in Foo
Class Bar {
...
};
};
3.non-member functions, static member functions, and global functions
Use a non-member function or a static member function in a namespace, and try not to use a global function.
4. Local Variables
Place a function variable in the smallest scope possible, initializing it when declaring a variable.
If the variable is an object, each entry to the scope calls its constructor, and each exit scope calls its destructor.It is more efficient to declare a similar variable to the outside of the circular action。
5. Global Variables
Global variables of class type are forbidden, and global variables of the built-in type are allowed, of course, the very few global variables in multithreaded code are
Forbidden. Never initialize a global variable with a function return value.

Third, C + + class
1. Functions of constructors
Constructors, only those that do not actually make sense are initialized,if the object requires meaningful initialization, consider using a different init () method and/or add a member
Used to indicate whether the object has been initialized successfully.
2. Default constructors
If a class defines several member variables and no other constructors, you need to define a default constructor (no parameters), or the compiler will automatically generate a default constructor.
3. Explicit Constructors
Use the C + + keyword explicit for a single-argument constructor.
A constructor with only one parameter can be used for transformations (implicit conversions generate a new object), and to avoid implicit conversions of constructors being called, you can declare them
For explicit.
4. Copy Constructors
Copy constructors are used only when you need to copy a class object in your code, and you should use disallow_copy_and_assign when you do not need a copy.
//macros that prohibit the use of copy constructors and assignment operations
Should be used in the private: of the class
#define DISALLOW_COPY_AND_ASSIGN (TypeName) \
TypeName (const typename&); \
void operator= (const typename&)
Class Foo {
Public
Foo (int f);
~foo ();
Private
Disallow_copy_and_assign (Foo);
};
In most cases, disallow_copy_and_assign should be used, if the class does require a copy, it should be explained in the header file of the class, and the copy constructor and assignment operation should be properly defined, noting that the operator= The Self-assignment (self-assignment) condition is detected in the
5.Structs and Classes
Use a struct only when data is available, and all others use class.
6. Inheritance
using a combination is often more appropriate than using inheritance, and only public inheritance is used if inheritance is used.
Implementing InheritanceReduces the amount of code by reusing the base class code intact,Interface InheritanceFeatures that can be used on programs to enhance the specific API of a class.
To restrict the member functions that are accessed only in subclasses as protected, it is important to note thatdata members should always be private。
When you redefine a derived virtual function, explicitly declare it as virtual in the derived class. Root cause: If virtual is omitted, the reader needs to retrieve all ancestors of the class to determine if the function is a virtual function.
7. Multiple Inheritance
Multiple inheritance is used only when up to one base class contains implementations, and other base classes are pure interface classes that are suffixed with interface.
Multiple inheritance allows subclasses to have multiple base classes, distinguishing between base classes that are pure interfaces and base classes that have implementations.
8. Interface
Pure interface:
1) only pure virtual functions ("= 0") and static functions (except for destructors mentioned below);
2) No non-static data members;
3) No constructors are defined. If there is, also does not contain the parameter, and is protected;
4) If you are a subclass, you can only inherit classes that meet the above criteria and have the interface suffix.
9. Operator Overloading
Generally do not overload operators, especially the assignment operation (operator=) is more sinister, should avoid overloading. You can define functions such as equals (), CopyFrom (), if necessary.
10. Access control
privatize data members and provide relevant access functions, such as defining variable foo_ and accessor function foo (), Assignment function Set_foo ().
The definition of an access function is typically inline in the header file.
11. Order of declarations
The definition order is as follows:
Public
Protected
Private:
If that piece is not, just ignore it.
in each block, the order of declarations is generally as follows:
1) typedefs and enums;
2) constant;
3) constructor function;
4) destructor function;
5) member functions, including static member functions;
6) data members, including static data members.
Macro Disallow_copy_and_assign is placed after the private: block as the last part of the class.
12. Writing Short Functions
The function is as short and simple as possible, allowing others to read and modify the code.
if the function exceeds 40 rows, consider splitting it without affecting the structure of the program.

Iv. Smart pointers and other C + + features
If you need to use a smart pointer,scoped_ptrPerfectly capable. In very special cases, you should only use thestd::tr1::shared_ptr, do not use auto_ptr under any circumstances.
1. Reference Parameters
The input parameter is a value or a constant reference, the output parameter is a pointer, and the input parameter can be a constant pointer, but cannot use a very number reference parameter.
void Foo (const string &in, String *out);
2. Function Overloading
Do not use function overloading to mimic default function parameters only if the input parameter types are different and the functions are using overloaded functions (with constructors).
3. Default Parameters
Disable the use of default function parameters.
The default parameter provides the convenience of having fewer functions defined for exceptions that are rarely involved.
The default parameter makes it difficult to copy and paste the previous code to render all parameters, which can cause significant problems when the default parameters do not apply to the new code.
4. Variable-length arrays and Alloca
The use of variable-length arrays and alloca () is prohibited.
They can cause hard-to-find memory leaks by assigning size to data on the stack.
5. Friends
The use of friend and friend functions is allowed.
Friend extends (but does not break) the encapsulation line of the class, so that when you want to allow only another class to access a member, the UF element is usually more
Its declaration is much better than public.
6. Exceptions
do not use C + + exceptions.
functions may be returned in an indeterminate place, leading to difficulty in code management and debugging.
7. Runtime type identification (run-time type information, RTTI)
do not use Rtti in addition to unit tests.
8. Type conversion(Casting)
Use C + + type conversions such as static_cast<> (), do not use int y = (int) x or int y = int (x);.
Instead of using C-style type conversions, use C + + style:
1) static_cast: and C-style conversions similar to the coercion of the value, or the pointer's parent class to the explicit upward conversion of the subclass;
2) Const_cast: Remove the const attribute;
3) Reinterpret_cast: The non-secure conversion between pointer type and integer or other pointers is only used when you are clear about what you do;
4) dynamic_cast: Do not use in addition to testing, in addition to unit testing, if you need to determine the type information at run time, indicating that the design is missing
(Refer to RTTI).
9. Stream (Streams)
Streams are used only when logging is logged, and the stream is an alternative to printf () and scanf ().
10. Pre-increment (++i/--i)
iteratorsand otherTemplate ObjectUse the prefix form (++i) for self-increment, self-subtraction.
If the return value is not considered,Pre-increment (++i) is usually more efficient than post-increment (i++), because the post-increment self-decrement requires a copy of the value of the expression, if I is an iterator or other non-numeric type, the cost of copying is relatively large.
Use of 11.const
It is strongly recommended that you use const in any situation where you can use it.
If you pass a const variable to a function, the function prototype must also be const (otherwise the variable requires a const_cast type conversion)
If the function does not modify the arguments of the incoming reference or pointer type, such arguments should be const;
Const int* Foo
12. Integral Type
<stdint.h> defines integer types such as int16_t, uint32_t, and int64_t, which can be used instead of short, unsigned long long, and so on when they need to determine the size of an integer.
Do not use unsigned integers such as uint32_t unless you are representing a bit set (bit pattern) instead of a numeric value.
portability under 13.64-bit
Code in 64-bit and 32-bit systems, in principle, should be more friendly.
14. Preprocessing Macros
Be cautious when using macros, instead of inline functions, enumerations, and constants as much as possible.
15.0 and Null
Integers with 0, real numbers with 0.0, pointers with NULL, characters (strings) with ' + '.
16.sizeof
Use sizeof (varname) instead of sizeof (type) whenever possible.
17.Boost Library
Use only libraries that are recognized in boost.

v. Naming conventions


Vi. Code comments
1. Annotation style
use//////, unity is good.
2. File comments
Add a copyright notice at the beginning of each file, followed by a description of the file content .
3. Class annotations
Each class is defined to attach a comment that describes the functionality and usage of the class.
4. Function comments
the contents of the comment at the function declaration:
1) inputs (input) and outputs (output);
2) for a class member function: Whether the object needs to persist the reference parameter during the function call, and whether the arguments will be disposed;
3) If the function allocates space, it needs to be freed by the caller;
4) Whether the parameter can be NULL;
5) Whether there is a performance concern for function use;
6) If the function is reentrant, what is the synchronization prerequisite?
function definition:
Each function definition is annotated with a comment explaining function functions and implementation essentials, such as the beautiful code used, the implementation of the brief steps, the reason for such an implementation, why the first half of the lock and the second half of the part is not required.
5. Variable annotations
Usually the variable name itself is good enough to explain the purpose of the variable, and in certain cases additional explanatory notes are required.
6. Implementing annotations
annotate the smart, obscure, interesting, and important areas of your implementation code.
7. Punctuation, spelling, and grammar
pay attention to punctuation, spelling, and grammar, and write good notes that are much easier to read than bad.
8.TODO Comments
use todo annotations for temporary, short-term solutions, or code that is good enough but not perfect.
TODO ([email protected]): Use a "*" here for concatenation operator.

VII. format
1. Line length
The number of code characters per line does not exceed 80.
2. Non-ASCII characters
Try not to use non-ASCII characters, you must use the UTF-8 format when using.
3. Spaces or Tab stops
use only spaces to indent 2 spaces at a time.
4. function declaration and definition
The return type and function name are on the same line, and if appropriate, the parameters are also on the same line.
5. Function calls
Try to put it on the same line, or enclose the argument in parentheses.
6. Conditional statements
It is more important not to add spaces in parentheses, and the keyword else to another line.
7. Loop and switch selection statements
The switch statement can be chunked with braces, and the empty loop body should use {} or continue.
8. Pointers and Reference expressions
Do not have spaces before or after the period (.) or arrow (.), and do not have spaces after the pointer/address operator (*, &).
x = *p;
p = &x;
x = R.Y;
x = r->y;
when you declare a pointer variable or parameter, the asterisk and the name of the type or variable are immediatelythe way individuals compare habits and variables closely.
Char *c;
Const string &str;
Or
char* C;
Const string& STR;
9. Boolean expressions
If a Boolean expression exceeds the standard line width (80 characters), if the break is to be unified.
10. Function return value
do not use parentheses in the return expression.
11. Initialization of variables and arrays
select = or ().
12. Pre-processing instructions
Preprocessing directives do not indent, starting at the beginning of the line.
Even if the preprocessing directives are in the indentation code block, the instructions should start at the beginning of the line.
13. Class format
Keywords public:, protected:, Private: To indent 1 spaces, and these three keywords are not indented.
14. Initialize the list
The constructor initialization list is placed in the same row or indented in a few rows by four cells.
15. Namespace formatting
Namespace content is not indented.
namespaces do not add additional indentation levels.
16. Horizontal Blank
Don't add meaningless blanks at the end of a line.
17. Vertical Blanks
The fewer vertical blanks, the better. .
Do not have a blank line on the function head or tail.
There is no blank line at the end of the code.

Learning notes: Google C + + programming style guide

Related Article

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.