@@ -181,7 +182,7 @@ pitfalls of using header files.
Header files should be self-contained (compile on their own) and
end in .h. Non-header files that are meant for inclusion
-should end in .inc.
+should end in .inc and be used sparingly.
@@ -191,25 +192,27 @@ header. Specifically, a header should
have header guards and include all
other headers it needs.
-
If a template or inline function is declared in a .h
-file, that same header should provide its definition. The definitions
-of these constructs must be included into every .cc file
-that uses them, or the program may fail to link in some build
-configurations. Do not move these definitions to separately included
-header files (-inl.h); this practice was common in the
-past, but is no longer allowed.
+
Prefer placing the definitions for template and inline functions in
+the same file as their declarations. The definitions of these
+constructs must be included into every .cc file that uses
+them, or the program may fail to link in some build configurations. If
+declarations and definitions are in different files, including the
+former should transitively include the latter. Do not move these
+definitions to separately included header files (-inl.h);
+this practice was common in the past, but is no longer allowed.
As an exception, a template that is explicitly instantiated for
all relevant sets of template arguments, or that is a private
implementation detail of a class, is allowed to be defined in the one
and only .cc file that instantiates the template.
-
There are rare cases where a file is not meant to be
-self-contained, but it is meant to be included at a specific point in
-the code. Examples are files that need to be included multiple times
-or platform-specific implementation details that are essentially part
-of other self-contained headers. Such files should use the file
-extension .inc.
+
There are rare cases where a file designed to be included is not
+self-contained. These are typically intended to be included at unusual
+locations, such as the middle of another file. They might not
+use header guards, and might not include
+their prerequisites. Name such files with the .inc
+extension. Use sparingly, and prefer self-contained headers when
+possible.
@@ -509,11 +512,12 @@ system-specific code small and localized. Example:
With few exceptions, place code in a namespace. Namespaces
should have unique names based on the project name, and possibly
-its path. Unnamed namespaces in .cc files are
-encouraged. Do not use using-directives (e.g.
+its path. Do not use using-directives (e.g.
using namespace foo). Do not use
-inline namespaces.
namespace X {
inline namespace Y {
void foo();
-}
-}
+} // namespace Y
+} // namespace X
The expressions X::Y::foo() and
@@ -565,10 +569,6 @@ because names aren't actually restricted to the namespace
where they are declared. They are only useful as part of
some larger versioning policy.
-
Use of unnamed namespaces in header files can easily
-cause violations of the C++ One Definition Rule
-(ODR).
-
In some contexts, it's necessary to repeatedly refer to
symbols by their fully-qualified names. For deeply-nested
namespaces, this can add a lot of clutter.
@@ -576,46 +576,12 @@ namespaces, this can add a lot of clutter.
-
Use namespaces according to the policy described
-below. Terminate namespaces with comments as shown in the
-given examples. See also the rules on
-Namespace Names.
-
-
-
-
Unnamed Namespaces
+
Namespaces should be used as follows:
-
-
Unnamed namespaces are allowed and even encouraged
- in .cc files, to avoid link time naming
- conflicts:
-
-
namespace { // This is in a .cc file.
-
-// The content of a namespace is not indented.
-//
-// This function is guaranteed not to generate a colliding symbol
-// with other symbols at link time, and is only visible to
-// callers in this .cc file.
-bool UpdateInternals(Frobber* f, int newval) {
- ...
-}
-
-} // namespace
-
Terminate namespaces with comments as shown in the given examples.
+
Namespaces wrap the entire source file after
includes,
@@ -653,12 +619,12 @@ void MyClass::Foo() {
#include "a.h"
-DEFINE_bool(someflag, false, "dummy flag");
-
-using ::foo::bar;
+DEFINE_FLAG(bool, someflag, false, "dummy flag");
namespace a {
+using ::foo::bar;
+
...code for a... // Code goes against the left margin.
} // namespace a
@@ -708,6 +674,44 @@ inline void my_inline_function() {
Do not use inline namespaces.
+
+
+
+
Unnamed Namespaces and Static
+Variables
+
+
+
When definitions in a .cc file do not need to be
+referenced outside that file, place them in an unnamed
+namespace or declare them static. Do not use either
+of these constructs in .h files.
+
+
+
+
+
+
All declarations can be given internal linkage by placing them in
+unnamed namespaces, and functions and variables can be given internal linkage by
+declaring them static. This means that anything you're declaring
+can't be accessed from another file. If a different file declares something
+with the same name, then the two entities are completely independent.
+
+
+
+
+
Use of internal linkage in .cc files is encouraged
+for all code that does not need to be referenced elsewhere.
+Do not use internal linkage in .h files.
+
+
Format unnamed namespaces like named namespaces. In the
+ terminating comment, leave the namespace name empty:
+
+
namespace {
+...
+} // namespace
+
+
+
Nonmember, Static Member, and Global Functions
@@ -747,8 +751,8 @@ functions which do not share static data, use
namespace foo_bar {
void Function1();
void Function2();
-}
-}
+} // namespace foo_bar
+} // namespace myproject
If you 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.
+needed in its .cc file, use
+internal linkage to limit
+its scope.
@@ -793,12 +796,12 @@ i = f(); // Bad -- initialization separate from declaration.
int j = g(); // Good -- declaration has initialization.
-
vector<int> v;
+
std::vector<int> v;
v.push_back(1); // Prefer initializing using brace initialization.
v.push_back(2);
-
vector<int> v = {1, 2}; // Good -- v starts initialized.
+
std::vector<int> v = {1, 2}; // Good -- v starts initialized.
Variables needed for if, while
@@ -855,7 +858,7 @@ 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 namespace-scope static variables to be initialized
+we do not allow non-local static 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. However, a static POD variable within
@@ -895,7 +898,7 @@ both places.)
As a result we only allow static variables to contain
POD data. This rule completely disallows
-vector (use C arrays instead), or
+std::vector (use C arrays instead), or
string (use const char []).
@@ -947,8 +950,6 @@ of the constructor.
-
The problems with doing work in constructors are:
-
If the work calls virtual functions, these calls
will not get dispatched to the subclass
@@ -1011,11 +1012,8 @@ class definition of the source or destination type. An implicit
conversion in the source type is defined by a type conversion operator
named after the destination type (e.g. operator
bool()). An implicit conversion in the destination
-type is defined by a converting constructor, which
-is a constructor that can take the source type as its only
-argument. Note that a multi-parameter constructor can still
-be a converting constructor, if all but the first parameter
-have default values.
+type is defined by a constructor that can take the source type as
+its only argument (or only argument with no default value).
The explicit keyword can be applied to a constructor
or (since C++11) a conversion operator, to ensure that it can only be
@@ -1160,7 +1158,7 @@ objects tied to a specific scope (Cleanup), or closely coupled to
object identity (Mutex) cannot be copied meaningfully.
Copy operations for base class types that are to be used
polymorphically are hazardous, because use of them can lead to
-object slicing.
+object slicing.
Defaulted or carelessly-implemented copy operations can be incorrect, and the
resulting bugs can be confusing and difficult to diagnose.
@@ -1207,7 +1205,14 @@ can use to implement it.
If you do not want to support copy/move operations on your type,
explicitly disable them using = delete in
-the public: section.
+the public: section:
+
+
// MyClass is neither copyable nor movable.
+MyClass(const MyClass&) = delete;
+MyClass& operator=(const MyClass&) = delete;
+
+
+
@@ -1594,50 +1599,30 @@ reasons, we allow data members of a test fixture class to
be protected when using
-Google
+Google
Test).
Declaration Order
-
Use the specified order of declarations within a class:
-public: before private:, methods
-before data members (variables), etc.
+
Group similar declarations together, placing public parts
+earlier.
-
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.
+
A class definition should usually start with a
+public: section, followed by
+protected:, then private:. Omit
+sections that would be empty.
-
Within each section, the declarations generally should
-be in the following order:
-
-
-
Using-declarations, Typedefs and Enums
-
-
Constants (static const data
- members)
-
-
Constructors and assignment operators
-
-
Destructor
-
-
Methods, including static methods
-
-
Data Members (except static const data
- members)
-
-
-
If copying and assignment are disabled with a macro such as
-DISALLOW_COPY_AND_ASSIGN, it should be
-at the end of the private: section, and should be
-the last thing in the class. See
-Copyable and Movable Types.
+
Within each section, generally prefer grouping similar
+kinds of declarations together, and generally prefer the
+following order: types (including typedef,
+using, and nested structs and classes),
+constants, factory functions, constructors, assignment
+operators, destructor, all other methods, data members.
Do not put large method definitions inline in the
class definition. Usually, only trivial or
@@ -1661,7 +1646,7 @@ outputs.
function, output from the function, or both. Input
parameters are usually values or const
references, while output and input/output parameters will
-be non-const pointers. When ordering
+be pointers to non-const. When ordering
function parameters, put all input-only parameters before
any output parameters. In particular, do not add new
parameters to the end of the function just because they
@@ -1821,7 +1806,7 @@ the name with some information about the arguments, e.g.,
rather than just Append(). If you are
overloading a function to support variable number of
arguments of the same type, consider making it take a
-vector so that the user can use an
+std::vector so that the user can use an
initializer list
to specify the arguments.
@@ -2091,9 +2076,7 @@ underlying object is immutable (i.e.
do use shared ownership, prefer to use
std::shared_ptr.
-
Do not use scoped_ptr in new code unless
-you need to be compatible with older versions of C++.
-Never use std::auto_ptr. Instead, use
+
Never use std::auto_ptr. Instead, use
std::unique_ptr.
@@ -2155,7 +2138,7 @@ rvalue reference to a string.
Defining a move constructor (a constructor taking
an rvalue reference to the class type) makes it
possible to move a value instead of copying it. If
- v1 is a vector<string>,
+ v1 is a std::vector<string>,
for example, then auto v2(std::move(v1))
will probably just result in some simple pointer
manipulation instead of copying a large amount of data.
@@ -2200,40 +2183,6 @@ moving a value from one object to another rather than copying it.
-
- Variable-Length Arrays and alloca()
-
-
-
We do not allow variable-length arrays or
-alloca().
-
-
-
-
-
-
Variable-length arrays have natural-looking syntax. Both
-variable-length arrays and alloca() are very
-efficient.
-
-
-
-
Variable-length arrays and alloca are not part of
-Standard C++. More importantly, they allocate a
-data-dependent amount of stack space that can trigger
-difficult-to-find memory overwriting bugs: "It ran fine
-on my machine, but dies mysteriously in production".
-
-
-
-
-
-
Use a safe allocator instead, such as
-vector or
-std::unique_ptr<T[]>.
Be very cautious with macros. Prefer inline functions,
-enums, and const variables to macros. Don't
-use macros to define pieces of a C++ API.
+
Avoid defining macros, especially in headers; prefer
+inline functions, enums, and const variables.
+Name macros with a project-specific prefix. Do not use
+macros to define pieces of a C++ API.
Exporting macros from headers (i.e. defining them in a header
+without #undefing them before the end of the header)
+is extremely strongly discouraged. If you do export a macro from a
+header, it must have a globally unique name. To achieve this, it
+must be named with a prefix consisting of your project's namespace
+name (but upper case).
Use auto to avoid type names that are noisy, obvious,
or unimportant - cases where the type doesn't aid in clarity for the
reader. Continue to use manifest type declarations when it helps
-readability, and never use auto for anything but local
-variables.
+readability.
@@ -3295,7 +3251,6 @@ small code region, the repetition may not be aiding readability.
the initialization expression, since that avoids the possibility of
unintended copies or type conversions.
-
@@ -3308,7 +3263,7 @@ like:
auto i = y.Find(key);
-
It may not be obvious what the resulting types are if the type
+
it may not be obvious what the resulting types are if the type
of y isn't very well known, or if y was
declared many lines earlier.
@@ -3325,10 +3280,8 @@ than intended.
-
auto is permitted, for local variables only, when it
-increases readability, particularly as described below. Do not
-use auto for file-scope or namespace-scope variables, or
-for class members. Never initialize an auto-typed
+
auto is permitted when it increases readability,
+particularly as described below. Never initialize an auto-typed
variable with a braced initializer list.
Specific cases where auto is allowed or encouraged:
@@ -3348,8 +3301,8 @@ nearby.
anything other than equality comparison.
(Encouraged) When iterating over a map with a range-based loop
(because it is often assumed that the correct type
-is pair<KeyType,ValueType> whereas it is actually
-pair<const KeyType,ValueType>). This is
+is std::pair<KeyType, ValueType> whereas it is actually
+std::pair<const KeyType, ValueType>). This is
particularly well paired with local key
and value aliases for .first
and .second (often const-ref).
@@ -3364,7 +3317,6 @@ and .second (often const-ref).
-
@@ -3378,8 +3330,7 @@ and .second (often const-ref).
In C++03, aggregate types (arrays and structs with no
-constructor) could be initialized with braced initializer lists.
-
+constructor) could be initialized with braced initializer lists.
struct Point { int x; int y; };
Point p = {1, 2};
@@ -3391,26 +3342,26 @@ be created with a braced initializer list, known as a
of its use.
// Vector takes a braced-init-list of elements.
-vector<string> v{"foo", "bar"};
+std::vector<string> v{"foo", "bar"};
// Basically the same, ignoring some small technicalities.
// You may choose to use either form.
-vector<string> v = {"foo", "bar"};
+std::vector<string> v = {"foo", "bar"};
// Usable with 'new' expressions.
auto p = new vector<string>{"foo", "bar"};
// A map can take a list of pairs. Nested braced-init-lists work.
-map<int, string> m = {{1, "one"}, {2, "2"}};
+std::map<int, string> m = {{1, "one"}, {2, "2"}};
// A braced-init-list can be implicitly converted to a return type.
-vector<int> test_function() { return {1, 2, 3}; }
+std::vector<int> test_function() { return {1, 2, 3}; }
// Iterate over a braced-init-list.
for (int i : {-1, -2, -3}) {}
// Call a function using a braced-init-list.
-void TestFunction2(vector<int> v) {}
+void TestFunction2(std::vector<int> v) {}
TestFunction2({1, 2, 3});
@@ -3550,7 +3501,6 @@ wrapper std::function.
hand; very long nested anonymous functions can make
code harder to understand.
-
@@ -3599,6 +3549,7 @@ use a named function instead of a lambda.
Specify the return type of the lambda explicitly if that will
make it more obvious to readers, as with
auto.
+
@@ -3759,19 +3710,28 @@ Currently, the following libraries are permitted:
Statistical Distributions and Functions from
boost/math/distributions
+
We are actively considering adding other Boost
@@ -3977,8 +3937,8 @@ guide, the following C++11 features may not be used:
as __builtin_prefetch, designated initializers (e.g.
Foo f = {.field = 3}), inline assembly, __COUNTER__,
__PRETTY_FUNCTION__, compound statement expressions (e.g.
- foo = ({ int x; Bar(&x); x }), and the a?:b
- syntax.
+ foo = ({ int x; Bar(&x); x }), variable-length arrays and
+ alloca(), and the a?:b syntax.
@@ -4146,7 +4106,17 @@ int pc_reader; // Lots of things can be abbreviated "pc".
int cstmr_id; // Deletes internal letters.
-
+
Note that certain universally-known abbreviations are OK, such as
+i for an iteration variable and T for a
+template parameter.
+
+
Template parameters should follow the naming style for their
+category: type template parameters should follow the rules for
+type names, and non-type template
+parameters should follow the rules for
+variable names.
+
+
File Names
@@ -4226,9 +4196,9 @@ enum UrlTableErrors { ...
Variable Names
-
The names of variables and data members are all lowercase, with
-underscores between words. Data members of classes (but not structs)
-additionally have trailing underscores. For instance:
+
The names of variables (including function parameters) and data members are
+all lowercase, with underscores between words. Data members of classes (but not
+structs) additionally have trailing underscores. For instance:
a_local_variable, a_struct_data_member,
a_class_data_member_.
@@ -4305,16 +4275,18 @@ versus a class.
Function Names
-
Regular functions have mixed case; "cheap" functions may
-use lower case with underscores.
+
Regular functions have mixed case; accessors and mutators may be named
+like variables.
-
Ordinarily, functions should start with a capital letter and have
-a capital letter for each new word (a.k.a. "upper camel case" or "Pascal case").
-Such names should not have underscores. Prefer to capitalize acronyms as
-single words (i.e. StartRpc(), not StartRPC()).
+
Ordinarily, functions should start with a capital letter and have a
+capital letter for each new word
+(a.k.a. "Camel
+Case" or "Pascal case"). Such names should not have
+underscores. Prefer to capitalize acronyms as single words
+(i.e. StartRpc(), not StartRPC()).
AddTableEntry()
DeleteUrl()
@@ -4326,22 +4298,11 @@ constants that are exposed as part of an API and that are intended to look
like functions, because the fact that they're
objects rather than functions is an unimportant implementation detail.)
-
Functions that are very cheap to call may instead follow the style
-for variable names (all lower-case, with underscores between words).
-The rule of thumb is that such a function should be so cheap that you
-normally wouldn't bother caching its return value when calling it in
-a loop. A canonical example is an inline method that just returns one
-of the class's member variables.
+
Accessors and mutators (get and set functions) may be named like
+variables. These often correspond to actual member variables, but this is
+not required. For example, int count() and void
+set_count(int count).
When documenting function overrides, focus on the
specifics of the override itself, rather than repeating
-the comment from the overriden function. In many of these
+the comment from the overridden function. In many of these
cases, the override needs no additional documentation and
thus no comment is required.
@@ -4793,7 +4754,8 @@ DoSomethingElseThatIsLonger(); // Two spaces between the code and the comment.
// thus the comment lines up with the following comments and code.
DoSomethingElse(); // Two spaces before line comments normally.
}
-vector<string> list{// Comments in braced lists describe the next element ..
+std::vector<string> list{
+ // Comments in braced lists describe the next element...
"First item",
// .. and should be aligned appropriately.
"Second item"};
@@ -5134,7 +5096,7 @@ hit the tab key.
Return type on the same line as function name, parameters
on the same line if they fit. Wrap parameter lists which do
not fit on a single line as you would wrap arguments in a
-function call.
// Examples of braced init list on a single line.
return {foo, bar};
functioncall({foo, bar});
-pair<int, int> p{foo, bar};
+std::pair<int, int> p{foo, bar};
// When you have to wrap.
SomeFunction(
@@ -5513,7 +5475,7 @@ if (condition) {
Switch statements may use braces for blocks. Annotate
non-trivial fall-through between cases.
Braces are optional for single-statement loops.
-Empty loop bodies should use {} or continue.
+Empty loop bodies should use empty braces or continue.
@@ -5564,13 +5526,13 @@ for (int i = 0; i < kSomeNumber; ++i) {
-
Empty loop bodies should use {} or
-continue, but not a single semicolon.
+
Empty loop bodies should use an empty pair of braces 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.
+for (int i = 0; i < kSomeNumber; ++i) {} // Good - one newline is also OK.
while (condition) continue; // Good - continue indicates no logic.
@@ -5616,11 +5578,18 @@ char *c;
const string &str;
// These are fine, space following.
-char* c; // but remember to do "char* c, *d, *e, ...;"!
+char* c;
const string& str;
-
char * c; // Bad - spaces on both sides of *
+It is allowed (if unusual) to declare multiple variables in the same
+declaration, but it is disallowed if any of those have pointer or
+reference decorations. Such declarations are easily misread.
+
// Fine if helpful for readability.
+int x, y;
+
+
int x, *y; // Disallowed - no & or * in multiple declaration
+char * c; // Bad - spaces on both sides of *
const string & str; // Bad - spaces on both sides of &
@@ -5722,8 +5691,8 @@ will call a default constructor if available. To force the
non-std::initializer_list constructor, use parentheses
instead of braces.
-
vector<int> v(100, 1); // A vector of 100 1s.
-vector<int> v{100, 1}; // A vector of 100, 1.
+
std::vector<int> v(100, 1); // A vector of 100 1s.
+std::vector<int> v{100, 1}; // A vector of 100, 1.
Also, the brace form prevents narrowing of integral
@@ -6004,16 +5973,11 @@ if (x && !y)
// No spaces inside the angle brackets (< and >), before
// <, or between >( in a cast
-vector<string> x;
+std::vector<string> x;
y = static_cast<char*>(x);
// Spaces between type and pointer are OK, but be consistent.
-vector<char *> x;
-set<list<string>> x; // Permitted in C++11 code.
-set<list<string> > x; // C++03 required a space in > >.
-
-// You may optionally use symmetric spacing in < <.
-set< list<string> > x;
+std::vector<char *> x;
@@ -6201,6 +6165,6 @@ more interesting. Have fun!
-