Google C++ Style Guide Notes (Revision 3.274)

Table of Contents

Homepage

Header Files

The #define Guard

所有头文件都应该使用 #define 防止头文件被多重包含, 命名格式当是: <PROJECT>_<PATH>_<FILE>_H_

For example, the file foo/src/bar/baz.h in project foo should have the following guard:

#ifndef FOO_BAR_BAZ_H_
#define FOO_BAR_BAZ_H_

...

#endif  // FOO_BAR_BAZ_H_

Forward Declarations

能用前置声明来避免不必要的#include.

A "forward declaration" is a declaration of a class, function, or template without an associated definition.

用前置声明可以显著减少需要包含的头文件数量. 举例说明: 如果头文件中用到类 File, 但不需要访问 File 类的声明, 头文件中只需前置声明 class File; 而无须 #include "file/base/file.h".

不允许访问类的定义的前提下, 我们在一个头文件中能对类 Foo 做哪些操作?

  • 我们可以将数据成员类型声明为 Foo * 或 Foo &.
  • 我们可以将函数参数 / 返回值的类型声明为 Foo (但不能定义实现).
  • 我们可以将静态数据成员的类型声明为 Foo, 因为静态数据成员的定义在类定义之外.

反之, 如果你的类是 Foo 的子类, 或者含有类型为 Foo 的非静态数据成员, 则必须包含 Foo 所在的头文件.

Decision:

  • When using a function declared in a header file, always #include that header.
  • When using a class template, prefer to #include its header file.
  • When using an ordinary class, relying on a forward declaration is OK, but be wary of situations where a forward declaration may be insufficient or incorrect; when in doubt, just #include the appropriate header.
  • Do not replace data members with pointers just to avoid an #include.

当然 .cc 文件无论如何都需要所使用类的定义部分, 自然也就会包含若干头文件.

Inline Functions

只有当函数只有 10 行甚至更少时才将其定义为内联函数.

Decision: 一个较为合理的经验准则是, 不要内联超过 10 行的函数. 谨慎对待析构函数, 析构函数往往比其表面看起来要更长, 因为有隐含的成员和基类析构函数被调用!

另一个实用的经验准则: 内联那些包含循环或 switch 语句的函数常常是得不偿失 (除非在大多数情况下, 这些循环或 switch 语句从不被执行).

有些函数即使声明为内联的也不一定会被编译器内联, 这点很重要; 比如虚函数和递归函数就不会被正常内联. 通常, 递归函数不应该声明成内联函数.(递归调用堆栈的展开并不像循环那么简单, 比如递归层数在编译时可能是未知的, 大多数编译器都不支持内联递归函数). 虚函数内联的主要原因则是想把它的函数体放在类定义内, 为了图个方便, 抑或是当作文档描述其行为, 比如精短的存取函数.

The -inl.h Files

复杂的内联函数的定义, 可放在后缀名为 -inl.h 的头文件中.

Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read.

Do not forget that a -inl.h file requires a #define guard just like any other header file.

Function Parameter Ordering

When defining a function, parameter order is: inputs, then outputs.

Names and Order of Includes

使用标准的头文件包含顺序可增强可读性, 避免隐藏依赖: C 库, C++ 库, 其他库的 .h, 本项目内的 .h.

For example, google-awesome-project/src/base/logging.h should be included as

#include "base/logging.h"

In dir/foo.cc or dir/foo_test.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows:

dir2/foo2.h (preferred location — see details below).
C system files.
C++ system files.
Other libraries' .h files.
Your project's .h files.

With the preferred ordering, if dir2/foo2.h omits any necessary includes, the build of dir/foo.cc or dir/foo_test.cc will break. Thus, this rule ensures that build breaks show up first for the people working on these files, not for innocent people in other packages.

Within each section the includes should be ordered alphabetically. Note that older code might not conform to this rule and should be fixed when convenient.

Exception: sometimes, system-specific code needs conditional includes. Such code can put conditional includes after other includes. Example:

#include "foo/public/fooserver.h"

#include "base/port.h"  // For LANG_CXX11.

#ifdef LANG_CXX11
#include <initializer_list>
#endif  // LANG_CXX11

Scoping

Namespaces

鼓励在 .cc 文件内使用匿名名字空间. 使用具名的名字空间时, 其名称可基于项目名或相对路径. 不要使用 using 关键字. 不要使用内嵌名字空间

Decision: Use namespaces according to the policy described below. Terminate namespaces with comments as shown in the given examples.

  • Unnamed Namespaces
    • Unnamed namespaces are allowed and even encouraged in .cc files, to avoid runtime naming conflicts:
      namespace {                           // This is in a .cc file.
      
      // The content of a namespace is not indented
      enum { kUnused, kEOF, kError };       // Commonly used tokens.
      bool AtEof() { return pos_ == kEOF; }  // Uses our namespace's EOF.
      
      }  // namespace
      

      However, file-scope declarations that are associated with a particular class may be declared in that class as types, static data members or static member functions rather than as members of an unnamed namespace.

    • Do not use unnamed namespaces in .h files.
  • Named Namespaces

    Named namespaces should be used as follows:

    • Namespaces wrap the entire source file after includes, gflags definitions/declarations, and forward declarations of classes from other namespaces:
      // In the .h file
      namespace mynamespace {
      
      // All declarations are within the namespace scope.
      // Notice the lack of indentation.
      class MyClass {
       public:
        ...
        void Foo();
      };
      
      }  // namespace mynamespace
      // In the .cc file
      namespace mynamespace {
      
      // Definition of functions is within scope of the namespace.
      void MyClass::Foo() {
        ...
      }
      
      }  // namespace mynamespace
      

      The typical .cc file might have more complex detail, including the need to reference classes in other namespaces.

      #include "a.h"
      
      DEFINE_bool(someflag, false, "dummy flag");
      
      class C;  // Forward declaration of class C in the global namespace.
      namespace a { class A; }  // Forward declaration of a::A.
      
      namespace b {
      
      ...code for b...         // Code goes against the left margin.
      
      }  // namespace b
      
    • Do not declare anything in namespace std, not even forward declarations of standard library classes.
    • You may not use a using-directive to make all names from a namespace available.
      // Forbidden -- This pollutes the namespace.
      using namespace foo;
      
    • You may use a using-declaration anywhere in a .cc file, and in functions, methods or classes in .h files.
      // OK in .cc files.
      // Must be in a function, method or class in .h files.
      using ::foo::bar;
      
    • Namespace aliases are allowed anywhere in a .cc file, anywhere inside the named namespace that wraps an entire .h file, and in functions and methods.
      // Shorten access to some commonly used names in .cc files.
      namespace fbz = ::foo::bar::baz;
      
      // Shorten access to some commonly used names (in a .h file).
      namespace librarian {
      // The following alias is available to all files including
      // this header (in namespace librarian):
      // alias names should therefore be chosen consistently
      // within a project.
      namespace pd_s = ::pipeline_diagnostics::sidetable;
      
      inline void my_inline_function() {
        // namespace alias local to a function (or method).
        namespace fbz = ::foo::bar::baz;
        ...
      }
      }  // namespace librarian
      
    • Do not use inline namespaces.

Nested Classes

当公有嵌套类作为接口的一部分时, 虽然可以直接将他们保持在全局作用域中, 但将嵌套类的声明置于名字空间内是更好的选择.

Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method.

Nonmember, Static Member, and Global Functions

使用静态成员函数或名字空间内的非成员函数, 尽量不要用裸的全局函数.

Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead.

Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library.

If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {…}) to limit its scope.

Local Variables

将函数变量尽可能置于最小作用域内, 并在变量声明时进行初始化.

There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope.

// Inefficient implementation:
for (int i = 0; i < 1000000; ++i) {
  Foo f;  // My ctor and dtor get called 1000000 times each.
  f.DoSomething(i);
}

It may be more efficient to declare such a variable used in a loop outside that loop:

Foo f;  // My ctor and dtor get called once each.
for (int i = 0; i < 1000000; ++i) {
  f.DoSomething(i);
}

Static and Global Variables

禁止使用 class 类型的静态或全局变量: 它们会导致很难发现的 bug 和不确定的构造和析构函数调用顺序.但是,允许这些变量, 当他们是没有动态初始和析构的constexpr:时。

Objects with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays/structs of POD.

The order in which class constructors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals.

One way to alleviate the destructor problem is to terminate the program by calling quick_exit() instead of exit(). The difference is that quick_exit() does not invoke destructors and does not invoke any handlers that were registered by calling atexit(). If you have a handler that needs to run when a program terminates via quick_exit() (flushing logs, for example), you can register it using at_quick_exit(). (If you have a handler that needs to run at both exit() and quick_exit(), you need to register it in both places.)、

If you need a static or global variable of a class type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a "smart" pointer, since the smart pointer's destructor will have the order-of-destructor issue that we are trying to avoid.

Classes

Doing Work in Constructors

在构造函数中避免做复杂的初始化(特别,能失败或需要调用虚函数)

Decision: Constructors should never call virtual functions or attempt to raise non-fatal failures. If your object requires non-trivial initialization, consider using a factory function or Init() method.

Initialization

如果类定义了成员变量,必须在类中定义一个初始化所有成员变量的初始化函数 或构造函数(可以是默认构造函数)。如果没有定义任何默认构造函数. 编译器 将自动生产一个默认的构造函数,使得一些没被初始化或初始化位不合理的值。

Decision: Use in-class member initialization for simple initializations, especially when a member variable must be initialized the same way in more than one constructor.

If your class defines member variables that aren't initialized in-class, and if it has no other constructors, you must define a default constructor (one that takes no arguments).

If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor.

Explicit Constructors

对单个参数的构造函数使用 C++ 关键字 explicit.

Decision: We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name);

The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments.

Finally, constructors that take only an initializerlist may be non-explicit. This is to permit construction of your type using the assigment form for brace init lists (i.e. MyType m = {1, 2} ).

Copy Constructors

仅在代码中需要拷贝一个类对象的时候使用拷贝构造函数; 大部分情况下都不需要, 此时应使用 DISALLOW_COPY_AND_ASSIGN.

Decision: Few classes need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer instead of by value, and you can store pointers rather than objects in an STL container.

If your class needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy constructor and assignment operator.

If your class does not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the private: section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error).

For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used:

// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
  TypeName(const TypeName&);               \
  void operator=(const TypeName&)

Then, in class Foo:

class Foo {
 public:
  Foo(int f);
  ~Foo();

 private:
  DISALLOW_COPY_AND_ASSIGN(Foo);
};

Delegating and inheriting constructors

使用委托和继承构造函数,当他们减少重复代码。

Decision: Use delegating and inheriting constructors when they reduce boilerplate and improve readability. Be cautious about inheriting constructors when your derived class has new member variables. Inheriting constructors may still be appropriate in that case if you can use in-class member initialization for the derived class's member variables.

Structs vs. Classes

仅当只有数据时使用 struct, 其它一概使用 class.

structs should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, destructor, Initialize(), Reset(), Validate().

If more functionality is required, a class is more appropriate. If in doubt, make it a class.

For consistency with STL, you can use struct instead of class for functors(仿函数) and traits(特性).

Note that member variables in structs and classes have different naming rules.

Inheritance

使用组合常常比使用继承更合理. 如果使用继承的话, 定义为 public 继承.

定义: 当子类继承基类时, 子类包含了父基类所有数据及操作的定义. C++ 实践中, 继承主要用于两种场合: 实现继承 (implementation inheritance), 子类继承父类的实现代码; 接口继承 (interface inheritance), 子类仅继承父类的方法名称.

Decision: All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead.

Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar "is a kind of" Foo.

Make your destructor virtual if necessary. If your class has virtual methods, its destructor should be virtual.

Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private.

When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not.

Multiple Inheritance

真正需要用到多重实现继承的情况少之又少. 只在以下情况我们才允许多重继承: 最多只有一个基类是非抽象类; 其它基类都是以 Interface 为后缀的 纯接口类.

Decision: Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure interfaces. In order to ensure that they remain pure interfaces, they must end with the Interface suffix.

Note: There is an exception to this rule on Windows.

Interfaces

接口是指满足特定条件的类, 这些类以 Interface 为后缀,不强制.

定义: 当一个类满足以下要求时, 称之为纯接口:

  • 只有纯虚函数 (“=0”) 和静态函数 (除了下文提到的析构函数).
  • 没有非静态数据成员.
  • 没有定义任何构造函数. 如果有, 也不能带有参数, 并且必须为 protected.
  • 如果它是一个子类, 也只能从满足上述条件并以 Interface 为后缀的类继承.

    Decision:

A class may end with Interface only if it meets the above requirements. however: classes that meet the above requirements are not required to end with Interface.

Operator Overloading

除少数特定环境外,不要重载运算符. 不要自己定义字义。

Decision: In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the class might be forward-declared.

Do not overload operator"", i.e. do not introduce user-defined literals.

However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container.

Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why.

Access Control

将所有数据成员声明为 private, 并根据需要提供相应的存取函数(一些技术原 因,允许测试类的数据成员位protected,当使用Google Test). 例如, 某个名 为 foo_ 的变量, 其取值函数是 foo(). 还可能需要一个赋值函数set_foo(). 例外:static const的数据成员(通常称为kFoo)不需要private.

The definitions of accessors are usually inlined in the header file.

Declaration Order

在类中使用特定的声明顺序: public: 在 private: 之前, 成员函数在数据成员 (变量) 前;

Your class definition should start with its public: section, followed by its protected: section and then its private: section. If any of these sections are empty, omit them.

Within each section, the declarations generally should be in the following order:

  • Typedefs and Enums
  • Constants (static const data members)
  • Constructors
  • Destructor
  • Methods, including static methods
  • Data Members (except static const data members)

Friend declarations should always be in the private section, and the DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end of the private: section. It should be the last thing in the class.

Method definitions in the corresponding .cc file should be the same as the declaration order, as much as possible.

Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline.

Write Short Functions

倾向编写简短, 凝练的函数.

如果函数超过 40 行, 可以思索一下能不能在不影响程序结构的前提下对其进行分割.

Google-Specific Magic

Ownership and Smart Pointers

对动态分配的对象只有一个固定的隶属折。传递隶属使用智能指针。

  • Definition:

    "Ownership" is a bookkeeping technique for managing dynamically allocated memory (and other resources). The owner of a dynamically allocated object is an object or function that is responsible for ensuring that it is deleted when no longer needed. Ownership can sometimes be shared, in which case the last owner is typically responsible for deleting it. Even when ownership is not shared, it can be transferred from one piece of code to another.

    "Smart" pointers are classes that act like pointers, e.g. by overloading the * and -> operators. Some smart pointer types can be used to automate ownership bookkeeping, to ensure these responsibilities are met. std::unique_ptr is a smart pointer type introduced in C++11, which expresses exclusive ownership of a dynamically allocated object; the object is deleted when the std::unique_ptr goes out of scope. It cannot be copied, but can be moved to represent ownership transfer. shared_ptr is a smart pointer type which expresses shared ownership of a dynamically allocated object. shared_ptrs can be copied; ownership of the object is shared among all copies, and the object is deleted when the last shared_ptr is destroyed.

  • Cons:
    • Ownership must be represented and transferred via pointers (whether smart or plain). Pointer semantics are more complicated than value semantics, especially in APIs: you have to worry not just about ownership, but also aliasing, lifetime, and mutability, among other issues.
    • The performance costs of value semantics are often overestimated, so the performance benefits of ownership transfer might not justify the readability and complexity costs.
    • APIs that transfer ownership force their clients into a single memory management model.
    • Code using smart pointers is less explicit about where the resource releases take place.
    • std::uniqueptr expresses ownership transfer using C++11's move semantics, which are generally forbidden in Google code, and may confuse some programmers.
    • Shared ownership can be a tempting alternative to careful ownership design, obfuscating the design of a system.
    • Shared ownership requires explicit bookkeeping at run-time, which can be costly.
    • In some cases (e.g. cyclic references), objects with shared ownership may never be deleted.
    • Smart pointers are not perfect substitutes for plain pointers.
  • Decision:

    If dynamic allocation is necessary, prefer to keep ownership with the code that allocated it. If other code needs access to the object, consider passing it a copy, or passing a pointer or reference without transferring ownership. Prefer to use std::unique_ptr to make ownership transfer explicit. For example:

    std::unique_ptr<Foo> FooFactory();
    void FooConsumer(std::unique_ptr<Foo> ptr);
    

    Do not design your code to use shared ownership without a very good reason. One such reason is to avoid expensive copy operations, but you should only do this if the performance benefits are significant, and the underlying object is immutable (i.e. shared_ptr<const Foo>). If you do use shared ownership, prefer to use shared_ptr.

    Do not use scoped_ptr in new code unless you need to be compatible with older versions of C++. Never use linked_ptr or std::auto_ptr. In all three cases, use std::unique_ptr instead.

cpplint

使用 cpplint.py 检查风格错误.

False positives can be ignored by putting // NOLINT at the end of the line.

download cpplint.py separately.

Other C++ Features

Reference Arguments

所有按引用传递的参数必须加上 const.

Decision: Within function parameter lists all references must be const:

void Foo(const string &in, string *out);

In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters except when required by convention, e.g., swap().

However, there are some instances where using const T* is preferable to const T& for input parameters. For example:

  • You want to pass in a null pointer.
  • The function saves a pointer or reference to the input.

So if you choose const T* rather than const T&, do so for a concrete reason; otherwise it will likely confuse readers by making them look for an explanation that doesn't exist.

Rvalue references

Do not use rvalue references, std::forward, std::move_iterator, or std::move_if_noexcept. Use the single-argument form of std::move only with non-copyable arguments.

Decision: Do not use rvalue references, and do not use the std::forward or std::move_if_noexcept utility functions (which are essentially just casts to rvalue reference types), or std::move_iterator. Use single-argument std::move only with objects that are not copyable (e.g. std::unique_ptr), or in templated code with objects that might not be copyable.

Function Overloading

仅在读者看到调用能很好的知道发生了啥而不是首先去搞清楚哪个重载被调用时 使用重载函数 (含构造函数).

Decision: If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., AppendString(), AppendInt() rather than just Append().

Default Arguments

我们不允许使用缺省函数参数,除了以下说明的有限场合。如果合适,用函数重 载来模仿它们。

Decision: So except as described below, we require all arguments to be explicitly specified.

One specific exception is when the function is a static function (or in an unnamed namespace) in a .cc file. In this case, the cons don't apply since the function's use is so localized.

Another specific exception is when default arguments are used to simulate variable-length argument lists.

// Support up to 4 params by using a default empty AlphaNum.
string StrCat(const AlphaNum &a,
              const AlphaNum &b = gEmptyAlphaNum,
              const AlphaNum &c = gEmptyAlphaNum,
              const AlphaNum &d = gEmptyAlphaNum);

Variable-Length Arrays and alloca()

我们不允许使用变长数组和 alloca().

Decision: Use a safe allocator instead, such as scoped_ptr/scoped_array.

Friends

我们允许合理的使用友元类及友元函数.

Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of friend is to have a FooBuilder class be a friend of Foo so that it can construct the inner state of Foo correctly, without exposing this state to the world. In some cases it may be useful to make a unittest class a friend of the class it tests.

Exceptions

我们不使用 C++ 异常.

On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions.

Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project.

This prohibition also applies to the exception-related features added in C++11, such as noexcept, std::exception_ptr, and std::nested_exception.

There is an exception to this rule (no pun intended) for Windows code.

Run-Time Type Information (RTTI)

禁止使用 RTTI.

RTTI allows a programmer to query the C++ class of an object at run time. This is done by use of typeid or dynamic_cast.

Decision: RTTI has legitimate uses but is prone to abuse, so you must be careful when using it. You may use it freely in unittests, but avoid it when possible in other code. In particular, think twice before using RTTI in new code. If you find yourself needing to write code that behaves differently based on the class of an object, consider one of the following alternatives to querying the type:

  • Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself.
  • If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system.

When the logic of a program guarantees that a given instance of a base class is in fact an instance of a particular derived class, then a dynamic_cast may be used freely on the object. Usually one can use a static_cast as an alternative in such situations.

Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags. Moreover, workarounds disguise your true intent.

Casting

使用 C++ 的类型转换, 如 static_cast<>(). 不要使用 int y = (int)x 或 int y = int(x) 等转换方式;

Decision: Do not use C-style casts. Instead, use these C++-style casts.

  • Use static_cast as the equivalent of a C-style cast that does value conversion, or when you need to explicitly up-cast a pointer from a class to its superclass.
  • Use const_cast to remove the const qualifier (see const).
  • Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues.
  • You may use dynamic_cast freely in unittests, but avoid it when possible in other code.

Streams

只在记录日志时使用流

Decision: Do not use streams, except where required by a logging interface. Use printf-like routines instead.

Either path would yield different advantages and disadvantages, and there is not a clearly superior solution. The simplicity doctrine mandates we settle on one of them though, and the majority decision was on printf + read/write.

Preincrement and Predecrement

对于迭代器和其他模板对象使用前缀形式 (++i) 的自增, 自减运算符.

Decision: For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment.

Use of const

我们强烈建议你在任何可能的情况下都要使用 const. 对于C++11中一些const, constexpr 是更好的选择。

const variables, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use const whenever it makes sense to do so:

  • If a function does not modify an argument passed by reference or by pointer, that argument should be const.
  • Declare methods to be const whenever possible. Accessors should almost always be const. Other methods should be const if they do not modify any data members, do not call any non-const methods, and do not return a non-const pointer or non-const reference to a data member.
  • Consider making data members const whenever they do not need to be modified after construction.

The mutable keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first.

That said, while we encourage putting const first, we do not require it. But be consistent with the code around you!

Use of constexpr

In C++11, use constexpr to define true constants or to ensure constant initialization.

Decision: constexpr definitions enable a more robust specification of the constant parts of an interface. Use constexpr to specify true constants and the functions that support their definitions. Avoid complexifying function definitions to enable their use with constexpr. Do not use constexpr to force inlining.

Integer Types

Of the built-in C++ integer types, the only one used is int. If a program needs a variable of a different size, use a precise-width integer type from <stdint.h>, such as int16_t. If your variable represents a value that could ever be greater than or equal to 231 (2GiB), use a 64-bit type such as int64_t. Keep in mind that even if your value won't ever be too large for an int, it may be used in intermediate calculations which may require a larger type. When in doubt, choose a larger type.

Decision: <stdint.h> defines types like int16_t, uint32_t, int64_t, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guarantee on the size of an integer. Of the C integer types, only int should be used. When appropriate, you are welcome to use standard types like size_t and ptrdiff_t.

For integers we know can be "big", use int64_t.

You should not use the unsigned integer types such as uint32t, unless there is a valid reason such as representing a bit pattern rather than a number, or you need defined overflow modulo 2N. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this.

Use care when converting integer types. Integer conversions and promotions can cause non-intuitive behavior.

So, document that a variable is non-negative using assertions. Don't use an unsigned type.

64-bit Portability

代码应该对 64 位和 32 位系统友好. 处理打印, 比较, 结构体对齐时应切记:

  • printf() specifiers for some types are not cleanly portable between 32-bit and 64-bit systems. C99 defines some portable format specifiers. Unfortunately, MSVC 7.1 does not understand some of these specifiers and the standard is missing a few, so we have to define our own ugly versions in some cases (in the style of the standard include file inttypes.h):
    // printf macros for size_t, in the style of inttypes.h
    #ifdef _LP64
    #define __PRIS_PREFIX "z"
    #else
    #define __PRIS_PREFIX
    #endif
    
    // Use these macros after a % in a printf format string
    // to get correct 32/64 bit behavior, like this:
    // size_t size = records.size();
    // printf("%"PRIuS"\n", size);
    
    #define PRIdS __PRIS_PREFIX "d"
    #define PRIxS __PRIS_PREFIX "x"
    #define PRIuS __PRIS_PREFIX "u"
    #define PRIXS __PRIS_PREFIX "X"
    #define PRIoS __PRIS_PREFIX "o"
    
Type DO NOT use DO use Notes
=void *=(or any pointer) %lx %p  
int64_t %qd,%lld %"PRId64"  
uint64_t %qu,%llu,%llx %"PRIu64",%"PRIx64"  
size_t %u %"PRIuS",%"PRIxS" C99 sepecifies %zu
ptrdiff_t %d %"PRIdS" C99 sepecifies %td

Note that the PRI* macros expand to independent strings which are concatenated by the compiler. Hence if you are using a non-constant format string, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., after the % when using the PRI* macros. So, e.g. printf("x = %30"PRIuS"\n", x) would expand on 32-bit Linux to printf("x = %30" "u" "\n", x), which the compiler will treat as printf("x = %30u\n", x).

  • Remember that sizeof(void *) != sizeof(int). Use intptr_t if you want a pointer-sized integer.
  • You may need to be careful with structure alignments, particularly for structures being stored on disk. Any class/structure with a int64t/uint64t member will by default end up being 8-byte aligned on a 64-bit system. If you have such structures being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectures. Most compilers offer a way to alter structure alignment. For gcc, you can use __attribute__((packed)). MSVC offers #pragma pack() and __declspec(align()).
  • Use the LL or ULL suffixes as needed to create 64-bit constants. For example:
    int64_t my_value = 0x123456789LL;
    uint64_t my_mask = 3ULL << 48;
    
  • If you really need different code on 32-bit and 64-bit systems, use #ifdef _LP64 to choose between the code variants. (But please avoid this if possible, and keep any such changes localized.)

Preprocessor Macros

使用宏时要非常谨慎, 尽量以内联函数, 枚举和常量代替之.

Instead of using a macro to inline performance-critical code, use an inline function. Instead of using a macro to store a constant, use a const variable. Instead of using a macro to "abbreviate" a long variable name, use a reference. Instead of using a macro to conditionally compile code … well, don't do that at all (except, of course, for the #define guards to prevent double inclusion of header files). It makes testing much more difficult.

Macros can do things these other techniques cannot, and you do see them in the codebase, especially in the lower-level libraries. And some of their special features (like stringifying(#), concatenation(##), and so forth) are not available through the language proper. But before using a macro, consider carefully whether there's a non-macro way to achieve the same result.

The following usage pattern will avoid many problems with macros; if you use macros, follow it whenever possible:

  • Don't define macros in a .h file.
  • #define macros right before you use them, and #undef them right after.
  • Do not just #undef an existing macro before replacing it with your own; instead, pick a name that's likely to be unique.
  • Try not to use macros that expand to unbalanced C++ constructs, or at least document that behavior well.
  • Prefer not using ## to generate function/class/variable names.

0 and nullptr/NULL

整数用 0, 实数用 0.0, 指针用 nullptr(或NULL), 字符 (串) 用 '\0'.

For pointers (address values), there is a choice between 0, NULL, and nullptr. For projects that allow C++11 features, use nullptr.

In fact, some C++ compilers provide special definitions of NULL which enable them to give useful warnings, particularly in situations where sizeof(NULL) is not equal to sizeof(0).

sizeof

尽可能用 sizeof(varname) 代替 sizeof(type).

Use sizeof(varname) when you take the size of a particular variable. sizeof(varname) will update appropriately if someone changes the variable type either now or later. You may use sizeof(type) for code unrelated to any particular variable, such as code that manages an external or internal data format where a variable of an appropriate C++ type is not convenient.

Struct data;
memset(&data, 0, sizeof(data));

memset(&data, 0, sizeof(Struct));

if (raw_size < sizeof(int)) {
  LOG(ERROR) << "compressed record not big enough for count: " << raw_size;
  return false;
}
</p>

auto

仅使用auto来避免杂乱的类型名。继续使用明示的类型声明当有助于读取,仅对本地变量使用auto。

Decision: auto is permitted, for local variables only. . Never assign a braced initializer list to an auto-typed variable.

The auto keyword is also used in an unrelated C++11 feature: it's part of the syntax for a new kind of function declaration with a trailing return type. Function declarations with trailing return types are not permitted.

Brace Initialization

可用 brace initialization.

Never assign a braced-init-list to an auto local variable. In the single element case, what this means can be confusing.

auto d = {1.23};        // d is an initializer_list<double>
auto d = double{1.23};  // Good -- d is a double, not an initializer_list.

Lambda expressions

不要使用lamba表达式,或相关的 std::function和std::bind程序。

Boost

只使用 Boost 中被认可的库.

Decision:

  • Call Traits from boost/call_traits.hpp
  • Compressed Pair from boost/compressed_pair.hpp
  • The Boost Graph Library (BGL) from boost/graph, except serialization (adj_list_serialize.hpp) and parallel/distributed algorithms and data structures (boost/graph/parallel/* and boost/graph/distributed/*).
  • Property Map from boost/property_map, except parallel/distributed property maps (boost/property_map/parallel/*).
  • The part of Iterator that deals with defining iterators: boost/iterator/iterator_adaptor.hpp, boost/iterator/iterator_facade.hpp, and boost/function_output_iterator.hpp
  • The part of Polygon that deals with Voronoi diagram construction and doesn't depend on the rest of Polygon: boost/polygon/voronoi_builder.hpp, boost/polygon/voronoi_diagram.hpp, and boost/polygon/voronoi_geometry_type.hpp
  • Bimap from boost/bimap
  • Statistical Distributions and Functions from boost/math/distributions

The following libraries are permitted, but their use is discouraged because they've been superseded by standard libraries in C++11:

  • Array from boost/array.hpp: use std::array instead.
  • Pointer Container from boost/ptr_container: use containers of std::unique_ptr instead.

C++11

适宜的使用C++11的库和语言扩展。再工程中使用c++11的特性前,考虑移植不同的环境。

Decision: C++11 features may be used unless specified otherwise. In addition to what's described in the rest of the style guide, the following C++11 features may not be used:

  • Functions with trailing return types, e.g. writing auto foo() ->int; instead of int foo();, because of a desire to preserve stylistic consistency with the many existing function declarations.
  • Compile-time rational numbers (<ratio>), because of concerns that it's tied to a more template-heavy interface style.
  • The <cfenv> and <fenv.h> headers, because many compilers do not support those features reliably.
  • Lambda expressions, or the related std::function or std::bind utilities.

Naming

General Naming Rules

函数命名, 变量命名, 文件命名应具备描述性; 不要过度缩写.

int price_count_reader;    // No abbreviation.
int num_errors;            // "num" is a widespread convention.
int num_dns_connections;   // Most people know what "DNS" stands for.

int n;                     // Meaningless.
int nerr;                  // Ambiguous abbreviation.
int n_comp_conns;          // Ambiguous abbreviation.
int wgc_connections;       // Only your group knows what this stands for.
int pc_reader;             // Lots of things can be abbreviated "pc".
int cstmr_id;              // Deletes internal letters.

File Names

文件名要全部小写, 可以包含下划线 (_) 或连字符 (-). 按项目约定来.如果没有本地模式遵循,用"_".

Examples of acceptable file names:

my_useful_class.cc
my-useful-class.cc
myusefulclass.cc
myusefulclass_test.cc // _unittest and _regtest are deprecated.

C++ files should end in .cc and header files should end in .h.

Inline functions must be in a .h file. If your inline functions are very short, they should go directly into your .h file. However, if your inline functions include a lot of code, they may go into a third file that ends in -inl.h. In a class with a lot of inline code, your class could have three files:

url_table.h      // The class declaration.
url_table.cc     // The class definition.
url_table-inl.h  // Inline functions that include lots of code.

Type Names

类型名称的每个单词首字母均大写, 不包含下划线: MyExcitingClass, MyExcitingEnum.

The names of all types — classes, structs, typedefs, and enums — have the same naming convention. Type names should start with a capital letter and have a capital letter for each new word. No underscores. For example:

// classes and structs
class UrlTable { ...
class UrlTableTester { ...
struct UrlTableProperties { ...

// typedefs
typedef hash_map<UrlTableProperties *, string> PropertiesMap;

// enums
enum UrlTableErrors { ...

Variable Names

变量名一律小写, 单词之间用下划线连接. 类的成员变量以下划线结尾, 如:my_exciting_local_variable, my_exciting_member_variable_.

  • Common Variable names For example:
    string table_name;  // OK - uses underscore.
    string tablename;   // OK - all lowercase.
    string tableName;   // Bad - mixed case.
    
  • Class Data Members Data members (also called instance variables or member variables) are lowercase with optional underscores like regular variable names, but always end with a trailing underscore.
    string table_name_;  // OK - underscore at end.
    string tablename_;   // OK.
    
  • Struct Variables Data members in structs should be named like regular variables without the trailing underscores that data members in classes have.
    struct UrlTableProperties {
      string name;
      int num_entries;
    }
    
  • Global Variables There are no special requirements for global variables, which should be rare in any case, but if you use one, consider prefixing it with g_ or some other marker to easily distinguish it from local variables.

Constant Names

在名称前加 k: kDaysInAWeek.

All compile-time constants, whether they are declared locally, globally, or as part of a class, follow a slightly different naming convention from other variables. Use a k followed by words with uppercase first letters:

const int kDaysInAWeek = 7;

Function Names

常规函数使用大小写混合, 取值和设值函数则要求与变量名匹配: MyExcitingFunction(), MyExcitingMethod(), my_exciting_member_variable(), set_my_exciting_member_variable()

  • Regular Functions Functions should start with a capital letter and have a capital letter for each new word. No underscores.

    If your function crashes upon an error, you should append OrDie to the function name. This only applies to functions which could be used by production code and to errors that are reasonably likely to occur during normal operation.

    AddTableEntry()
    DeleteUrl()
    OpenFileOrDie()
    
  • Accessors and Mutators Accessors and mutators (get and set functions) should match the name of the variable they are getting and setting. This shows an excerpt of a class whose instance variable is num_entries_.
    class MyClass {
     public:
      ...
      int num_entries() const { return num_entries_; }
      void set_num_entries(int num_entries) { num_entries_ = num_entries; }
    
     private:
      int num_entries_;
    };
    

    You may also use lowercase letters for other very short inlined functions.

Namespace Names

名字空间用小写字母命名, 并基于项目名称和目录结构: google_awesome_project.

Enumerator Names

枚举的命名应当和 常量 或 宏 一致: kEnumName 或是 ENUM_NAME.

Preferably, the individual enumerators should be named like constants. However, it is also acceptable to name them like macros. The enumeration name, UrlTableErrors (and AlternateUrlTableErrors), is a type, and therefore mixed case.

enum UrlTableErrors {
  kOK = 0,
  kErrorOutOfMemory,
  kErrorMalformedInput,
};
enum AlternateUrlTableErrors {
  OK = 0,
  OUT_OF_MEMORY = 1,
  MALFORMED_INPUT = 2,
};

Until January 2009, the style was to name enum values like macros. This caused problems with name collisions between enum values and macros. Hence, the change to prefer constant-style naming was put in place. New code should prefer constant-style naming if possible.

Macro Names

你并不打算 使用宏, 对吧? 如果你一定要用, 像这样命名: MY_MACRO_THAT_SCARES_SMALL_CHILDREN.

Please see the description of macros; in general macros should not be used. However, if they are absolutely needed, then they should be named with all capitals and underscores.

#define ROUND(x) ...
#define PI_ROUNDED 3.0

Exceptions to Naming Rules

如果你命名的实体与已有 C/C++ 实体相似, 可参考现有命名策略.

  • bigopen() function name, follows form of open()
  • uint typedef
  • bigpos struct or class, follows form of pos
  • sparse_hash_map STL-like entity; follows STL naming conventions
  • LONGLONG_MAX a constant, as in INT_MAX

Comments

Comment Style

使用 // 或 /* */, 统一就好.

You can use either the / or the /* * syntax; however, // is much more common.

File Comments

在每一个文件开头加入版权公告, 然后是文件内容描述.

  • Legal Notice and Author Line Every file should contain license boilerplate. Choose the appropriate boilerplate for the license used by the project (for example, Apache 2.0, BSD, LGPL, GPL).

    If you make significant changes to a file with an author line, consider deleting the author line.

  • File Contents Every file should have a comment at the top describing its contents.

    Generally a .h file will describe the classes that are declared in the file with an overview of what they are for and how they are used. A .cc file should contain more information about implementation details or discussions of tricky algorithms. If you feel the implementation details or a discussion of the algorithms would be useful for someone reading the .h, feel free to put it there instead, but mention in the .cc that the documentation is in the .h file.

    Do not duplicate comments in both the .h and the .cc.

Class Comments

每个类的定义都要附带一份注释, 描述类的功能和用法.

// Iterates over the contents of a GargantuanTable.  Sample usage:
//    GargantuanTableIterator* iter = table->NewIterator();
//    for (iter->Seek("foo"); !iter->done(); iter->Next()) {
//      process(iter->key(), iter->value());
//    }
//    delete iter;
class GargantuanTableIterator {
  ...
};

If you have already described a class in detail in the comments at the top of your file feel free to simply state "See comment at top of file for a complete description", but be sure to have some sort of comment.

Document the synchronization assumptions the class makes, if any. If an instance of the class can be accessed by multiple threads, take extra care to document the rules and invariants surrounding multithreaded use.

Function Comments

函数声明处注释描述函数功能; 定义处描述函数实现.

  • 函数声明: 注释位于声明之前, 对函数功能及用法进行描述. 注释使用叙述式 (“Opens the file”) 而非指令式 (“Open the file”); 注释只是为了描述函数, 而不是命令函数做什么. 通常, 注释不会描述函数如何工作. 那是函数定义部分的事情.

    函数声明处注释的内容:

    • 函数的输入输出.
    • 对类成员函数而言: 函数调用期间对象是否需要保持引用参数, 是否会释放这些参数.
    • 如果函数分配了空间, 需要由调用者释放.
    • 参数是否可以为 NULL.
    • 是否存在函数使用上的性能隐患.
    • 如果函数是可重入的, 其同步前提是什么?

    举例如下:

    // Returns an iterator for this table.  It is the client's
    // responsibility to delete the iterator when it is done with it,
    // and it must not use the iterator once the GargantuanTable object
    // on which the iterator was created has been deleted.
    //
    // The iterator is initially positioned at the beginning of the table.
    //
    // This method is equivalent to:
    //    Iterator* iter = table->NewIterator();
    //    iter->Seek("");
    //    return iter;
    // If you are going to immediately seek to another place in the
    // returned iterator, it will be faster to use NewIterator()
    // and avoid the extra seek.
    Iterator* GetIterator() const;
    

    但也要避免罗罗嗦嗦, 或做些显而易见的说明. 下面的注释就没有必要加上 “returns false otherwise”, 因为已经暗含其中了:

    // Returns true if the table cannot hold any more entries.
    bool IsTableFull();
    

    注释构造/析构函数时, 切记读代码的人知道构造/析构函数是干啥的, 所以“destroys this object” 这样的注释是没有意义的. 注明构造函数对参数做了什么 (例如, 是否取得指针所有权) 以及析构函数清理了什么. 如果都是些无关紧要的内容, 直接省掉注释. 析构函数前没有注释是很正常的.

  • 函数定义: 每个函数定义时要用注释说明函数功能和实现要点. 比如说说你用的编程技巧, 实现的大致步骤, 或解释如此实现的理由, 为什么前半部分要加锁而后半部分不需要.

    不要 从 .h 文件或其他地方的函数声明处直接复制注释. 简要重述函数功能是可以的, 但注释重点要放在如何实现上.

Variable Comments

通常变量名本身足以很好说明变量用途. 某些情况下, 也需要额外的注释说明.

  • Class Data Members Each class data member (also called an instance variable or member variable) should have a comment describing what it is used for. If the variable can take sentinel values with special meanings, such as a null pointer or -1, document this. For example:
    private:
     // Keeps track of the total number of entries in the table.
     // Used to ensure we do not go over the limit. -1 means
     // that we don't yet know how many entries the table has.
     int num_total_entries_;
    
  • Global Variables As with data members, all global variables should have a comment describing what they are and what they are used for. For example:
    // The total number of tests cases that we run through in this regression test.
    const int kNumTestCases = 6;
    

Implementation Comments

对于代码中巧妙的, 晦涩的, 有趣的, 重要的地方加以注释.

  • Class Data Members Tricky or complicated code blocks should have comments before them. Example:
    // Divide result by two, taking into account that x
    // contains the carry from the add.
    for (int i = 0; i < result->size(); i++) {
      x = (x << 8) + (*result)[i];
      (*result)[i] = x >> 1;
      x &= 1;
    }
    
  • Line Comments Also, lines that are non-obvious should get a comment at the end of the line. These end-of-line comments should be separated from the code by 2 spaces. Example:
    // If we have enough memory, mmap the data portion too.
    mmap_budget = max<int64>(0, mmap_budget - index_->length());
    if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock))
      return;  // Error already logged.
    

    Note that there are both comments that describe what the code is doing, and comments that mention that an error has already been logged when the function returns.

    If you have several comments on subsequent lines, it can often be more readable to line them up:

    DoSomething();                  // Comment here so the comments line up.
    DoSomethingElseThatIsLonger();  // Comment here so there are two spaces between
                                    // the code and the comment.
    { // One space before comment when opening a new scope is allowed,
      // thus the comment lines up with the following comments and code.
      DoSomethingElse();  // Two spaces before line comments normally.
    }
    DoSomething(); /* For trailing block comments, one space is fine. */
    
  • nullptr/NULL, true/false, 1, 2, 3… When you pass in a null pointer, boolean, or literal integer values to functions, you should consider adding a comment about what they are, or make your code self-documenting by using constants. For example, compare:
    bool success = CalculateSomething(interesting_value,
                                      10,
                                      false,
                                      NULL);  // What are these arguments??
    

    versus:

    bool success = CalculateSomething(interesting_value,
                                      10,     // Default base value.
                                      false,  // Not the first time we're calling this.
                                      NULL);  // No callback.
    

    Or alternatively, constants or self-describing variables:

    const int kDefaultBaseValue = 10;
    const bool kFirstTimeCalling = false;
    Callback *null_callback = NULL;
    bool success = CalculateSomething(interesting_value,
                                      kDefaultBaseValue,
                                      kFirstTimeCalling,
                                      null_callback);
    
  • Don'ts Note that you should never describe the code itself. Assume that the person reading the code knows C++ better than you do, even though he or she does not know what you are trying to do:
    // Now go through the b array and make sure that if i occurs,
    // the next element is i+1.
    ...        // Geez.  What a useless comment.
    

Punctuation, Spelling and Grammar

注意标点, 拼写和语法; 写的好的注释比差的要易读的多.

Comments should be as readable as narrative text, with proper capitalization and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style.

TODO Comments

对那些临时的, 短期的解决方案, 或已经够好但仍不完美的代码使用 TODO 注释.

TODOs should include the string TODO in all caps, followed by the name, e-mail address, or other identifier of the person who can best provide context about the problem referenced by the TODO. A colon is optional. The main purpose is to have a consistent TODO format that can be searched to find the person who can provide more details upon request. A TODO is not a commitment that the person referenced will fix the problem. Thus when you create a TODO, it is almost always your name that is given.

// TODO(kl@gmail.com): Use a "*" here for concatenation operator.
// TODO(Zeke) change this to use relations.

If your TODO is of the form "At a future date do something" make sure that you either include a very specific date ("Fix by November 2005") or a very specific event ("Remove this code when all clients can handle XML responses.").

Deprecation Comments

用DEPRECATED注释来标识废弃的接口。

You can mark an interface as deprecated by writing a comment containing the word DEPRECATED in all caps. The comment goes either before the declaration of the interface or on the same line as the declaration.

After the word DEPRECATED, write your name, e-mail address, or other identifier in parentheses.

A deprecation comment must include simple, clear directions for people to fix their callsites. In C++, you can implement a deprecated function as an inline function that calls the new interface point.

Formatting

Line Length

每一行代码字符数不超过 80.

80 characters is the maximum.

  • Exception: if a comment line contains an example command or a literal URL longer than 80 characters, that line may be longer than 80 characters for ease of cut and paste.
  • Exception: an #include statement with a long path may exceed 80 columns. Try to avoid situations where this becomes necessary.
  • Exception: you needn't be concerned about header guards that exceed the maximum length.

Non-ASCII Characters

量不使用非 ASCII 字符, 使用时必须使用 UTF-8 编码.

Hex encoding is also OK, and encouraged where it enhances readability — for example, "\xEF\xBB\xBF", or, even more simply, u8"\uFEFF", is the Unicode zero-width no-break space character, which would be invisible if included in the source as straight UTF-8.

Use the u8 prefix to guarantee that a string literal containing \uXXXX escape sequences is encoded as UTF-8. Do not use it for strings containing non-ASCII characters encoded as UTF-8, because that will produce incorrect output if the compiler does not interpret the source file as UTF-8.

You shouldn't use the C++11 char16t and char32t character types, since they're for non-UTF-8 text. For similar reasons you also shouldn't use wchart (unless you're writing code that interacts with the Windows API, which uses wchart extensively).

Spaces vs. Tabs

只使用空格, 每次缩进 2 个空格.

We use spaces for indentation. Do not use tabs in your code. You should set your editor to emit spaces when you hit the tab key.

Function Declarations and Definitions

返回类型和函数名在同一行, 参数也尽量放在同一行.

Functions look like this:

ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
  DoSomething();
  ...
}

If you have too much text to fit on one line:

ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,
                                             Type par_name3) {
  DoSomething();
  ...
}

or if you cannot fit even the first parameter:

ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
    Type par_name1,  // 4 space indent
    Type par_name2,
    Type par_name3) {
  DoSomething();  // 2 space indent
  ...
}

注意以下几点:

  • 如果不能使返回值和函数名在同一行,分开它们;
  • 如果返回值总是和函数名被分开,不要缩进;
  • 左圆括号总是和函数名在同一行;
  • 函数名和左圆括号间没有空格;
  • 圆括号与参数间没有空格;
  • 左大括号总在最后一个参数同一行的末尾处;
  • 右大括号总是单独位于函数最后一行;
  • 右圆括号和左大括号间总是有一个空格;
  • 函数声明和实现处的所有形参名称必须保持一致;
  • 所有形参应尽可能对齐;
  • 缺省缩进为 2 个空格;
  • 换行后的参数保持 4 个空格的缩进;

If some parameters are unused, comment out the variable name in the function definition:

// Always have named parameters in interfaces.
class Shape {
 public:
  virtual void Rotate(double radians) = 0;
}

// Always have named parameters in the declaration.
class Circle : public Shape {
 public:
  virtual void Rotate(double radians);
}

// Comment out unused named parameters in definitions.
void Circle::Rotate(double /*radians*/) {}
// Bad - if someone wants to implement later, it's not clear what the
// variable means.
void Circle::Rotate(double) {}

Function Calls

尽量放在同一行, 否则, 将实参封装在圆括号中.

Function calls have the following format:

bool retval = DoSomething(argument1, argument2, argument3);

If the arguments do not all fit on one line, they should be broken up onto multiple lines, with each subsequent line aligned with the first argument. Do not add spaces after the open paren or before the close paren:

bool retval = DoSomething(averyveryveryverylongargument1,
                          argument2, argument3);

If the function has many arguments, consider having one per line if this makes the code more readable:

bool retval = DoSomething(argument1,
                          argument2,
                          argument3,
                          argument4);

Arguments may optionally all be placed on subsequent lines, with one line per argument:

if (...) {
  ...
  ...
  if (...) {
    DoSomething(
        argument1,  // 4 space indent
        argument2,
        argument3,
        argument4);
  }

Braced Initializer Lists

如格式化函数调用一样格式化括号列单。

If the braced list follows a name (e.g. a type or variable name), format as if the {} were the parentheses of a function call with that name. If there is no name, assume a zero-length name.

// Examples of braced init list on a single line.
return {foo, bar};
functioncall({foo, bar});
pair<int, int> p{foo, bar};

// When you have to wrap.
SomeFunction(
    {"assume a zero-length name before {"},
    some_other_function_parameter);
SomeType variable{
    some, other, values,
    {"assume a zero-length name before {"},
    SomeOtherType{
        "Very long string requiring the surrounding breaks.",
        some, other values},
    SomeOtherType{"Slightly shorter string",
                  some, other, values}};
SomeType variable{
    "This is too long to fit all in one line"};
MyType m = {  // Here, you could also break before {.
    superlongvariablename1,
    superlongvariablename2,
    {short, interior, list},
    {interiorwrappinglist,
     interiorwrappinglist2}};

Conditionals

倾向于不在圆括号内使用空格. 关键字 else 另起一行.

There are two acceptable formats for a basic conditional statement. One includes spaces between the parentheses and the condition, and one does not.

The most common form is without spaces. Either is fine, but be consistent. If you are modifying a file, use the format that is already present. If you are writing new code, use the format that the other files in that directory or project use. If in doubt and you have no personal preference, do not add the spaces.

if (condition) {  // no spaces inside parentheses
  ...  // 2 space indent.
} else if (...) {  // The else goes on the same line as the closing brace.
  ...
} else {
  ...
}

If you prefer you may add spaces inside the parentheses:

if ( condition ) {  // spaces inside parentheses - rare
  ...  // 2 space indent.
} else {  // The else goes on the same line as the closing brace.
  ...
}

Note that in all cases you must have a space between the if and the open parenthesis. You must also have a space between the close parenthesis and the curly brace, if you're using one.

if(condition)     // Bad - space missing after IF.
if (condition){   // Bad - space missing before {.
if(condition){    // Doubly bad.
if (condition) {  // Good - proper space after IF and before {.

Short conditional statements may be written on one line if this enhances readability. You may use this only when the line is brief and the statement does not use the else clause.

if (x == kFoo) return new Foo();
if (x == kBar) return new Bar();

This is not allowed when the if statement has an else:

// Not allowed - IF statement on one line when there is an ELSE clause
if (x) DoThis();
else DoThat();

In general, curly braces are not required for single-line statements, but they are allowed if you like them; conditional or loop statements with complex conditions or statements may be more readable with curly braces. Some projects require that an if must always always have an accompanying brace.

if (condition)
  DoSomething();  // 2 space indent.

if (condition) {
  DoSomething();  // 2 space indent.
}

However, if one part of an if-else statement uses curly braces, the other part must too:

// Not allowed - curly on IF but not ELSE
if (condition) {
  foo;
} else
  bar;

// Not allowed - curly on ELSE but not IF
if (condition)
  foo;
else {
  bar;
}
// Curly braces around both IF and ELSE required because
// one of the clauses used braces.
if (condition) {
  foo;
} else {
  bar;
}

Loops and Switch Statements

switch 语句可以使用大括号分段. 空循环体应使用 {} 或 continue.

case blocks in switch statements can have curly braces or not, depending on your preference. If you do include curly braces they should be placed as shown below.

If not conditional on an enumerated value, switch statements should always have a default case (in the case of an enumerated value, the compiler will warn you if any values are not handled). If the default case should never execute, simply assert:

switch (var) {
  case 0: {  // 2 space indent
    ...      // 4 space indent
    break;
  }
  case 1: {
    ...
    break;
  }
  default: {
    assert(false);
  }
}

Empty loop bodies should use {} or continue, but not a single semicolon.

while (condition) {
  // Repeat test until it returns false.
}
for (int i = 0; i < kSomeNumber; ++i) {}  // Good - empty body.
while (condition) continue;  // Good - continue indicates no logic.
while (condition);  // Bad - looks like part of do/while loop.

Pointer and Reference Expressions

句点或箭头前后不要有空格. 指针/地址操作符 (*, &) 之后不能有空格.

Note that:

  • There are no spaces around the period or arrow when accessing a member.
  • Pointer operators have no space after the * or &.

When declaring a pointer variable or argument, you may place the asterisk adjacent to either the type or to the variable name

Boolean Expressions

如果一个布尔表达式超过 标准行宽, 断行方式要统一一下.

In this example, the logical AND operator is always at the end of the lines:

if (this_one_thing > this_other_thing &&
    a_third_thing == a_fourth_thing &&
    yet_another && last_one) {
  ...
}

Note that when the code wraps in this example, both of the && logical AND operators are at the end of the line. This is more common in Google code, though wrapping all operators at the beginning of the line is also allowed. Feel free to insert extra parentheses judiciously because they can be very helpful in increasing readability when used appropriately.

Return Values

return 表达式中不要用圆括号包围.

Use parentheses in return expr; only where you would use them in x = expr;.

return result;                  // No parentheses in the simple case.
return (some_long_condition &&  // Parentheses ok to make a complex
        another_condition);     //     expression more readable.
return (value);                // You wouldn't write var = (value);
return(result);                // return is not a function!

Variable and Array Initialization

用 =, ()或{} 均可.

You may choose between =, (), and {}; the following are all correct:

int x = 3;
int x(3);
int x{3};
string name = "Some Name";
string name("Some Name");
string name{"Some Name"};

Be careful when using the {} on a type that takes an initializerlist in one of its constructors. The {} syntax prefers the initializerlist constructor whenever possible. To get the non- initializerlist constructor, use ().

vector<int> v(100, 1);  // A vector of 100 1s.
vector<int> v{100, 1};  // A vector of 100, 1.

Also, the brace form prevents narrowing of integral types. This can prevent some types of programming errors.

int pi(3.14);  // OK -- pi == 3.
int pi{3.14};  // Compile error: narrowing conversion.

Preprocessor Directives

预处理指令不要缩进, 从行首开始.

Even when preprocessor directives are within the body of indented code, the directives should start at the beginning of the line.

// Good - directives at beginning of line
  if (lopsided_score) {
#if DISASTER_PENDING      // Correct -- Starts at beginning of line
    DropEverything();
# if NOTIFY               // OK but not required -- Spaces after #
    NotifyClient();
# endif
#endif
    BackToNormal();
  }

Class Format

访问控制块的声明依次序是 public:, protected:, private:, 每次缩进 1 个 空格.

The basic format for a class declaration (lacking the comments, see Class Comments for a discussion of what comments are needed) is:

class MyClass : public OtherClass {
 public:      // Note the 1 space indent!
  MyClass();  // Regular 2 space indent.
  explicit MyClass(int var);
  ~MyClass() {}

  void SomeFunction();
  void SomeFunctionThatDoesNothing() {
  }

  void set_some_var(int var) { some_var_ = var; }
  int some_var() const { return some_var_; }

 private:
  bool SomeInternalFunction();

  int some_var_;
  int some_other_var_;
  DISALLOW_COPY_AND_ASSIGN(MyClass);
};

Things to note:

  • Any base class name should be on the same line as the subclass name, subject to the 80-column limit.
  • The public:, protected:, and private: keywords should be indented one space.
  • Except for the first instance, these keywords should be preceded by a blank line. This rule is optional in small classes.
  • Do not leave a blank line after these keywords.
  • The public section should be first, followed by the protected and finally the private section.
  • See Declaration Order for rules on ordering declarations within each of these sections.

Constructor Initializer Lists

构造函数初始化列表放在同一行或按四格缩进并排几行.

There are two acceptable formats for initializer lists:

// When it all fits on one line:
MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {}

or

// When it requires multiple lines, indent 4 spaces, putting the colon on
// the first initializer line:
MyClass::MyClass(int var)
    : some_var_(var),             // 4 space indent
      some_other_var_(var + 1) {  // lined up
  ...
  DoSomething();
  ...
}

Namespace Formatting

名字空间内容不缩进.

Namespaces do not add an extra level of indentation. For example, use:

namespace {

void foo() {  // Correct.  No extra indentation within namespace.
  ...
}

}  // namespace

Do not indent within a namespace:

namespace {

  // Wrong.  Indented when it should not be.
  void foo() {
    ...
  }

}  // namespace

When declaring nested namespaces, put each namespace on its own line.

namespace foo {
namespace bar {

Horizontal Whitespace

水平留白的使用因地制宜. 永远不要在行尾添加没意义的留白

  • General
    void f(bool b) {  // Open braces should always have a space before them.
      ...
    int i = 0;  // Semicolons usually have no space before them.
    int x[] = { 0 };  // Spaces inside braces for braced-init-list are
    int x[] = {0};    // optional.  If you use them, put them on both sides!
    // Spaces around the colon in inheritance and initializer lists.
    class Foo : public Bar {
     public:
      // For inline function implementations, put spaces between the braces
      // and the implementation itself.
      Foo(int b) : Bar(), baz_(b) {}  // No spaces inside empty braces.
      void Reset() { baz_ = 0; }  // Spaces separating braces from implementation.
      ...
    

    Adding trailing whitespace can cause extra work for others editing the same file, when they merge, as can removing existing trailing whitespace. So: Don't introduce trailing whitespace. Remove it if you're already changing that line, or do it in a separate clean-up operation (preferably when no-one else is working on the file).

  • Loops and Conditionals
    if (b) {          // Space after the keyword in conditions and loops.
    } else {          // Spaces around else.
    }
    while (test) {}   // There is usually no space inside parentheses.
    switch (i) {
    for (int i = 0; i < 5; ++i) {
    switch ( i ) {    // Loops and conditions may have spaces inside
    if ( test ) {     // parentheses, but this is rare.  Be consistent.
    for ( int i = 0; i < 5; ++i ) {
    for ( ; i < 5 ; ++i) {  // For loops always have a space after the
      ...                   // semicolon, and may have a space before the
                            // semicolon.
    for (auto x : counts) {  // Range-based for loops always have a
      ...                    // space before and after the colon.
    }
    switch (i) {
      case 1:         // No space before colon in a switch case.
        ...
      case 2: break;  // Use a space after a colon if there's code after it.
    
  • Operators
    x = 0;              // Assignment operators always have spaces around
                        // them.
    x = -5;             // No spaces separating unary operators and their
    ++x;                // arguments.
    if (x && !y)
      ...
    v = w * x + y / z;  // Binary operators usually have spaces around them,
    v = w*x + y/z;      // but it's okay to remove spaces around factors.
    v = w * (x + z);    // Parentheses should have no spaces inside them.
    
  • Templates and Casts
    vector<string> x;           // No spaces inside the angle
    y = static_cast<char*>(x);  // brackets (< and >), before
                                // <, or between >( in a cast.
    vector<char *> x;           // Spaces between type and pointer are
                                // okay, but be consistent.
    set<list<string>> x;        // Permitted in C++11 code.
    set<list<string> > x;       // C++03 required a space in > >.
    set< list<string> > x;      // You may optionally use
                                // symmetric spacing in < <.
    

Vertical Whitespace

垂直留白越少越好.

This is more a principle than a rule: don't use blank lines when you don't have to. In particular, don't put more than one or two blank lines between functions, resist starting functions with a blank line, don't end functions with a blank line, and be discriminating with your use of blank lines inside functions.

The basic principle is: The more code that fits on one screen, the easier it is to follow and understand the control flow of the program. Of course, readability can suffer from code being too dense as well as too spread out, so use your judgement. But in general, minimize use of vertical whitespace.

Some rules of thumb to help when blank lines may be useful:

  • Blank lines at the beginning or end of a function very rarely help readability.
  • Blank lines inside a chain of if-else blocks may well help readability.

Exceptions to the Rules

Existing Non-conformant Code

#+beginhtml <p class="info"> 对于现有不符合既定编程风格的代码可以网开一面. </p> #+endhtml. 当你修改使用其他风格的代码时, 为了与代码原有风格保持一致可以不使用本指南约定. 如果不放心可以与代码原作者或现在的负责人员商讨, 记住, 一致性包括原有的一致性.

Windows Code

Windows 程序员有自己的编程习惯, 主要源于 Windows 头文件和其它 Microsoft 代码. 我们希望任何人都可以顺利读懂你的代码, 所以针对所有平台 的 C++ 编程只给出一个单独的指南.

如果你习惯使用 Windows 编码风格, 这儿有必要重申一下某些你可能会忘记的指南:

  • 不要使用匈牙利命名法 (比如把整型变量命名成 iNum). 使用 Google 命名约定, 包括对源文件使用 .cc 扩展名.
  • Windows 定义了很多原生类型的同义词 (YuleFox 注: 这一点, 我也很反感), 如 DWORD, HANDLE 等等. 在调用 Windows API 时这是完全可以接受甚至鼓励的. 但还是尽量使用原有的 C++ 类型, 例如, 使用 const TCHAR * 而不是 LPCTSTR.
  • 使用 Microsoft Visual C++ 进行编译时, 将警告级别设置为 3 或更高, 并将所有 warnings 当作 errors 处理.
  • 不要使用 #pragma once; 而应该使用 Google 的头文件保护规则. 头文件保护的路径应该相对于项目根目录 (yospaly 注: 如 #ifndef SRCDIRBARH_, 参考 #define 保护 一节).
  • 除非万不得已, 不要使用任何非标准的扩展, 如 #pragma 和 _declspec. 允许使用 _declspec(dllimport) 和 _declspec(dllexport); 但你必须通过宏来使用, 比如 DLLIMPORT 和 DLLEXPORT, 这样其他人在分享使用这些代码时很容易就去掉这些扩展.

在 Windows 上, 只有很少的一些情况下, 我们可以偶尔违反规则:

  • 通常我们 禁止使用多重继承, 但在使用 COM 和 ATL/WTL 类时可以使用多重继承. 为了实现 COM 或 ATL/WTL 类/接口, 你可能不得不使用多重实现继承.
  • 虽然代码中不应该使用异常, 但是在 ATL 和部分 STL(包括 Visual C++ 的 STL) 中异常被广泛使用. 使用 ATL 时, 应定义 _ATLNOEXCEPTIONS 以禁用异常. 你要研究一下是否能够禁用 STL 的异常, 如果无法禁用, 启用编译器异常也可以. (注意这只是为了编译 STL, 自己代码里仍然不要含异常处理.)
  • 通常为了利用头文件预编译, 每个每个源文件的开头都会包含一个名为 StdAfx.h 或 precompile.h 的文件. 为了使代码方便与其他项目共享, 避免显式包含此文件 (precompile.cc), 使用 /FI 编译器选项以自动包含.
  • 资源头文件通常命名为 resource.h, 且只包含宏的, 不需要遵守本风格指南.

Author: Shi Shougang

Created: 2015-03-05 Thu 23:21

Emacs 24.3.1 (Org mode 8.2.10)

Validate