mirror of
https://github.com/google/styleguide.git
synced 2024-03-22 13:11:43 +08:00
Update Java and C++ style guides with various changes since the last update.
This commit is contained in:
parent
8f254427d9
commit
db0a26320f
432
cppguide.html
432
cppguide.html
|
@ -5,6 +5,7 @@
|
||||||
<title>Google C++ Style Guide</title>
|
<title>Google C++ Style Guide</title>
|
||||||
<link rel="stylesheet" type="text/css" href="include/styleguide.css">
|
<link rel="stylesheet" type="text/css" href="include/styleguide.css">
|
||||||
<script language="javascript" src="include/styleguide.js"></script>
|
<script language="javascript" src="include/styleguide.js"></script>
|
||||||
|
<link rel="shortcut icon" type="image/x-icon" href="https://www.google.com/favicon.ico" />
|
||||||
</head>
|
</head>
|
||||||
<body onload="initStyleGuide();">
|
<body onload="initStyleGuide();">
|
||||||
<div id="content">
|
<div id="content">
|
||||||
|
@ -181,7 +182,7 @@ pitfalls of using header files.</p>
|
||||||
<div class="summary">
|
<div class="summary">
|
||||||
<p>Header files should be self-contained (compile on their own) and
|
<p>Header files should be self-contained (compile on their own) and
|
||||||
end in <code>.h</code>. Non-header files that are meant for inclusion
|
end in <code>.h</code>. Non-header files that are meant for inclusion
|
||||||
should end in <code>.inc</code>. </p>
|
should end in <code>.inc</code> and be used sparingly.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
@ -191,25 +192,27 @@ header. Specifically, a header should
|
||||||
have <a href="#The__define_Guard">header guards</a> and include all
|
have <a href="#The__define_Guard">header guards</a> and include all
|
||||||
other headers it needs.</p>
|
other headers it needs.</p>
|
||||||
|
|
||||||
<p>If a template or inline function is declared in a <code>.h</code>
|
<p>Prefer placing the definitions for template and inline functions in
|
||||||
file, that same header should provide its definition. The definitions
|
the same file as their declarations. The definitions of these
|
||||||
of these constructs must be included into every <code>.cc</code> file
|
constructs must be included into every <code>.cc</code> file that uses
|
||||||
that uses them, or the program may fail to link in some build
|
them, or the program may fail to link in some build configurations. If
|
||||||
configurations. Do not move these definitions to separately included
|
declarations and definitions are in different files, including the
|
||||||
header files (<code>-inl.h</code>); this practice was common in the
|
former should transitively include the latter. Do not move these
|
||||||
past, but is no longer allowed.</p>
|
definitions to separately included header files (<code>-inl.h</code>);
|
||||||
|
this practice was common in the past, but is no longer allowed.</p>
|
||||||
|
|
||||||
<p>As an exception, a template that is explicitly instantiated for
|
<p>As an exception, a template that is explicitly instantiated for
|
||||||
all relevant sets of template arguments, or that is a private
|
all relevant sets of template arguments, or that is a private
|
||||||
implementation detail of a class, is allowed to be defined in the one
|
implementation detail of a class, is allowed to be defined in the one
|
||||||
and only <code>.cc</code> file that instantiates the template.</p>
|
and only <code>.cc</code> file that instantiates the template.</p>
|
||||||
|
|
||||||
<p>There are rare cases where a file is not meant to be
|
<p>There are rare cases where a file designed to be included is not
|
||||||
self-contained, but it is meant to be included at a specific point in
|
self-contained. These are typically intended to be included at unusual
|
||||||
the code. Examples are files that need to be included multiple times
|
locations, such as the middle of another file. They might not
|
||||||
or platform-specific implementation details that are essentially part
|
use <a href="#The__define_Guard">header guards</a>, and might not include
|
||||||
of other self-contained headers. Such files should use the file
|
their prerequisites. Name such files with the <code>.inc</code>
|
||||||
extension <code>.inc</code>.</p>
|
extension. Use sparingly, and prefer self-contained headers when
|
||||||
|
possible.</p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -509,11 +512,12 @@ system-specific code small and localized. Example:</p>
|
||||||
<div class="summary">
|
<div class="summary">
|
||||||
<p>With few exceptions, place code in a namespace. Namespaces
|
<p>With few exceptions, place code in a namespace. Namespaces
|
||||||
should have unique names based on the project name, and possibly
|
should have unique names based on the project name, and possibly
|
||||||
its path. Unnamed namespaces in <code>.cc</code> files are
|
its path. Do not use <i>using-directives</i> (e.g.
|
||||||
encouraged. Do not use <i>using-directives</i> (e.g.
|
|
||||||
<code>using namespace foo</code>). Do not use
|
<code>using namespace foo</code>). Do not use
|
||||||
inline namespaces.</p>
|
inline namespaces. For unnamed namespaces, see
|
||||||
</div>
|
<a href="#Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and
|
||||||
|
Static Variables</a>.
|
||||||
|
</p></div>
|
||||||
|
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
|
||||||
|
@ -544,8 +548,8 @@ example:</p>
|
||||||
<pre>namespace X {
|
<pre>namespace X {
|
||||||
inline namespace Y {
|
inline namespace Y {
|
||||||
void foo();
|
void foo();
|
||||||
}
|
} // namespace Y
|
||||||
}
|
} // namespace X
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<p>The expressions <code>X::Y::foo()</code> and
|
<p>The expressions <code>X::Y::foo()</code> 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
|
where they are declared. They are only useful as part of
|
||||||
some larger versioning policy.</p>
|
some larger versioning policy.</p>
|
||||||
|
|
||||||
<p>Use of unnamed namespaces in header files can easily
|
|
||||||
cause violations of the C++ One Definition Rule
|
|
||||||
(ODR).</p>
|
|
||||||
|
|
||||||
<p>In some contexts, it's necessary to repeatedly refer to
|
<p>In some contexts, it's necessary to repeatedly refer to
|
||||||
symbols by their fully-qualified names. For deeply-nested
|
symbols by their fully-qualified names. For deeply-nested
|
||||||
namespaces, this can add a lot of clutter.</p>
|
namespaces, this can add a lot of clutter.</p>
|
||||||
|
@ -576,46 +576,12 @@ namespaces, this can add a lot of clutter.</p>
|
||||||
|
|
||||||
<div class="decision">
|
<div class="decision">
|
||||||
|
|
||||||
<p>Use namespaces according to the policy described
|
<p>Namespaces should be used as follows:</p>
|
||||||
below. Terminate namespaces with comments as shown in the
|
|
||||||
given examples. See also the rules on
|
|
||||||
<a href="#Namespace_Names">Namespace Names</a>.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h4 class="stylepoint_subsection">Unnamed Namespaces</h4>
|
|
||||||
|
|
||||||
<ul>
|
<ul>
|
||||||
<li>
|
<li>Follow the rules on <a href="#Namespace_Names">Namespace Names</a>.
|
||||||
<p>Unnamed namespaces are allowed and even encouraged
|
</li><li>Terminate namespaces with comments as shown in the given examples.
|
||||||
in <code>.cc</code> files, to avoid link time naming
|
</li><li>
|
||||||
conflicts:</p>
|
|
||||||
|
|
||||||
<pre>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
|
|
||||||
</pre>
|
|
||||||
</li>
|
|
||||||
|
|
||||||
<li>Do not use unnamed namespaces in <code>.h</code>
|
|
||||||
files.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<h4 class="stylepoint_subsection">Named Namespaces</h4>
|
|
||||||
|
|
||||||
<p>Named namespaces should be used as follows:</p>
|
|
||||||
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
|
|
||||||
<p>Namespaces wrap the entire source file after
|
<p>Namespaces wrap the entire source file after
|
||||||
includes,
|
includes,
|
||||||
|
@ -653,12 +619,12 @@ void MyClass::Foo() {
|
||||||
|
|
||||||
<pre>#include "a.h"
|
<pre>#include "a.h"
|
||||||
|
|
||||||
DEFINE_bool(someflag, false, "dummy flag");
|
DEFINE_FLAG(bool, someflag, false, "dummy flag");
|
||||||
|
|
||||||
using ::foo::bar;
|
|
||||||
|
|
||||||
namespace a {
|
namespace a {
|
||||||
|
|
||||||
|
using ::foo::bar;
|
||||||
|
|
||||||
...code for a... // Code goes against the left margin.
|
...code for a... // Code goes against the left margin.
|
||||||
|
|
||||||
} // namespace a
|
} // namespace a
|
||||||
|
@ -708,6 +674,44 @@ inline void my_inline_function() {
|
||||||
|
|
||||||
</li><li>Do not use inline namespaces.</li>
|
</li><li>Do not use inline namespaces.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3 id="Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and Static
|
||||||
|
Variables</h3>
|
||||||
|
|
||||||
|
<div class="summary">
|
||||||
|
<p>When definitions in a <code>.cc</code> file do not need to be
|
||||||
|
referenced outside that file, place them in an unnamed
|
||||||
|
namespace or declare them <code>static</code>. Do not use either
|
||||||
|
of these constructs in <code>.h</code> files.
|
||||||
|
</p></div>
|
||||||
|
|
||||||
|
<div class="stylebody">
|
||||||
|
|
||||||
|
<div class="definition">
|
||||||
|
<p>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 <code>static</code>. 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.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="decision">
|
||||||
|
|
||||||
|
<p>Use of internal linkage in <code>.cc</code> files is encouraged
|
||||||
|
for all code that does not need to be referenced elsewhere.
|
||||||
|
Do not use internal linkage in <code>.h</code> files.</p>
|
||||||
|
|
||||||
|
<p>Format unnamed namespaces like named namespaces. In the
|
||||||
|
terminating comment, leave the namespace name empty:</p>
|
||||||
|
|
||||||
|
<pre>namespace {
|
||||||
|
...
|
||||||
|
} // namespace
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3>
|
<h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3>
|
||||||
|
|
||||||
|
@ -747,8 +751,8 @@ functions which do not share static data, use
|
||||||
namespace foo_bar {
|
namespace foo_bar {
|
||||||
void Function1();
|
void Function1();
|
||||||
void Function2();
|
void Function2();
|
||||||
}
|
} // namespace foo_bar
|
||||||
}
|
} // namespace myproject
|
||||||
</pre>
|
</pre>
|
||||||
<p>instead of</p>
|
<p>instead of</p>
|
||||||
<pre class="badcode">namespace myproject {
|
<pre class="badcode">namespace myproject {
|
||||||
|
@ -757,14 +761,13 @@ class FooBar {
|
||||||
static void Function1();
|
static void Function1();
|
||||||
static void Function2();
|
static void Function2();
|
||||||
};
|
};
|
||||||
}
|
} // namespace myproject
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<p>If you define a nonmember function and it is only
|
<p>If you define a nonmember function and it is only
|
||||||
needed in its <code>.cc</code> file, use an unnamed
|
needed in its <code>.cc</code> file, use
|
||||||
<a href="#Namespaces">namespace</a> or
|
<a href="#Unnamed_Namespaces_and_Static_Variables">internal linkage</a> to limit
|
||||||
<code>static</code> linkage (eg <code>static int Foo()
|
its scope.</p>
|
||||||
{...}</code>) to limit its scope.</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
@ -793,12 +796,12 @@ i = f(); // Bad -- initialization separate from declaration.
|
||||||
<pre>int j = g(); // Good -- declaration has initialization.
|
<pre>int j = g(); // Good -- declaration has initialization.
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<pre class="badcode">vector<int> v;
|
<pre class="badcode">std::vector<int> v;
|
||||||
v.push_back(1); // Prefer initializing using brace initialization.
|
v.push_back(1); // Prefer initializing using brace initialization.
|
||||||
v.push_back(2);
|
v.push_back(2);
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<pre>vector<int> v = {1, 2}; // Good -- v starts initialized.
|
<pre>std::vector<int> v = {1, 2}; // Good -- v starts initialized.
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<p>Variables needed for <code>if</code>, <code>while</code>
|
<p>Variables needed for <code>if</code>, <code>while</code>
|
||||||
|
@ -855,7 +858,7 @@ for static variables are called is only partially
|
||||||
specified in C++ and can even change from build to build,
|
specified in C++ and can even change from build to build,
|
||||||
which can cause bugs that are difficult to find.
|
which can cause bugs that are difficult to find.
|
||||||
Therefore in addition to banning globals of class type,
|
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
|
with the result of a function, unless that function (such
|
||||||
as getenv(), or getpid()) does not itself depend on any
|
as getenv(), or getpid()) does not itself depend on any
|
||||||
other globals. However, a static POD variable within
|
other globals. However, a static POD variable within
|
||||||
|
@ -895,7 +898,7 @@ both places.)</p>
|
||||||
|
|
||||||
<p>As a result we only allow static variables to contain
|
<p>As a result we only allow static variables to contain
|
||||||
POD data. This rule completely disallows
|
POD data. This rule completely disallows
|
||||||
<code>vector</code> (use C arrays instead), or
|
<code>std::vector</code> (use C arrays instead), or
|
||||||
<code>string</code> (use <code>const char []</code>).</p>
|
<code>string</code> (use <code>const char []</code>).</p>
|
||||||
|
|
||||||
|
|
||||||
|
@ -947,8 +950,6 @@ of the constructor.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="cons">
|
<div class="cons">
|
||||||
<p>The problems with doing work in constructors are:</p>
|
|
||||||
|
|
||||||
<ul>
|
<ul>
|
||||||
<li>If the work calls virtual functions, these calls
|
<li>If the work calls virtual functions, these calls
|
||||||
will not get dispatched to the subclass
|
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
|
conversion in the source type is defined by a type conversion operator
|
||||||
named after the destination type (e.g. <code>operator
|
named after the destination type (e.g. <code>operator
|
||||||
bool()</code>). An implicit conversion in the destination
|
bool()</code>). An implicit conversion in the destination
|
||||||
type is defined by a <def>converting constructor</def>, which
|
type is defined by a constructor that can take the source type as
|
||||||
is a constructor that can take the source type as its only
|
its only argument (or only argument with no default value).</p>
|
||||||
argument. Note that a multi-parameter constructor can still
|
|
||||||
be a converting constructor, if all but the first parameter
|
|
||||||
have default values.</p>
|
|
||||||
|
|
||||||
<p>The <code>explicit</code> keyword can be applied to a constructor
|
<p>The <code>explicit</code> keyword can be applied to a constructor
|
||||||
or (since C++11) a conversion operator, to ensure that it can only be
|
or (since C++11) a conversion operator, to ensure that it can only be
|
||||||
|
@ -1160,7 +1158,7 @@ objects tied to a specific scope (<code>Cleanup</code>), or closely coupled to
|
||||||
object identity (<code>Mutex</code>) cannot be copied meaningfully.
|
object identity (<code>Mutex</code>) cannot be copied meaningfully.
|
||||||
Copy operations for base class types that are to be used
|
Copy operations for base class types that are to be used
|
||||||
polymorphically are hazardous, because use of them can lead to
|
polymorphically are hazardous, because use of them can lead to
|
||||||
<a href="http://en.wikipedia.org/wiki/Object_slicing">object slicing</a>.
|
<a href="https://en.wikipedia.org/wiki/Object_slicing">object slicing</a>.
|
||||||
Defaulted or carelessly-implemented copy operations can be incorrect, and the
|
Defaulted or carelessly-implemented copy operations can be incorrect, and the
|
||||||
resulting bugs can be confusing and difficult to diagnose.</p>
|
resulting bugs can be confusing and difficult to diagnose.</p>
|
||||||
|
|
||||||
|
@ -1207,7 +1205,14 @@ can use to implement it.</p>
|
||||||
|
|
||||||
<p>If you do not want to support copy/move operations on your type,
|
<p>If you do not want to support copy/move operations on your type,
|
||||||
explicitly disable them using <code>= delete</code> in
|
explicitly disable them using <code>= delete</code> in
|
||||||
the <code>public:</code> section. </p>
|
the <code>public:</code> section:</p>
|
||||||
|
|
||||||
|
<pre class="code">// MyClass is neither copyable nor movable.
|
||||||
|
MyClass(const MyClass&) = delete;
|
||||||
|
MyClass& operator=(const MyClass&) = delete;
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
<p></p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -1594,50 +1599,30 @@ reasons, we allow data members of a test fixture class to
|
||||||
be <code>protected</code> when using
|
be <code>protected</code> when using
|
||||||
|
|
||||||
|
|
||||||
<a href="https://code.google.com/p/googletest/">Google
|
<a href="https://github.com/google/googletest">Google
|
||||||
Test</a>).</p>
|
Test</a>).</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h3 id="Declaration_Order">Declaration Order</h3>
|
<h3 id="Declaration_Order">Declaration Order</h3>
|
||||||
|
|
||||||
<div class="summary">
|
<div class="summary">
|
||||||
<p> Use the specified order of declarations within a class:
|
<p>Group similar declarations together, placing public parts
|
||||||
<code>public:</code> before <code>private:</code>, methods
|
earlier.</p>
|
||||||
before data members (variables), etc.</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
|
||||||
<p>Your class definition should start with its
|
<p>A class definition should usually start with a
|
||||||
<code>public:</code> section, followed by its
|
<code>public:</code> section, followed by
|
||||||
<code>protected:</code> section and then its
|
<code>protected:</code>, then <code>private:</code>. Omit
|
||||||
<code>private:</code> section. If any of these sections
|
sections that would be empty.</p>
|
||||||
are empty, omit them.</p>
|
|
||||||
|
|
||||||
<p>Within each section, the declarations generally should
|
<p>Within each section, generally prefer grouping similar
|
||||||
be in the following order:</p>
|
kinds of declarations together, and generally prefer the
|
||||||
|
following order: types (including <code>typedef</code>,
|
||||||
<ul>
|
<code>using</code>, and nested structs and classes),
|
||||||
<li>Using-declarations, Typedefs and Enums</li>
|
constants, factory functions, constructors, assignment
|
||||||
|
operators, destructor, all other methods, data members.</p>
|
||||||
<li>Constants (<code>static const</code> data
|
|
||||||
members)</li>
|
|
||||||
|
|
||||||
<li>Constructors and assignment operators</li>
|
|
||||||
|
|
||||||
<li>Destructor</li>
|
|
||||||
|
|
||||||
<li>Methods, including static methods</li>
|
|
||||||
|
|
||||||
<li>Data Members (except <code>static const</code> data
|
|
||||||
members)</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p>If copying and assignment are disabled with a macro such as
|
|
||||||
<code>DISALLOW_COPY_AND_ASSIGN</code>, it should be
|
|
||||||
at the end of the <code>private:</code> section, and should be
|
|
||||||
the last thing in the class. See
|
|
||||||
<a href="#Copyable_Movable_Types">Copyable and Movable Types</a>.</p>
|
|
||||||
|
|
||||||
<p>Do not put large method definitions inline in the
|
<p>Do not put large method definitions inline in the
|
||||||
class definition. Usually, only trivial or
|
class definition. Usually, only trivial or
|
||||||
|
@ -1661,7 +1646,7 @@ outputs.</p>
|
||||||
function, output from the function, or both. Input
|
function, output from the function, or both. Input
|
||||||
parameters are usually values or <code>const</code>
|
parameters are usually values or <code>const</code>
|
||||||
references, while output and input/output parameters will
|
references, while output and input/output parameters will
|
||||||
be non-<code>const</code> pointers. When ordering
|
be pointers to non-<code>const</code>. When ordering
|
||||||
function parameters, put all input-only parameters before
|
function parameters, put all input-only parameters before
|
||||||
any output parameters. In particular, do not add new
|
any output parameters. In particular, do not add new
|
||||||
parameters to the end of the function just because they
|
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 <code>Append()</code>. If you are
|
rather than just <code>Append()</code>. If you are
|
||||||
overloading a function to support variable number of
|
overloading a function to support variable number of
|
||||||
arguments of the same type, consider making it take a
|
arguments of the same type, consider making it take a
|
||||||
<code>vector</code> so that the user can use an
|
<code>std::vector</code> so that the user can use an
|
||||||
<a href="#Braced_Initializer_List">initializer list
|
<a href="#Braced_Initializer_List">initializer list
|
||||||
</a> to specify the arguments.</p>
|
</a> to specify the arguments.</p>
|
||||||
</div>
|
</div>
|
||||||
|
@ -2091,9 +2076,7 @@ underlying object is immutable (i.e.
|
||||||
do use shared ownership, prefer to use
|
do use shared ownership, prefer to use
|
||||||
<code>std::shared_ptr</code>.</p>
|
<code>std::shared_ptr</code>.</p>
|
||||||
|
|
||||||
<p>Do not use <code>scoped_ptr</code> in new code unless
|
<p>Never use <code>std::auto_ptr</code>. Instead, use
|
||||||
you need to be compatible with older versions of C++.
|
|
||||||
Never use <code>std::auto_ptr</code>. Instead, use
|
|
||||||
<code>std::unique_ptr</code>.</p>
|
<code>std::unique_ptr</code>.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -2155,7 +2138,7 @@ rvalue reference to a string.</p>
|
||||||
<li>Defining a move constructor (a constructor taking
|
<li>Defining a move constructor (a constructor taking
|
||||||
an rvalue reference to the class type) makes it
|
an rvalue reference to the class type) makes it
|
||||||
possible to move a value instead of copying it. If
|
possible to move a value instead of copying it. If
|
||||||
<code>v1</code> is a <code>vector<string></code>,
|
<code>v1</code> is a <code>std::vector<string></code>,
|
||||||
for example, then <code>auto v2(std::move(v1))</code>
|
for example, then <code>auto v2(std::move(v1))</code>
|
||||||
will probably just result in some simple pointer
|
will probably just result in some simple pointer
|
||||||
manipulation instead of copying a large amount of data.
|
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. </p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h3 id="Variable-Length_Arrays_and_alloca__">
|
|
||||||
Variable-Length Arrays and alloca()</h3>
|
|
||||||
|
|
||||||
<div class="summary">
|
|
||||||
<p>We do not allow variable-length arrays or
|
|
||||||
<code>alloca()</code>.</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="stylebody">
|
|
||||||
|
|
||||||
<div class="pros">
|
|
||||||
<p>Variable-length arrays have natural-looking syntax. Both
|
|
||||||
variable-length arrays and <code>alloca()</code> are very
|
|
||||||
efficient.</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="cons">
|
|
||||||
<p>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".</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="decision">
|
|
||||||
|
|
||||||
|
|
||||||
<p>Use a safe allocator instead, such as
|
|
||||||
<code>vector</code> or
|
|
||||||
<code>std::unique_ptr<T[]></code>.</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h3 id="Friends">Friends</h3>
|
<h3 id="Friends">Friends</h3>
|
||||||
|
|
||||||
<div class="summary">
|
<div class="summary">
|
||||||
|
@ -3130,9 +3079,10 @@ uint64_t my_mask = 3ULL << 48;
|
||||||
<h3 id="Preprocessor_Macros">Preprocessor Macros</h3>
|
<h3 id="Preprocessor_Macros">Preprocessor Macros</h3>
|
||||||
|
|
||||||
<div class="summary">
|
<div class="summary">
|
||||||
<p>Be very cautious with macros. Prefer inline functions,
|
<p>Avoid defining macros, especially in headers; prefer
|
||||||
enums, and <code>const</code> variables to macros. Don't
|
inline functions, enums, and <code>const</code> variables.
|
||||||
use macros to define pieces of a C++ API.</p>
|
Name macros with a project-specific prefix. Do not use
|
||||||
|
macros to define pieces of a C++ API.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
@ -3206,6 +3156,13 @@ possible:</p>
|
||||||
function/class/variable names.</li>
|
function/class/variable names.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
|
<p>Exporting macros from headers (i.e. defining them in a header
|
||||||
|
without <code>#undef</code>ing 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). </p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h3 id="0_and_nullptr/NULL">0 and nullptr/NULL</h3>
|
<h3 id="0_and_nullptr/NULL">0 and nullptr/NULL</h3>
|
||||||
|
@ -3278,8 +3235,7 @@ memset(&data, 0, sizeof(data));
|
||||||
<p>Use <code>auto</code> to avoid type names that are noisy, obvious,
|
<p>Use <code>auto</code> to avoid type names that are noisy, obvious,
|
||||||
or unimportant - cases where the type doesn't aid in clarity for the
|
or unimportant - cases where the type doesn't aid in clarity for the
|
||||||
reader. Continue to use manifest type declarations when it helps
|
reader. Continue to use manifest type declarations when it helps
|
||||||
readability, and never use <code>auto</code> for anything but local
|
readability.</p>
|
||||||
variables.</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
@ -3295,7 +3251,6 @@ small code region, the repetition may not be aiding readability.</li>
|
||||||
the initialization expression, since that avoids the possibility of
|
the initialization expression, since that avoids the possibility of
|
||||||
unintended copies or type conversions.</li>
|
unintended copies or type conversions.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<p></p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="cons">
|
<div class="cons">
|
||||||
|
|
||||||
|
@ -3308,7 +3263,7 @@ like:</p>
|
||||||
auto i = y.Find(key);
|
auto i = y.Find(key);
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<p>It may not be obvious what the resulting types are if the type
|
<p>it may not be obvious what the resulting types are if the type
|
||||||
of <code>y</code> isn't very well known, or if <code>y</code> was
|
of <code>y</code> isn't very well known, or if <code>y</code> was
|
||||||
declared many lines earlier.</p>
|
declared many lines earlier.</p>
|
||||||
|
|
||||||
|
@ -3325,10 +3280,8 @@ than intended.</p>
|
||||||
|
|
||||||
<div class="decision">
|
<div class="decision">
|
||||||
|
|
||||||
<p><code>auto</code> is permitted, for local variables only, when it
|
<p><code>auto</code> is permitted when it increases readability,
|
||||||
increases readability, particularly as described below. Do not
|
particularly as described below. Never initialize an <code>auto</code>-typed
|
||||||
use <code>auto</code> for file-scope or namespace-scope variables, or
|
|
||||||
for class members. Never initialize an <code>auto</code>-typed
|
|
||||||
variable with a braced initializer list.</p>
|
variable with a braced initializer list.</p>
|
||||||
|
|
||||||
<p>Specific cases where <code>auto</code> is allowed or encouraged:
|
<p>Specific cases where <code>auto</code> is allowed or encouraged:
|
||||||
|
@ -3348,8 +3301,8 @@ nearby.</li>
|
||||||
anything other than equality comparison.</li>
|
anything other than equality comparison.</li>
|
||||||
<li>(Encouraged) When iterating over a map with a range-based loop
|
<li>(Encouraged) When iterating over a map with a range-based loop
|
||||||
(because it is often assumed that the correct type
|
(because it is often assumed that the correct type
|
||||||
is <code>pair<KeyType,ValueType></code> whereas it is actually
|
is <code>std::pair<KeyType, ValueType></code> whereas it is actually
|
||||||
<code>pair<const KeyType,ValueType></code>). This is
|
<code>std::pair<const KeyType, ValueType></code>). This is
|
||||||
particularly well paired with local <code>key</code>
|
particularly well paired with local <code>key</code>
|
||||||
and <code>value</code> aliases for <code>.first</code>
|
and <code>value</code> aliases for <code>.first</code>
|
||||||
and <code>.second</code> (often const-ref).
|
and <code>.second</code> (often const-ref).
|
||||||
|
@ -3364,7 +3317,6 @@ and <code>.second</code> (often const-ref).
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<p></p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
@ -3378,8 +3330,7 @@ and <code>.second</code> (often const-ref).
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
|
||||||
<p>In C++03, aggregate types (arrays and structs with no
|
<p>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.</p>
|
||||||
</p>
|
|
||||||
|
|
||||||
<pre>struct Point { int x; int y; };
|
<pre>struct Point { int x; int y; };
|
||||||
Point p = {1, 2};
|
Point p = {1, 2};
|
||||||
|
@ -3391,26 +3342,26 @@ be created with a braced initializer list, known as a
|
||||||
of its use.</p>
|
of its use.</p>
|
||||||
|
|
||||||
<pre>// Vector takes a braced-init-list of elements.
|
<pre>// 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.
|
// Basically the same, ignoring some small technicalities.
|
||||||
// You may choose to use either form.
|
// You may choose to use either form.
|
||||||
vector<string> v = {"foo", "bar"};
|
std::vector<string> v = {"foo", "bar"};
|
||||||
|
|
||||||
// Usable with 'new' expressions.
|
// Usable with 'new' expressions.
|
||||||
auto p = new vector<string>{"foo", "bar"};
|
auto p = new vector<string>{"foo", "bar"};
|
||||||
|
|
||||||
// A map can take a list of pairs. Nested braced-init-lists work.
|
// 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.
|
// 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.
|
// Iterate over a braced-init-list.
|
||||||
for (int i : {-1, -2, -3}) {}
|
for (int i : {-1, -2, -3}) {}
|
||||||
|
|
||||||
// Call a function using a braced-init-list.
|
// Call a function using a braced-init-list.
|
||||||
void TestFunction2(vector<int> v) {}
|
void TestFunction2(std::vector<int> v) {}
|
||||||
TestFunction2({1, 2, 3});
|
TestFunction2({1, 2, 3});
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
|
@ -3550,7 +3501,6 @@ wrapper <code>std::function</code>.
|
||||||
hand; very long nested anonymous functions can make
|
hand; very long nested anonymous functions can make
|
||||||
code harder to understand.</li>
|
code harder to understand.</li>
|
||||||
|
|
||||||
|
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -3599,6 +3549,7 @@ use a named function instead of a lambda.</li>
|
||||||
<li>Specify the return type of the lambda explicitly if that will
|
<li>Specify the return type of the lambda explicitly if that will
|
||||||
make it more obvious to readers, as with
|
make it more obvious to readers, as with
|
||||||
<a href="#auto"><code>auto</code></a>.</li>
|
<a href="#auto"><code>auto</code></a>.</li>
|
||||||
|
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -3759,19 +3710,28 @@ Currently, the following libraries are permitted:</p>
|
||||||
Statistical Distributions and Functions</a> from
|
Statistical Distributions and Functions</a> from
|
||||||
<code>boost/math/distributions</code></li>
|
<code>boost/math/distributions</code></li>
|
||||||
|
|
||||||
|
<li><a href="https://www.boost.org/libs/math/doc/html/special.html">
|
||||||
|
Special Functions</a> from <code>boost/math/special_functions</code></li>
|
||||||
|
|
||||||
<li><a href="https://www.boost.org/libs/multi_index/">
|
<li><a href="https://www.boost.org/libs/multi_index/">
|
||||||
Multi-index</a> from <code>boost/multi_index</code></li>
|
Multi-index</a> from <code>boost/multi_index</code></li>
|
||||||
|
|
||||||
<li><a href="https://www.boost.org/libs/heap/">
|
<li><a href="https://www.boost.org/libs/heap/">
|
||||||
Heap</a> from <code>boost/heap</code></li>
|
Heap</a> from <code>boost/heap</code></li>
|
||||||
|
|
||||||
<li>The flat containers from <a href="https://www.boost.org/libs/container/">
|
<li>The flat containers from
|
||||||
Container</a>:
|
<a href="https://www.boost.org/libs/container/">Container</a>:
|
||||||
<code>boost/container/flat_map</code>, and
|
<code>boost/container/flat_map</code>, and
|
||||||
<code>boost/container/flat_set</code></li>
|
<code>boost/container/flat_set</code></li>
|
||||||
|
|
||||||
<li><a href="https://www.boost.org/libs/intrusive/">
|
<li><a href="https://www.boost.org/libs/intrusive/">Intrusive</a>
|
||||||
Intrusive</a> from <code>boost/intrusive</code>.</li>
|
from <code>boost/intrusive</code>.</li>
|
||||||
|
|
||||||
|
<li><a href="https://www.boost.org/libs/sort/">The
|
||||||
|
<code>boost/sort</code> library</a>.</li>
|
||||||
|
|
||||||
|
<li><a href="https://www.boost.org/libs/preprocessor/">Preprocessor</a>
|
||||||
|
from <code>boost/preprocessor</code>.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<p>We are actively considering adding other Boost
|
<p>We are actively considering adding other Boost
|
||||||
|
@ -3977,8 +3937,8 @@ guide, the following C++11 features may not be used:</p>
|
||||||
as <code>__builtin_prefetch</code>, designated initializers (e.g.
|
as <code>__builtin_prefetch</code>, designated initializers (e.g.
|
||||||
<code>Foo f = {.field = 3}</code>), inline assembly, <code>__COUNTER__</code>,
|
<code>Foo f = {.field = 3}</code>), inline assembly, <code>__COUNTER__</code>,
|
||||||
<code>__PRETTY_FUNCTION__</code>, compound statement expressions (e.g.
|
<code>__PRETTY_FUNCTION__</code>, compound statement expressions (e.g.
|
||||||
<code>foo = ({ int x; Bar(&x); x })</code>, and the <code>a?:b</code>
|
<code>foo = ({ int x; Bar(&x); x })</code>, variable-length arrays and
|
||||||
syntax.</p>
|
<code>alloca()</code>, and the <code>a?:b</code> syntax.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pros">
|
<div class="pros">
|
||||||
|
@ -4146,7 +4106,17 @@ int pc_reader; // Lots of things can be abbreviated "pc".
|
||||||
int cstmr_id; // Deletes internal letters.
|
int cstmr_id; // Deletes internal letters.
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
</div>
|
<p>Note that certain universally-known abbreviations are OK, such as
|
||||||
|
<code>i</code> for an iteration variable and <code>T</code> for a
|
||||||
|
template parameter.</p>
|
||||||
|
|
||||||
|
<p>Template parameters should follow the naming style for their
|
||||||
|
category: type template parameters should follow the rules for
|
||||||
|
<a href="#Type_Names">type names</a>, and non-type template
|
||||||
|
parameters should follow the rules for <a href="#Variable_Names">
|
||||||
|
variable names</a>.
|
||||||
|
|
||||||
|
</p></div>
|
||||||
|
|
||||||
<h3 id="File_Names">File Names</h3>
|
<h3 id="File_Names">File Names</h3>
|
||||||
|
|
||||||
|
@ -4226,9 +4196,9 @@ enum UrlTableErrors { ...
|
||||||
<h3 id="Variable_Names">Variable Names</h3>
|
<h3 id="Variable_Names">Variable Names</h3>
|
||||||
|
|
||||||
<div class="summary">
|
<div class="summary">
|
||||||
<p>The names of variables and data members are all lowercase, with
|
<p>The names of variables (including function parameters) and data members are
|
||||||
underscores between words. Data members of classes (but not structs)
|
all lowercase, with underscores between words. Data members of classes (but not
|
||||||
additionally have trailing underscores. For instance:
|
structs) additionally have trailing underscores. For instance:
|
||||||
<code>a_local_variable</code>, <code>a_struct_data_member</code>,
|
<code>a_local_variable</code>, <code>a_struct_data_member</code>,
|
||||||
<code>a_class_data_member_</code>.</p>
|
<code>a_class_data_member_</code>.</p>
|
||||||
</div>
|
</div>
|
||||||
|
@ -4305,16 +4275,18 @@ versus a class.</p>
|
||||||
<h3 id="Function_Names">Function Names</h3>
|
<h3 id="Function_Names">Function Names</h3>
|
||||||
|
|
||||||
<div class="summary">
|
<div class="summary">
|
||||||
<p>Regular functions have mixed case; "cheap" functions may
|
<p>Regular functions have mixed case; accessors and mutators may be named
|
||||||
use lower case with underscores.</p>
|
like variables.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
|
||||||
<p>Ordinarily, functions should start with a capital letter and have
|
<p>Ordinarily, functions should start with a capital letter and have a
|
||||||
a capital letter for each new word (a.k.a. "upper camel case" or "Pascal case").
|
capital letter for each new word
|
||||||
Such names should not have underscores. Prefer to capitalize acronyms as
|
(a.k.a. "<a href="https://en.wikipedia.org/wiki/Camel_case">Camel
|
||||||
single words (i.e. <code>StartRpc()</code>, not <code>StartRPC()</code>).</p>
|
Case</a>" or "Pascal case"). Such names should not have
|
||||||
|
underscores. Prefer to capitalize acronyms as single words
|
||||||
|
(i.e. <code>StartRpc()</code>, not <code>StartRPC()</code>).</p>
|
||||||
|
|
||||||
<pre>AddTableEntry()
|
<pre>AddTableEntry()
|
||||||
DeleteUrl()
|
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
|
like functions, because the fact that they're
|
||||||
objects rather than functions is an unimportant implementation detail.)</p>
|
objects rather than functions is an unimportant implementation detail.)</p>
|
||||||
|
|
||||||
<p>Functions that are very cheap to call may instead follow the style
|
<p>Accessors and mutators (get and set functions) may be named like
|
||||||
for variable names (all lower-case, with underscores between words).
|
variables. These often correspond to actual member variables, but this is
|
||||||
The rule of thumb is that such a function should be so cheap that you
|
not required. For example, <code>int count()</code> and <code>void
|
||||||
normally wouldn't bother caching its return value when calling it in
|
set_count(int count)</code>.</p>
|
||||||
a loop. A canonical example is an inline method that just returns one
|
|
||||||
of the class's member variables.</p>
|
|
||||||
|
|
||||||
<pre>class MyClass {
|
|
||||||
public:
|
|
||||||
...
|
|
||||||
bool is_empty() const { return num_entries_ == 0; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
int num_entries_;
|
|
||||||
};
|
|
||||||
</pre>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h3 id="Namespace_Names">Namespace Names</h3>
|
<h3 id="Namespace_Names">Namespace Names</h3>
|
||||||
|
@ -4668,7 +4629,7 @@ bool IsTableFull();
|
||||||
|
|
||||||
<p>When documenting function overrides, focus on the
|
<p>When documenting function overrides, focus on the
|
||||||
specifics of the override itself, rather than repeating
|
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
|
cases, the override needs no additional documentation and
|
||||||
thus no comment is required.</p>
|
thus no comment is required.</p>
|
||||||
|
|
||||||
|
@ -4793,7 +4754,8 @@ DoSomethingElseThatIsLonger(); // Two spaces between the code and the comment.
|
||||||
// thus the comment lines up with the following comments and code.
|
// thus the comment lines up with the following comments and code.
|
||||||
DoSomethingElse(); // Two spaces before line comments normally.
|
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",
|
"First item",
|
||||||
// .. and should be aligned appropriately.
|
// .. and should be aligned appropriately.
|
||||||
"Second item"};
|
"Second item"};
|
||||||
|
@ -5134,7 +5096,7 @@ hit the tab key.</p>
|
||||||
<p>Return type on the same line as function name, parameters
|
<p>Return type on the same line as function name, parameters
|
||||||
on the same line if they fit. Wrap parameter lists which do
|
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
|
not fit on a single line as you would wrap arguments in a
|
||||||
function call.</p>
|
<a href="#Function_Calls">function call</a>.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
@ -5258,11 +5220,11 @@ lists like other comma-separated lists.</p>
|
||||||
<p>For by-reference captures, do not leave a space between the
|
<p>For by-reference captures, do not leave a space between the
|
||||||
ampersand (&) and the variable name.</p>
|
ampersand (&) and the variable name.</p>
|
||||||
<pre>int x = 0;
|
<pre>int x = 0;
|
||||||
auto add_to_x = [&x](int n) { x += n; };
|
auto x_plus_n = [&x](int n) -> int { return x + n; }
|
||||||
</pre>
|
</pre>
|
||||||
<p>Short lambdas may be written inline as function arguments.</p>
|
<p>Short lambdas may be written inline as function arguments.</p>
|
||||||
<pre>set<int> blacklist = {7, 8, 9};
|
<pre>std::set<int> blacklist = {7, 8, 9};
|
||||||
vector<int> digits = {3, 9, 1, 8, 4, 7, 1};
|
std::vector<int> digits = {3, 9, 1, 8, 4, 7, 1};
|
||||||
digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) {
|
digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) {
|
||||||
return blacklist.find(i) != blacklist.end();
|
return blacklist.find(i) != blacklist.end();
|
||||||
}),
|
}),
|
||||||
|
@ -5366,7 +5328,7 @@ is no name, assume a zero-length name.</p>
|
||||||
<pre>// Examples of braced init list on a single line.
|
<pre>// Examples of braced init list on a single line.
|
||||||
return {foo, bar};
|
return {foo, bar};
|
||||||
functioncall({foo, bar});
|
functioncall({foo, bar});
|
||||||
pair<int, int> p{foo, bar};
|
std::pair<int, int> p{foo, bar};
|
||||||
|
|
||||||
// When you have to wrap.
|
// When you have to wrap.
|
||||||
SomeFunction(
|
SomeFunction(
|
||||||
|
@ -5513,7 +5475,7 @@ if (condition) {
|
||||||
<p>Switch statements may use braces for blocks. Annotate
|
<p>Switch statements may use braces for blocks. Annotate
|
||||||
non-trivial fall-through between cases.
|
non-trivial fall-through between cases.
|
||||||
Braces are optional for single-statement loops.
|
Braces are optional for single-statement loops.
|
||||||
Empty loop bodies should use <code>{}</code> or <code>continue</code>.</p>
|
Empty loop bodies should use empty braces or <code>continue</code>.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stylebody">
|
<div class="stylebody">
|
||||||
|
@ -5564,13 +5526,13 @@ for (int i = 0; i < kSomeNumber; ++i) {
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
|
|
||||||
<p>Empty loop bodies should use <code>{}</code> or
|
<p>Empty loop bodies should use an empty pair of braces or <code>continue</code>,
|
||||||
<code>continue</code>, but not a single semicolon.</p>
|
but not a single semicolon.</p>
|
||||||
|
|
||||||
<pre>while (condition) {
|
<pre>while (condition) {
|
||||||
// Repeat test until it returns false.
|
// 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.
|
while (condition) continue; // Good - continue indicates no logic.
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
|
@ -5616,11 +5578,18 @@ char *c;
|
||||||
const string &str;
|
const string &str;
|
||||||
|
|
||||||
// These are fine, space following.
|
// These are fine, space following.
|
||||||
char* c; // but remember to do "char* c, *d, *e, ...;"!
|
char* c;
|
||||||
const string& str;
|
const string& str;
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<pre class="badcode">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.
|
||||||
|
<pre>// Fine if helpful for readability.
|
||||||
|
int x, y;
|
||||||
|
</pre>
|
||||||
|
<pre class="badcode">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 &
|
const string & str; // Bad - spaces on both sides of &
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
|
@ -5722,8 +5691,8 @@ will call a default constructor if available. To force the
|
||||||
non-<code>std::initializer_list</code> constructor, use parentheses
|
non-<code>std::initializer_list</code> constructor, use parentheses
|
||||||
instead of braces.</p>
|
instead of braces.</p>
|
||||||
|
|
||||||
<pre>vector<int> v(100, 1); // A vector of 100 1s.
|
<pre>std::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, 1.
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<p>Also, the brace form prevents narrowing of integral
|
<p>Also, the brace form prevents narrowing of integral
|
||||||
|
@ -6004,16 +5973,11 @@ if (x && !y)
|
||||||
|
|
||||||
<pre>// No spaces inside the angle brackets (< and >), before
|
<pre>// No spaces inside the angle brackets (< and >), before
|
||||||
// <, or between >( in a cast
|
// <, or between >( in a cast
|
||||||
vector<string> x;
|
std::vector<string> x;
|
||||||
y = static_cast<char*>(x);
|
y = static_cast<char*>(x);
|
||||||
|
|
||||||
// Spaces between type and pointer are OK, but be consistent.
|
// Spaces between type and pointer are OK, but be consistent.
|
||||||
vector<char *> x;
|
std::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;
|
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
@ -6201,6 +6165,6 @@ more interesting. Have fun!</p>
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</body></html></div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
120
javaguide.html
120
javaguide.html
|
@ -3,10 +3,11 @@
|
||||||
<head>
|
<head>
|
||||||
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
|
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
|
||||||
<title>Google Java Style Guide</title>
|
<title>Google Java Style Guide</title>
|
||||||
<link rel="stylesheet" type="text/css" href="javaguide.css"/>
|
<link rel="stylesheet" type="text/css" href="javaguide.css">
|
||||||
<script language="javascript" src="include/styleguide.js"></script>
|
<script language="javascript" src="include/styleguide.js"></script>
|
||||||
<link href="https://www.google.com/favicon.ico" type="image/x-icon" rel="shortcut icon" />
|
<link rel="shortcut icon" type="image/x-icon" href="https://www.google.com/favicon.ico" />
|
||||||
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js" type="text/javascript"></script></head>
|
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
|
||||||
|
</head>
|
||||||
<body onload="initStyleGuide();">
|
<body onload="initStyleGuide();">
|
||||||
<div id="content">
|
<div id="content">
|
||||||
<h1>Google Java Style Guide</h1>
|
<h1>Google Java Style Guide</h1>
|
||||||
|
@ -36,7 +37,11 @@ avoids giving <em>advice</em> that isn't clearly enforceable (whether by human o
|
||||||
<li>The term <em>class</em> is used inclusively to mean an "ordinary" class, enum class,
|
<li>The term <em>class</em> is used inclusively to mean an "ordinary" class, enum class,
|
||||||
interface or annotation type (<code class="prettyprint lang-java">@interface</code>).</li>
|
interface or annotation type (<code class="prettyprint lang-java">@interface</code>).</li>
|
||||||
|
|
||||||
<li>The term <em>comment</em> always refers to <em>implementation</em> comments. We do not
|
<li>The term <em>member</em> (of a class) is used inclusively to mean a nested class, field,
|
||||||
|
method, <em>or constructor</em>; that is, all top-level contents of a class except initializers
|
||||||
|
and comments.
|
||||||
|
|
||||||
|
</li><li>The term <em>comment</em> always refers to <em>implementation</em> comments. We do not
|
||||||
use the phrase "documentation comments", instead using the common term "Javadoc."</li>
|
use the phrase "documentation comments", instead using the common term "Javadoc."</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
|
@ -202,6 +207,11 @@ sorts before ';'.)</p>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<h4 id="s3.3.4-import-class-not-static">3.3.4 No static import for classes</h4>
|
||||||
|
|
||||||
|
<p>Static import is not used for static nested classes. They are imported with
|
||||||
|
normal imports.</p>
|
||||||
|
|
||||||
<h3 id="s3.4-class-declaration">3.4 Class declaration</h3>
|
<h3 id="s3.4-class-declaration">3.4 Class declaration</h3>
|
||||||
|
|
||||||
<a name="oneclassperfile"></a>
|
<a name="oneclassperfile"></a>
|
||||||
|
@ -209,16 +219,17 @@ sorts before ';'.)</p>
|
||||||
|
|
||||||
<p>Each top-level class resides in a source file of its own.</p>
|
<p>Each top-level class resides in a source file of its own.</p>
|
||||||
|
|
||||||
<h4 id="s3.4.2-class-member-ordering">3.4.2 Class member ordering</h4>
|
<a name="s3.4.2-class-member-ordering"></a>
|
||||||
|
<h4 id="s3.4.2-ordering-class-contents">3.4.2 Ordering of class contents</h4>
|
||||||
|
|
||||||
<p>The ordering of the members of a class can have a great effect on learnability, but there is
|
<p>The order you choose for the members and initializers of your class can have a great effect on
|
||||||
no single correct recipe for how to do it. Different classes may order their members
|
learnability. However, there's no single correct recipe for how to do it; different classes may
|
||||||
differently.</p>
|
order their contents in different ways.</p>
|
||||||
|
|
||||||
<p>What is important is that each class order its members in <strong><em>some</em> logical
|
<p>What is important is that each class uses <strong><em>some</em> logical order</strong>, which its
|
||||||
order</strong>, which its maintainer could explain if asked. For example, new methods are not
|
maintainer could explain if asked. For example, new methods are not just habitually added to the end
|
||||||
just habitually added to the end of the class, as that would yield "chronological by date
|
of the class, as that would yield "chronological by date added" ordering, which is not a logical
|
||||||
added" ordering, which is not a logical ordering.</p>
|
ordering.</p>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -226,8 +237,7 @@ added" ordering, which is not a logical ordering.</p>
|
||||||
<h5 id="s3.4.2.1-overloads-never-split">3.4.2.1 Overloads: never split</h5>
|
<h5 id="s3.4.2.1-overloads-never-split">3.4.2.1 Overloads: never split</h5>
|
||||||
|
|
||||||
<p>When a class has multiple constructors, or multiple methods with the same name, these appear
|
<p>When a class has multiple constructors, or multiple methods with the same name, these appear
|
||||||
sequentially, with no intervening members (not even private ones).</p>
|
sequentially, with no other code in between (not even private members).</p>
|
||||||
|
|
||||||
|
|
||||||
<h2 id="s4-formatting">4 Formatting</h2>
|
<h2 id="s4-formatting">4 Formatting</h2>
|
||||||
|
|
||||||
|
@ -299,16 +309,27 @@ return new MyClass() {
|
||||||
<a name="emptyblocks"></a>
|
<a name="emptyblocks"></a>
|
||||||
<h4 id="s4.1.3-braces-empty-blocks">4.1.3 Empty blocks: may be concise</h4>
|
<h4 id="s4.1.3-braces-empty-blocks">4.1.3 Empty blocks: may be concise</h4>
|
||||||
|
|
||||||
<p>An empty block or block-like construct <em>may</em> be closed immediately after it is
|
<p>An empty block or block-like construct may be in K & R style (as described in
|
||||||
opened, with no characters or line break in between
|
<a href="#s4.1.2-blocks-k-r-style">Section 4.1.2</a>). Alternatively, it may be closed immediately
|
||||||
|
after it is opened, with no characters or line break in between
|
||||||
(<code class="prettyprint lang-java">{}</code>), <strong>unless</strong> it is part of a
|
(<code class="prettyprint lang-java">{}</code>), <strong>unless</strong> it is part of a
|
||||||
<em>multi-block statement</em> (one that directly contains multiple blocks:
|
<em>multi-block statement</em> (one that directly contains multiple blocks:
|
||||||
<code class="prettyprint lang-java">if/else-if/else</code> or
|
<code class="prettyprint lang-java">if/else</code> or
|
||||||
<code class="prettyprint lang-java">try/catch/finally</code>).</p>
|
<code class="prettyprint lang-java">try/catch/finally</code>).</p>
|
||||||
|
|
||||||
<p>Example:</p>
|
<p>Examples:</p>
|
||||||
|
|
||||||
<pre class="prettyprint lang-java"> void doNothing() {}
|
<pre class="prettyprint lang-java"> // This is acceptable
|
||||||
|
void doNothing() {}
|
||||||
|
|
||||||
|
// This is equally acceptable
|
||||||
|
void doNothingElse() {
|
||||||
|
}
|
||||||
|
</pre>
|
||||||
|
<pre class="prettyprint lang-java badcode"> // This is not acceptable: No concise empty blocks in a multi-block statement
|
||||||
|
try {
|
||||||
|
doSomething();
|
||||||
|
} catch (Exception e) {}
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<h3 id="s4.2-block-indentation">4.2 Block indentation: +2 spaces</h3>
|
<h3 id="s4.2-block-indentation">4.2 Block indentation: +2 spaces</h3>
|
||||||
|
@ -370,12 +391,17 @@ without the need to line-wrap.</p>
|
||||||
the symbol. (Note that this is not the same practice used in Google style for other languages,
|
the symbol. (Note that this is not the same practice used in Google style for other languages,
|
||||||
such as C++ and JavaScript.)
|
such as C++ and JavaScript.)
|
||||||
<ul>
|
<ul>
|
||||||
<li>This also applies to the following "operator-like" symbols: the dot separator
|
<li>This also applies to the following "operator-like" symbols:
|
||||||
(<code class="prettyprint lang-java">.</code>), the two colons of a method reference
|
<ul>
|
||||||
(<code class="prettyprint lang-java">::</code>), the ampersand in type bounds
|
<li>the dot separator (<code class="prettyprint lang-java">.</code>)</li>
|
||||||
(<code class="prettyprint lang-java"><T extends Foo & Bar></code>), and the pipe in
|
<li>the two colons of a method reference
|
||||||
catch blocks
|
(<code class="prettyprint lang-java">::</code>)</li>
|
||||||
(<code class="prettyprint lang-java">catch (FooException | BarException e)</code>).</li>
|
<li>an ampersand in a type bound
|
||||||
|
(<code class="prettyprint lang-java"><T extends Foo & Bar></code>)</li>
|
||||||
|
<li>a pipe in a catch block
|
||||||
|
(<code class="prettyprint lang-java">catch (FooException | BarException e)</code>).</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
|
@ -392,6 +418,19 @@ without the need to line-wrap.</p>
|
||||||
|
|
||||||
<li>A comma (<code class="prettyprint lang-java">,</code>) stays attached to the token that
|
<li>A comma (<code class="prettyprint lang-java">,</code>) stays attached to the token that
|
||||||
precedes it.</li>
|
precedes it.</li>
|
||||||
|
|
||||||
|
<li>A line is never broken adjacent to the arrow in a lambda, except that a
|
||||||
|
break may come immediately after the arrow if the body of the lambda consists
|
||||||
|
of a single unbraced expression. Examples:
|
||||||
|
<pre class="prettyprint lang-java">MyLambda<String, Long, Object> lambda =
|
||||||
|
(String label, Long value, Object obj) -> {
|
||||||
|
...
|
||||||
|
};
|
||||||
|
|
||||||
|
Predicate<String> predicate = str ->
|
||||||
|
longExpressionInvolving(str);
|
||||||
|
</pre>
|
||||||
|
</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<p class="note"><strong>Note:</strong> The primary goal for line wrapping is to have clear
|
<p class="note"><strong>Note:</strong> The primary goal for line wrapping is to have clear
|
||||||
|
@ -418,8 +457,8 @@ previous lines.</p>
|
||||||
<p>A single blank line appears:</p>
|
<p>A single blank line appears:</p>
|
||||||
|
|
||||||
<ol>
|
<ol>
|
||||||
<li><em>Between</em> consecutive members (or initializers) of a class: fields, constructors,
|
<li><em>Between</em> consecutive members or initializers of a class: fields, constructors,
|
||||||
methods, nested classes, static initializers, instance initializers.
|
methods, nested classes, static initializers, and instance initializers.
|
||||||
<ul>
|
<ul>
|
||||||
<li><span class="exception"><strong>Exception:</strong> A blank line between two consecutive
|
<li><span class="exception"><strong>Exception:</strong> A blank line between two consecutive
|
||||||
fields (having no other code between them) is optional. Such blank lines are used as needed to
|
fields (having no other code between them) is optional. Such blank lines are used as needed to
|
||||||
|
@ -431,8 +470,8 @@ previous lines.</p>
|
||||||
|
|
||||||
<li>Between statements, <em>as needed</em> to organize the code into logical subsections.
|
<li>Between statements, <em>as needed</em> to organize the code into logical subsections.
|
||||||
|
|
||||||
</li><li><em>Optionally</em> before the first member or after the last member of the class (neither
|
</li><li><em>Optionally</em> before the first member or initializer, or after the last member or
|
||||||
encouraged nor discouraged).</li>
|
initializer of the class (neither encouraged nor discouraged).</li>
|
||||||
|
|
||||||
<li>As required by other sections of this document (such as Section 3,
|
<li>As required by other sections of this document (such as Section 3,
|
||||||
<a href="#s3-source-file-structure">Source file structure</a>, and Section 3.3,
|
<a href="#s3-source-file-structure">Source file structure</a>, and Section 3.3,
|
||||||
|
@ -490,7 +529,7 @@ Javadoc, a single ASCII space also appears in the following places <strong>only<
|
||||||
<li>the two colons (<code class="prettyprint lang-java">::</code>) of a method reference, which
|
<li>the two colons (<code class="prettyprint lang-java">::</code>) of a method reference, which
|
||||||
is written like <code class="prettyprint lang-java">Object::toString</code></li>
|
is written like <code class="prettyprint lang-java">Object::toString</code></li>
|
||||||
<li>the dot separator (<code class="prettyprint lang-java">.</code>), which is written like
|
<li>the dot separator (<code class="prettyprint lang-java">.</code>), which is written like
|
||||||
<code class="prettyprint lang-java">object.toString()</code></li>
|
<code class="prettyprint lang-java">object.toString()</code></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
|
@ -629,8 +668,8 @@ one or more <em>switch labels</em> (either <code class="prettyprint lang-java">c
|
||||||
|
|
||||||
<p>As with any other block, the contents of a switch block are indented +2.</p>
|
<p>As with any other block, the contents of a switch block are indented +2.</p>
|
||||||
|
|
||||||
<p>After a switch label, a newline appears, and the indentation level is increased +2, exactly as
|
<p>After a switch label, there is a line break, and the indentation level is increased +2, exactly
|
||||||
if a block were being opened. The following switch label returns to the previous indentation
|
as if a block were being opened. The following switch label returns to the previous indentation
|
||||||
level, as if a block had been closed.</p>
|
level, as if a block had been closed.</p>
|
||||||
|
|
||||||
<a name="fallthrough"></a>
|
<a name="fallthrough"></a>
|
||||||
|
@ -702,6 +741,9 @@ for example:</p>
|
||||||
<p>This section addresses <em>implementation comments</em>. Javadoc is addressed separately in
|
<p>This section addresses <em>implementation comments</em>. Javadoc is addressed separately in
|
||||||
Section 7, <a href="#s7-javadoc">Javadoc</a>.</p>
|
Section 7, <a href="#s7-javadoc">Javadoc</a>.</p>
|
||||||
|
|
||||||
|
<p>Any line break may be preceded by arbitrary whitespace followed by an implementation comment.
|
||||||
|
Such a comment renders the line non-blank.</p>
|
||||||
|
|
||||||
<h5 id="s4.8.6.1-block-comment-style">4.8.6.1 Block comment style</h5>
|
<h5 id="s4.8.6.1-block-comment-style">4.8.6.1 Block comment style</h5>
|
||||||
|
|
||||||
<p>Block comments are indented at the same level as the surrounding code. They may be in
|
<p>Block comments are indented at the same level as the surrounding code. They may be in
|
||||||
|
@ -802,15 +844,15 @@ Way to name test methods.</p>
|
||||||
<p>Constant names use <code class="prettyprint lang-java">CONSTANT_CASE</code>: all uppercase
|
<p>Constant names use <code class="prettyprint lang-java">CONSTANT_CASE</code>: all uppercase
|
||||||
letters, with words separated by underscores. But what <em>is</em> a constant, exactly?</p>
|
letters, with words separated by underscores. But what <em>is</em> a constant, exactly?</p>
|
||||||
|
|
||||||
<p>Every constant is a static final field, but not all static final fields are constants. Before
|
<p>Constants are static final fields whose contents are deeply immutable and whose methods have no
|
||||||
choosing constant case, consider whether the field really <em>feels like</em> a constant. For
|
detectable side effects. This includes primitives, Strings, immutable types, and immutable
|
||||||
example, if any of that instance's observable state can change, it is almost certainly not a
|
collections of immutable types. If any of the instance's observable state can change, it is not a
|
||||||
constant. Merely <em>intending</em> to never mutate the object is generally not
|
constant. Merely <em>intending</em> to never mutate the object is not enough. Examples:</p>
|
||||||
enough. Examples:</p>
|
|
||||||
|
|
||||||
<pre class="prettyprint lang-java">// Constants
|
<pre class="prettyprint lang-java">// Constants
|
||||||
static final int NUMBER = 5;
|
static final int NUMBER = 5;
|
||||||
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
|
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
|
||||||
|
static final ImmutableMap<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
|
||||||
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
|
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
|
||||||
static final SomeMutableType[] EMPTY_ARRAY = {};
|
static final SomeMutableType[] EMPTY_ARRAY = {};
|
||||||
enum SomeEnum { ENUM_CONSTANT }
|
enum SomeEnum { ENUM_CONSTANT }
|
||||||
|
@ -820,6 +862,8 @@ static String nonFinal = "non-final";
|
||||||
final String nonStatic = "non-static";
|
final String nonStatic = "non-static";
|
||||||
static final Set<String> mutableCollection = new HashSet<String>();
|
static final Set<String> mutableCollection = new HashSet<String>();
|
||||||
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
|
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
|
||||||
|
static final ImmutableMap<String, SomeMutableType> mutableValues =
|
||||||
|
ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
|
||||||
static final Logger logger = Logger.getLogger(MyClass.getName());
|
static final Logger logger = Logger.getLogger(MyClass.getName());
|
||||||
static final String[] nonEmptyArray = {"these", "can", "change"};
|
static final String[] nonEmptyArray = {"these", "can", "change"};
|
||||||
</pre>
|
</pre>
|
||||||
|
@ -1058,7 +1102,7 @@ are indented four (or more) spaces from the position of the <code>@</code>.
|
||||||
|
|
||||||
<h3 id="s7.2-summary-fragment">7.2 The summary fragment</h3>
|
<h3 id="s7.2-summary-fragment">7.2 The summary fragment</h3>
|
||||||
|
|
||||||
<p>The Javadoc for each class and member begins with a brief <strong>summary fragment</strong>. This
|
<p>Each Javadoc block begins with a brief <strong>summary fragment</strong>. This
|
||||||
fragment is very important: it is the only part of the text that appears in certain contexts such as
|
fragment is very important: it is the only part of the text that appears in certain contexts such as
|
||||||
class and method indexes.</p>
|
class and method indexes.</p>
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user