blob: 7f837ac059bd58340581436823ad0eaadbf5c92a [file] [log] [blame]
Ted Osborne505ba682018-01-30 12:36:50 -05001<!DOCTYPE html>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002<html lang="en">
Ted Osborne505ba682018-01-30 12:36:50 -05003<head>
Victor Costan6dfd9d92018-02-05 18:30:35 -08004<meta charset="utf-8">
Ted Osborne505ba682018-01-30 12:36:50 -05005<title>Google C++ Style Guide</title>
Victor Costan6dfd9d92018-02-05 18:30:35 -08006<link rel="stylesheet" href="include/styleguide.css">
7<script src="include/styleguide.js"></script>
8<link rel="shortcut icon" href="https://www.google.com/favicon.ico">
Ted Osborne505ba682018-01-30 12:36:50 -05009</head>
10<body onload="initStyleGuide();">
11<div id="content">
12<h1>Google C++ Style Guide</h1>
13<div class="horizontal_toc" id="tocDiv"></div>
14
15<div class="main_body">
16
17<h2 class="ignoreLink" id="Background">Background</h2>
18
19<p>C++ is one of the main development languages used by
20many of Google's open-source projects. As every C++
21programmer knows, the language has many powerful features, but
22this power brings with it complexity, which in turn can make
23code more bug-prone and harder to read and maintain.</p>
24
25<p>The goal of this guide is to manage this complexity by
26describing in detail the dos and don'ts of writing C++ code.
27These rules exist to
28keep the code base manageable while still allowing
29coders to use C++ language features productively.</p>
30
31<p><em>Style</em>, also known as readability, is what we call
32the conventions that govern our C++ code. The term Style is a
33bit of a misnomer, since these conventions cover far more than
34just source file formatting.</p>
35
36<p>
37Most open-source projects developed by
38Google conform to the requirements in this guide.
39</p>
40
41
42
43
44
45<p>Note that this guide is not a C++ tutorial: we assume that
46the reader is familiar with the language. </p>
47
48<h3 id="Goals">Goals of the Style Guide</h3>
49<div class="stylebody">
50<p>Why do we have this document?</p>
51
52<p>There are a few core goals that we believe this guide should
53serve. These are the fundamental <b>why</b>s that
54underlie all of the individual rules. By bringing these ideas to
55the fore, we hope to ground discussions and make it clearer to our
56broader community why the rules are in place and why particular
57decisions have been made. If you understand what goals each rule is
58serving, it should be clearer to everyone when a rule may be waived
59(some can be), and what sort of argument or alternative would be
60necessary to change a rule in the guide.</p>
61
62<p>The goals of the style guide as we currently see them are as follows:</p>
63<dl>
64<dt>Style rules should pull their weight</dt>
65<dd>The benefit of a style rule
66must be large enough to justify asking all of our engineers to
67remember it. The benefit is measured relative to the codebase we would
68get without the rule, so a rule against a very harmful practice may
69still have a small benefit if people are unlikely to do it
70anyway. This principle mostly explains the rules we don&#8217;t have, rather
71than the rules we do: for example, <code>goto</code> contravenes many
72of the following principles, but is already vanishingly rare, so the Style
73Guide doesn&#8217;t discuss it.</dd>
74
75<dt>Optimize for the reader, not the writer</dt>
76<dd>Our codebase (and most individual components submitted to it) is
77expected to continue for quite some time. As a result, more time will
78be spent reading most of our code than writing it. We explicitly
79choose to optimize for the experience of our average software engineer
80reading, maintaining, and debugging code in our codebase rather than
81ease when writing said code. "Leave a trace for the reader" is a
82particularly common sub-point of this principle: When something
83surprising or unusual is happening in a snippet of code (for example,
84transfer of pointer ownership), leaving textual hints for the reader
85at the point of use is valuable (<code>std::unique_ptr</code>
86demonstrates the ownership transfer unambiguously at the call
87site). </dd>
88
89<dt>Be consistent with existing code</dt>
90<dd>Using one style consistently through our codebase lets us focus on
91other (more important) issues. Consistency also allows for
92automation: tools that format your code or adjust
93your <code>#include</code>s only work properly when your code is
94consistent with the expectations of the tooling. In many cases, rules
95that are attributed to "Be Consistent" boil down to "Just pick one and
96stop worrying about it"; the potential value of allowing flexibility
97on these points is outweighed by the cost of having people argue over
98them. </dd>
99
100<dt>Be consistent with the broader C++ community when appropriate</dt>
101<dd>Consistency with the way other organizations use C++ has value for
102the same reasons as consistency within our code base. If a feature in
103the C++ standard solves a problem, or if some idiom is widely known
104and accepted, that's an argument for using it. However, sometimes
105standard features and idioms are flawed, or were just designed without
106our codebase's needs in mind. In those cases (as described below) it's
107appropriate to constrain or ban standard features. In some cases we
108prefer a homegrown or third-party library over a library defined in
109the C++ Standard, either out of perceived superiority or insufficient
110value to transition the codebase to the standard interface.</dd>
111
112<dt>Avoid surprising or dangerous constructs</dt>
113<dd>C++ has features that are more surprising or dangerous than one
114might think at a glance. Some style guide restrictions are in place to
115prevent falling into these pitfalls. There is a high bar for style
116guide waivers on such restrictions, because waiving such rules often
117directly risks compromising program correctness.
118</dd>
119
120<dt>Avoid constructs that our average C++ programmer would find tricky
121or hard to maintain</dt>
122<dd>C++ has features that may not be generally appropriate because of
123the complexity they introduce to the code. In widely used
124code, it may be more acceptable to use
125trickier language constructs, because any benefits of more complex
126implementation are multiplied widely by usage, and the cost in understanding
127the complexity does not need to be paid again when working with new
128portions of the codebase. When in doubt, waivers to rules of this type
129can be sought by asking
130your project leads. This is specifically
131important for our codebase because code ownership and team membership
132changes over time: even if everyone that works with some piece of code
133currently understands it, such understanding is not guaranteed to hold a
134few years from now.</dd>
135
136<dt>Be mindful of our scale</dt>
137<dd>With a codebase of 100+ million lines and thousands of engineers,
138some mistakes and simplifications for one engineer can become costly
139for many. For instance it's particularly important to
140avoid polluting the global namespace: name collisions across a
141codebase of hundreds of millions of lines are difficult to work with
142and hard to avoid if everyone puts things into the global
143namespace.</dd>
144
145<dt>Concede to optimization when necessary</dt>
146<dd>Performance optimizations can sometimes be necessary and
147appropriate, even when they conflict with the other principles of this
148document.</dd>
149</dl>
150
151<p>The intent of this document is to provide maximal guidance with
152reasonable restriction. As always, common sense and good taste should
153prevail. By this we specifically refer to the established conventions
154of the entire Google C++ community, not just your personal preferences
155or those of your team. Be skeptical about and reluctant to use
156clever or unusual constructs: the absence of a prohibition is not the
157same as a license to proceed. Use your judgment, and if you are
158unsure, please don't hesitate to ask your project leads to get additional
159input.</p>
160
161</div>
162
163
164
165<h2 id="Header_Files">Header Files</h2>
166
167<p>In general, every <code>.cc</code> file should have an
168associated <code>.h</code> file. There are some common
169exceptions, such as unittests and
170small <code>.cc</code> files containing just a
171<code>main()</code> function.</p>
172
173<p>Correct use of header files can make a huge difference to
174the readability, size and performance of your code.</p>
175
176<p>The following rules will guide you through the various
177pitfalls of using header files.</p>
178
179<a id="The_-inl.h_Files"></a>
180<h3 id="Self_contained_Headers">Self-contained Headers</h3>
181
182<div class="summary">
183<p>Header files should be self-contained (compile on their own) and
184end in <code>.h</code>. Non-header files that are meant for inclusion
185should end in <code>.inc</code> and be used sparingly.</p>
186</div>
187
188<div class="stylebody">
189<p>All header files should be self-contained. Users and refactoring
190tools should not have to adhere to special conditions to include the
191header. Specifically, a header should
192have <a href="#The__define_Guard">header guards</a> and include all
193other headers it needs.</p>
194
195<p>Prefer placing the definitions for template and inline functions in
196the same file as their declarations. The definitions of these
197constructs must be included into every <code>.cc</code> file that uses
198them, or the program may fail to link in some build configurations. If
199declarations and definitions are in different files, including the
200former should transitively include the latter. Do not move these
201definitions to separately included header files (<code>-inl.h</code>);
202this practice was common in the past, but is no longer allowed.</p>
203
204<p>As an exception, a template that is explicitly instantiated for
205all relevant sets of template arguments, or that is a private
206implementation detail of a class, is allowed to be defined in the one
207and only <code>.cc</code> file that instantiates the template.</p>
208
209<p>There are rare cases where a file designed to be included is not
210self-contained. These are typically intended to be included at unusual
211locations, such as the middle of another file. They might not
212use <a href="#The__define_Guard">header guards</a>, and might not include
213their prerequisites. Name such files with the <code>.inc</code>
214extension. Use sparingly, and prefer self-contained headers when
215possible.</p>
216
217</div>
218
219<h3 id="The__define_Guard">The #define Guard</h3>
220
221<div class="summary">
222<p>All header files should have <code>#define</code> guards to
223prevent multiple inclusion. The format of the symbol name
224should be
225<code><i>&lt;PROJECT&gt;</i>_<i>&lt;PATH&gt;</i>_<i>&lt;FILE&gt;</i>_H_</code>.</p>
226</div>
227
228<div class="stylebody">
229
230
231
232<p>To guarantee uniqueness, they should
233be based on the full path in a project's source tree. For
234example, the file <code>foo/src/bar/baz.h</code> in
235project <code>foo</code> should have the following
236guard:</p>
237
238<pre>#ifndef FOO_BAR_BAZ_H_
239#define FOO_BAR_BAZ_H_
240
241...
242
243#endif // FOO_BAR_BAZ_H_
244</pre>
245
246
247
248
249</div>
250
251<h3 id="Forward_Declarations">Forward Declarations</h3>
252
253<div class="summary">
254 <p>Avoid using forward declarations where possible.
255 Just <code>#include</code> the headers you need.</p>
256</div>
257
258<div class="stylebody">
259
260<div class="definition">
261<p>A "forward declaration" is a declaration of a class,
262function, or template without an associated definition.</p>
263</div>
264
265<div class="pros">
266<ul>
267 <li>Forward declarations can save compile time, as
268 <code>#include</code>s force the compiler to open
269 more files and process more input.</li>
270
271 <li>Forward declarations can save on unnecessary
272 recompilation. <code>#include</code>s can force
273 your code to be recompiled more often, due to unrelated
274 changes in the header.</li>
275</ul>
276</div>
277
278<div class="cons">
279<ul>
280 <li>Forward declarations can hide a dependency, allowing
281 user code to skip necessary recompilation when headers
282 change.</li>
283
284 <li>A forward declaration may be broken by subsequent
285 changes to the library. Forward declarations of functions
286 and templates can prevent the header owners from making
287 otherwise-compatible changes to their APIs, such as
288 widening a parameter type, adding a template parameter
289 with a default value, or migrating to a new namespace.</li>
290
291 <li>Forward declaring symbols from namespace
292 <code>std::</code> yields undefined behavior.</li>
293
294 <li>It can be difficult to determine whether a forward
295 declaration or a full <code>#include</code> is needed.
296 Replacing an <code>#include</code> with a forward
297 declaration can silently change the meaning of
298 code:
299 <pre> // b.h:
300 struct B {};
301 struct D : B {};
302
303 // good_user.cc:
304 #include "b.h"
305 void f(B*);
306 void f(void*);
307 void test(D* x) { f(x); } // calls f(B*)
308 </pre>
309 If the <code>#include</code> was replaced with forward
310 decls for <code>B</code> and <code>D</code>,
311 <code>test()</code> would call <code>f(void*)</code>.
312 </li>
313
314 <li>Forward declaring multiple symbols from a header
315 can be more verbose than simply
316 <code>#include</code>ing the header.</li>
317
318 <li>Structuring code to enable forward declarations
319 (e.g. using pointer members instead of object members)
320 can make the code slower and more complex.</li>
321
322
323</ul>
324</div>
325
326<div class="decision">
327<ul>
328 <li>Try to avoid forward declarations of entities
329 defined in another project.</li>
330
331 <li>When using a function declared in a header file,
332 always <code>#include</code> that header.</li>
333
334 <li>When using a class template, prefer to
335 <code>#include</code> its header file.</li>
336</ul>
337
338<p>Please see <a href="#Names_and_Order_of_Includes">Names and Order
339of Includes</a> for rules about when to #include a header.</p>
340</div>
341
342</div>
343
344<h3 id="Inline_Functions">Inline Functions</h3>
345
346<div class="summary">
347<p>Define functions inline only when they are small, say, 10
348lines or fewer.</p>
349</div>
350
351<div class="stylebody">
352
353<div class="definition">
354<p>You can declare functions in a way that allows the compiler to expand
355them inline rather than calling them through the usual
356function call mechanism.</p>
357</div>
358
359<div class="pros">
360<p>Inlining a function can generate more efficient object
361code, as long as the inlined function is small. Feel free
362to inline accessors and mutators, and other short,
363performance-critical functions.</p>
364</div>
365
366<div class="cons">
367<p>Overuse of inlining can actually make programs slower.
368Depending on a function's size, inlining it can cause the
369code size to increase or decrease. Inlining a very small
370accessor function will usually decrease code size while
371inlining a very large function can dramatically increase
372code size. On modern processors smaller code usually runs
373faster due to better use of the instruction cache.</p>
374</div>
375
376<div class="decision">
377<p>A decent rule of thumb is to not inline a function if
378it is more than 10 lines long. Beware of destructors,
379which are often longer than they appear because of
380implicit member- and base-destructor calls!</p>
381
382<p>Another useful rule of thumb: it's typically not cost
383effective to inline functions with loops or switch
384statements (unless, in the common case, the loop or
385switch statement is never executed).</p>
386
387<p>It is important to know that functions are not always
388inlined even if they are declared as such; for example,
389virtual and recursive functions are not normally inlined.
390Usually recursive functions should not be inline. The
391main reason for making a virtual function inline is to
392place its definition in the class, either for convenience
393or to document its behavior, e.g., for accessors and
394mutators.</p>
395</div>
396
397</div>
398
399<h3 id="Names_and_Order_of_Includes">Names and Order of Includes</h3>
400
401<div class="summary">
402<p>Use standard order for readability and to avoid hidden
403dependencies: Related header, C library, C++ library, other libraries'
404<code>.h</code>, your project's <code>.h</code>.</p>
405</div>
406
407<div class="stylebody">
408<p>
409All of a project's header files should be
410listed as descendants of the project's source
411directory without use of UNIX directory shortcuts
412<code>.</code> (the current directory) or <code>..</code>
413(the parent directory). For example,
414
415<code>google-awesome-project/src/base/logging.h</code>
416should be included as:</p>
417
418<pre>#include "base/logging.h"
419</pre>
420
421<p>In <code><var>dir/foo</var>.cc</code> or
422<code><var>dir/foo_test</var>.cc</code>, whose main
423purpose is to implement or test the stuff in
424<code><var>dir2/foo2</var>.h</code>, order your includes
425as follows:</p>
426
427<ol>
428 <li><code><var>dir2/foo2</var>.h</code>.</li>
429
Victor Costan6dfd9d92018-02-05 18:30:35 -0800430 <li>A blank line</li>
431
Ted Osborne505ba682018-01-30 12:36:50 -0500432 <li>C system files.</li>
433
434 <li>C++ system files.</li>
435
Victor Costan6dfd9d92018-02-05 18:30:35 -0800436 <li>A blank line</li>
437
Ted Osborne505ba682018-01-30 12:36:50 -0500438 <li>Other libraries' <code>.h</code>
439 files.</li>
440
441 <li>
442 Your project's <code>.h</code>
443 files.</li>
444</ol>
445
Victor Costan6dfd9d92018-02-05 18:30:35 -0800446<p>Note that any adjacent blank lines should be collapsed.</p>
447
Ted Osborne505ba682018-01-30 12:36:50 -0500448<p>With the preferred ordering, if
449<code><var>dir2/foo2</var>.h</code> omits any necessary
450includes, the build of <code><var>dir/foo</var>.cc</code>
451or <code><var>dir/foo</var>_test.cc</code> will break.
452Thus, this rule ensures that build breaks show up first
453for the people working on these files, not for innocent
454people in other packages.</p>
455
456<p><code><var>dir/foo</var>.cc</code> and
457<code><var>dir2/foo2</var>.h</code> are usually in the same
458directory (e.g. <code>base/basictypes_test.cc</code> and
459<code>base/basictypes.h</code>), but may sometimes be in different
460directories too.</p>
461
462
463
Victor Costan6dfd9d92018-02-05 18:30:35 -0800464<p>Note that the C compatibility headers such as <code>stddef.h</code>
465are essentially interchangeable with their C++ counterparts
466(<code>cstddef</code>)
467Either style is acceptable, but prefer consistency with existing code.</p>
468
Ted Osborne505ba682018-01-30 12:36:50 -0500469<p>Within each section the includes should be ordered
470alphabetically. Note that older code might not conform to
471this rule and should be fixed when convenient.</p>
472
473<p>You should include all the headers that define the symbols you rely
474upon, except in the unusual case of <a href="#Forward_Declarations">forward
475declaration</a>. If you rely on symbols from <code>bar.h</code>,
476don't count on the fact that you included <code>foo.h</code> which
477(currently) includes <code>bar.h</code>: include <code>bar.h</code>
478yourself, unless <code>foo.h</code> explicitly demonstrates its intent
479to provide you the symbols of <code>bar.h</code>. However, any
480includes present in the related header do not need to be included
481again in the related <code>cc</code> (i.e., <code>foo.cc</code> can
482rely on <code>foo.h</code>'s includes).</p>
483
484<p>For example, the includes in
485
486<code>google-awesome-project/src/foo/internal/fooserver.cc</code>
487might look like this:</p>
488
489
490<pre>#include "foo/server/fooserver.h"
491
492#include &lt;sys/types.h&gt;
493#include &lt;unistd.h&gt;
Ted Osborne505ba682018-01-30 12:36:50 -0500494#include &lt;vector&gt;
495
496#include "base/basictypes.h"
497#include "base/commandlineflags.h"
498#include "foo/server/bar.h"
499</pre>
500
501<p class="exception">Sometimes, system-specific code needs
502conditional includes. Such code can put conditional
503includes after other includes. Of course, keep your
504system-specific code small and localized. Example:</p>
505
506<pre>#include "foo/public/fooserver.h"
507
508#include "base/port.h" // For LANG_CXX11.
509
510#ifdef LANG_CXX11
511#include &lt;initializer_list&gt;
512#endif // LANG_CXX11
513</pre>
514
515</div>
516
517<h2 id="Scoping">Scoping</h2>
518
519<h3 id="Namespaces">Namespaces</h3>
520
521<div class="summary">
522<p>With few exceptions, place code in a namespace. Namespaces
523should have unique names based on the project name, and possibly
524its path. Do not use <i>using-directives</i> (e.g.
525<code>using namespace foo</code>). Do not use
526inline namespaces. For unnamed namespaces, see
527<a href="#Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and
528Static Variables</a>.
529</p></div>
530
531<div class="stylebody">
532
533<div class="definition">
534<p>Namespaces subdivide the global scope
535into distinct, named scopes, and so are useful for preventing
536name collisions in the global scope.</p>
537</div>
538
539<div class="pros">
540
541<p>Namespaces provide a method for preventing name conflicts
542in large programs while allowing most code to use reasonably
543short names.</p>
544
545<p>For example, if two different projects have a class
546<code>Foo</code> in the global scope, these symbols may
547collide at compile time or at runtime. If each project
548places their code in a namespace, <code>project1::Foo</code>
549and <code>project2::Foo</code> are now distinct symbols that
550do not collide, and code within each project's namespace
551can continue to refer to <code>Foo</code> without the prefix.</p>
552
553<p>Inline namespaces automatically place their names in
554the enclosing scope. Consider the following snippet, for
555example:</p>
556
Victor Costan6dfd9d92018-02-05 18:30:35 -0800557<pre>namespace outer {
558inline namespace inner {
Ted Osborne505ba682018-01-30 12:36:50 -0500559 void foo();
Victor Costan6dfd9d92018-02-05 18:30:35 -0800560} // namespace inner
561} // namespace outer
Ted Osborne505ba682018-01-30 12:36:50 -0500562</pre>
563
Victor Costan6dfd9d92018-02-05 18:30:35 -0800564<p>The expressions <code>outer::inner::foo()</code> and
565<code>outer::foo()</code> are interchangeable. Inline
Ted Osborne505ba682018-01-30 12:36:50 -0500566namespaces are primarily intended for ABI compatibility
567across versions.</p>
568</div>
569
570<div class="cons">
571
572<p>Namespaces can be confusing, because they complicate
573the mechanics of figuring out what definition a name refers
574to.</p>
575
576<p>Inline namespaces, in particular, can be confusing
577because names aren't actually restricted to the namespace
578where they are declared. They are only useful as part of
579some larger versioning policy.</p>
580
581<p>In some contexts, it's necessary to repeatedly refer to
582symbols by their fully-qualified names. For deeply-nested
583namespaces, this can add a lot of clutter.</p>
584</div>
585
586<div class="decision">
587
588<p>Namespaces should be used as follows:</p>
589
590<ul>
591 <li>Follow the rules on <a href="#Namespace_Names">Namespace Names</a>.
592 </li><li>Terminate namespaces with comments as shown in the given examples.
593 </li><li>
594
595 <p>Namespaces wrap the entire source file after
596 includes,
597 <a href="https://gflags.github.io/gflags/">
598 gflags</a> definitions/declarations
599 and forward declarations of classes from other namespaces.</p>
600
601<pre>// In the .h file
602namespace mynamespace {
603
604// All declarations are within the namespace scope.
605// Notice the lack of indentation.
606class MyClass {
607 public:
608 ...
609 void Foo();
610};
611
612} // namespace mynamespace
613</pre>
614
615<pre>// In the .cc file
616namespace mynamespace {
617
618// Definition of functions is within scope of the namespace.
619void MyClass::Foo() {
620 ...
621}
622
623} // namespace mynamespace
624</pre>
625
626 <p>More complex <code>.cc</code> files might have additional details,
627 like flags or using-declarations.</p>
628
629<pre>#include "a.h"
630
631DEFINE_FLAG(bool, someflag, false, "dummy flag");
632
Victor Costan6dfd9d92018-02-05 18:30:35 -0800633namespace mynamespace {
Ted Osborne505ba682018-01-30 12:36:50 -0500634
635using ::foo::bar;
636
Victor Costan6dfd9d92018-02-05 18:30:35 -0800637...code for mynamespace... // Code goes against the left margin.
Ted Osborne505ba682018-01-30 12:36:50 -0500638
Victor Costan6dfd9d92018-02-05 18:30:35 -0800639} // namespace mynamespace
Ted Osborne505ba682018-01-30 12:36:50 -0500640</pre>
641 </li>
642
643
644
645 <li>Do not declare anything in namespace
646 <code>std</code>, including forward declarations of
647 standard library classes. Declaring entities in
648 namespace <code>std</code> is undefined behavior, i.e.,
649 not portable. To declare entities from the standard
650 library, include the appropriate header file.</li>
651
652 <li><p>You may not use a <i>using-directive</i>
653 to make all names from a namespace available.</p>
654
655<pre class="badcode">// Forbidden -- This pollutes the namespace.
656using namespace foo;
657</pre>
658 </li>
659
660 <li><p>Do not use <i>Namespace aliases</i> at namespace scope
661 in header files except in explicitly marked
662 internal-only namespaces, because anything imported into a namespace
663 in a header file becomes part of the public
664 API exported by that file.</p>
665
666<pre>// Shorten access to some commonly used names in .cc files.
667namespace baz = ::foo::bar::baz;
668</pre>
669
670<pre>// Shorten access to some commonly used names (in a .h file).
671namespace librarian {
672namespace impl { // Internal, not part of the API.
673namespace sidetable = ::pipeline_diagnostics::sidetable;
674} // namespace impl
675
676inline void my_inline_function() {
677 // namespace alias local to a function (or method).
678 namespace baz = ::foo::bar::baz;
679 ...
680}
681} // namespace librarian
682</pre>
683
684 </li><li>Do not use inline namespaces.</li>
685</ul>
686</div>
687</div>
688
689<h3 id="Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and Static
690Variables</h3>
691
692<div class="summary">
693<p>When definitions in a <code>.cc</code> file do not need to be
694referenced outside that file, place them in an unnamed
695namespace or declare them <code>static</code>. Do not use either
696of these constructs in <code>.h</code> files.
697</p></div>
698
699<div class="stylebody">
700
701<div class="definition">
Victor Costan6dfd9d92018-02-05 18:30:35 -0800702<p>All declarations can be given internal linkage by placing them in unnamed
703namespaces. Functions and variables can also be given internal linkage by
Ted Osborne505ba682018-01-30 12:36:50 -0500704declaring them <code>static</code>. This means that anything you're declaring
Victor Costan6dfd9d92018-02-05 18:30:35 -0800705can't be accessed from another file. If a different file declares something with
706the same name, then the two entities are completely independent.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500707</div>
708
709<div class="decision">
710
711<p>Use of internal linkage in <code>.cc</code> files is encouraged
712for all code that does not need to be referenced elsewhere.
713Do not use internal linkage in <code>.h</code> files.</p>
714
715<p>Format unnamed namespaces like named namespaces. In the
716 terminating comment, leave the namespace name empty:</p>
717
718<pre>namespace {
719...
720} // namespace
721</pre>
722</div>
723</div>
724
725<h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3>
726
727<div class="summary">
728<p>Prefer placing nonmember functions in a namespace; use completely global
Victor Costan6dfd9d92018-02-05 18:30:35 -0800729functions rarely. Do not use a class simply to group static functions. Static
730methods of a class should generally be closely related to instances of the
731class or the class's static data.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500732</div>
733
734 <div class="stylebody">
735
736 <div class="pros">
737 <p>Nonmember and static member functions can be useful in
738 some situations. Putting nonmember functions in a
739 namespace avoids polluting the global namespace.</p>
740 </div>
741
742<div class="cons">
743<p>Nonmember and static member functions may make more sense
744as members of a new class, especially if they access
745external resources or have significant dependencies.</p>
746</div>
747
748<div class="decision">
749<p>Sometimes it is useful to define a
750function not bound to a class instance. Such a function
751can be either a static member or a nonmember function.
752Nonmember functions should not depend on external
753variables, and should nearly always exist in a namespace.
Victor Costan6dfd9d92018-02-05 18:30:35 -0800754Do not create classes only to group static member functions;
755this is no different than just giving the function names a
756common prefix, and such grouping is usually unnecessary anyway.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500757
758<p>If you define a nonmember function and it is only
759needed in its <code>.cc</code> file, use
760<a href="#Unnamed_Namespaces_and_Static_Variables">internal linkage</a> to limit
761its scope.</p>
762</div>
763
764</div>
765
766<h3 id="Local_Variables">Local Variables</h3>
767
768<div class="summary">
769<p>Place a function's variables in the narrowest scope
770possible, and initialize variables in the declaration.</p>
771</div>
772
773<div class="stylebody">
774
775<p>C++ allows you to declare variables anywhere in a
776function. We encourage you to declare them in as local a
777scope as possible, and as close to the first use as
778possible. This makes it easier for the reader to find the
779declaration and see what type the variable is and what it
780was initialized to. In particular, initialization should
781be used instead of declaration and assignment, e.g.:</p>
782
783<pre class="badcode">int i;
784i = f(); // Bad -- initialization separate from declaration.
785</pre>
786
787<pre>int j = g(); // Good -- declaration has initialization.
788</pre>
789
790<pre class="badcode">std::vector&lt;int&gt; v;
791v.push_back(1); // Prefer initializing using brace initialization.
792v.push_back(2);
793</pre>
794
795<pre>std::vector&lt;int&gt; v = {1, 2}; // Good -- v starts initialized.
796</pre>
797
798<p>Variables needed for <code>if</code>, <code>while</code>
799and <code>for</code> statements should normally be declared
800within those statements, so that such variables are confined
801to those scopes. E.g.:</p>
802
803<pre>while (const char* p = strchr(str, '/')) str = p + 1;
804</pre>
805
806<p>There is one caveat: if the variable is an object, its
807constructor is invoked every time it enters scope and is
808created, and its destructor is invoked every time it goes
809out of scope.</p>
810
811<pre class="badcode">// Inefficient implementation:
812for (int i = 0; i &lt; 1000000; ++i) {
813 Foo f; // My ctor and dtor get called 1000000 times each.
814 f.DoSomething(i);
815}
816</pre>
817
818<p>It may be more efficient to declare such a variable
819used in a loop outside that loop:</p>
820
821<pre>Foo f; // My ctor and dtor get called once each.
822for (int i = 0; i &lt; 1000000; ++i) {
823 f.DoSomething(i);
824}
825</pre>
826
827</div>
828
829<h3 id="Static_and_Global_Variables">Static and Global Variables</h3>
830
831<div class="summary">
Victor Costan6dfd9d92018-02-05 18:30:35 -0800832<p>Objects with
833<a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration">
834static storage duration</a> are forbidden unless they are
835<a href="http://en.cppreference.com/w/cpp/types/is_destructible">trivially
836destructible</a>. Informally this means that the destructor does not do
837anything, even taking member and base destructors into account. More formally it
838means that the type has no user-defined or virtual destructor and that all bases
839and non-static members are trivially destructible.
840Static function-local variables may use dynamic initialization.
841Use of dynamic initialization for static class member variables or variables at
842namespace scope is discouraged, but allowed in limited circumstances; see below
843for details.</p>
844
845<p>As a rule of thumb: a global variable satisfies these requirements if its
846declaration, considered in isolation, could be <code>constexpr</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500847</div>
848
849<div class="stylebody">
850
Victor Costan6dfd9d92018-02-05 18:30:35 -0800851<div class="definition">
852<p>Every object has a <dfn>storage duration</dfn>, which correlates with its
853lifetime. Objects with static storage duration live from the point of their
854initialization until the end of the program. Such objects appear as variables at
855namespace scope ("global variables"), as static data members of classes, or as
856function-local variables that are declared with the <code>static</code>
857specifier. Function-local static variables are initialized when control first
858passes through their declaration; all other objects with static storage duration
859are initialized as part of program start-up. All objects with static storage
860duration are destroyed at program exit (which happens before unjoined threads
861are terminated).</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500862
Victor Costan6dfd9d92018-02-05 18:30:35 -0800863<p>Initialization may be <dfn>dynamic</dfn>, which means that something
864non-trivial happens during initialization. (For example, consider a constructor
865that allocates memory, or a variable that is initialized with the current
866process ID.) The other kind of initialization is <dfn>static</dfn>
867initialization. The two aren't quite opposites, though: static
868initialization <em>always</em> happens to objects with static storage duration
869(initializing the object either to a given constant or to a representation
870consisting of all bytes set to zero), whereas dynamic initialization happens
871after that, if required.</p>
872</div>
Ted Osborne505ba682018-01-30 12:36:50 -0500873
Victor Costan6dfd9d92018-02-05 18:30:35 -0800874<div class="pros">
875<p>Global and static variables are very useful for a large number of
876applications: named constants, auxiliary data structures internal to some
877translation unit, command-line flags, logging, registration mechanisms,
878background infrastructure, etc.</p>
879</div>
Ted Osborne505ba682018-01-30 12:36:50 -0500880
Victor Costan6dfd9d92018-02-05 18:30:35 -0800881<div class="cons">
882<p>Global and static variables that use dynamic initialization or have
883non-trivial destructors create complexity that can easily lead to hard-to-find
884bugs. Dynamic initialization is not ordered across translation units, and
885neither is destruction (except that destruction
886happens in reverse order of initialization). When one initialization refers to
887another variable with static storage duration, it is possible that this causes
888an object to be accessed before its lifetime has begun (or after its lifetime
889has ended). Moreover, when a program starts threads that are not joined at exit,
890those threads may attempt to access objects after their lifetime has ended if
891their destructor has already run.</p>
892</div>
Ted Osborne505ba682018-01-30 12:36:50 -0500893
Victor Costan6dfd9d92018-02-05 18:30:35 -0800894<div class="decision">
895<h4>Decision on destruction</h4>
896
897<p>When destructors are trivial, their execution is not subject to ordering at
898all (they are effectively not "run"); otherwise we are exposed to the risk of
899accessing objects after the end of their lifetime. Therefore, we only allow
900objects with static storage duration if they are trivially destructible.
901Fundamental types (like pointers and <code>int</code>) are trivially
902destructible, as are arrays of trivially destructible types. Note that
903variables marked with <code>constexpr</code> are trivially destructible.</p>
904<pre>const int kNum = 10; // allowed
905
906struct X { int n; };
907const X kX[] = {{1}, {2}, {3}}; // allowed
908
909void foo() {
910 static const char* const kMessages[] = {"hello", "world"}; // allowed
911}
912
913// allowed: constexpr guarantees trivial destructor
914constexpr std::array&lt;int, 3&gt; kArray = {{1, 2, 3}};</pre>
915<pre class="badcode">// bad: non-trivial destructor
916const string kFoo = "foo";
917
918// bad for the same reason, even though kBar is a reference (the
919// rule also applies to lifetime-extended temporary objects)
920const string&amp; kBar = StrCat("a", "b", "c");
921
922void bar() {
923 // bad: non-trivial destructor
924 static std::map&lt;int, int&gt; kData = {{1, 0}, {2, 0}, {3, 0}};
925}</pre>
926
927<p>Note that references are not objects, and thus they are not subject to the
928constraints on destructibility. The constraint on dynamic initialization still
929applies, though. In particular, a function-local static reference of the form
930<code>static T&amp; t = *new T;</code> is allowed.</p>
931
932<h4>Decision on initialization</h4>
933
934<p>Initialization is a more complex topic. This is because we must not only
935consider whether class constructors execute, but we must also consider the
936evaluation of the initializer:</p>
937<pre class="neutralcode">int n = 5; // fine
938int m = f(); // ? (depends on f)
939Foo x; // ? (depends on Foo::Foo)
940Bar y = g(); // ? (depends on g and on Bar::Bar)</pre>
941
942<p>All but the first statement expose us to indeterminate initialization
943ordering.</p>
944
945<p>The concept we are looking for is called <em>constant initialization</em> in
946the formal language of the C++ standard. It means that the initializing
947expression is a constant expression, and if the object is initialized by a
948constructor call, then the constructor must be specified as
949<code>constexpr</code>, too:</p>
950<pre>struct Foo { constexpr Foo(int) {} };
951
952int n = 5; // fine, 5 is a constant expression
953Foo x(2); // fine, 2 is a constant expression and the chosen constructor is constexpr
954Foo a[] = { Foo(1), Foo(2), Foo(3) }; // fine</pre>
955
956<p>Constant initialization is always allowed. Constant initialization of
957static storage duration variables should be marked with <code>constexpr</code>
958where possible. Any non-local static storage
959duration variable that is not so marked should be presumed to have
960dynamic initialization, and reviewed very carefully.</p>
961
962<p>By contrast, the following initializations are problematic:</p>
963
964<pre class="neutralcode">time_t time(time_t*); // not constexpr!
965int f(); // not constexpr!
966struct Bar { Bar() {} };
967
968time_t m = time(nullptr); // initializing expression not a constant expression
969Foo y(f()); // ditto
970Bar b; // chosen constructor Bar::Bar() not constexpr</pre>
971
972<p>Dynamic initialization of nonlocal variables is discouraged, and in general
973it is forbidden. However, we do permit it if no aspect of the program depends
974on the sequencing of this initialization with respect to all other
975initializations. Under those restrictions, the ordering of the initialization
976does not make an observable difference. For example:</p>
977<pre>int p = getpid(); // allowed, as long as no other static variable
978 // uses p in its own initialization</pre>
979
980<p>Dynamic initialization of static local variables is allowed (and common).</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500981
982
Victor Costan6dfd9d92018-02-05 18:30:35 -0800983</div>
Ted Osborne505ba682018-01-30 12:36:50 -0500984
Victor Costan6dfd9d92018-02-05 18:30:35 -0800985<h4>Common patterns</h4>
Ted Osborne505ba682018-01-30 12:36:50 -0500986
Victor Costan6dfd9d92018-02-05 18:30:35 -0800987<ul>
988 <li>Global strings: if you require a global or static string constant,
989 consider using a simple character array, or a char pointer to the first
990 element of a string literal. String literals have static storage duration
991 already and are usually sufficient.</li>
992 <li>Maps, sets, and other dynamic containers: if you require a static, fixed
993 collection, such as a set to search against or a lookup table, you cannot
994 use the dynamic containers from the standard library as a static variable,
995 since they have non-trivial destructors. Instead, consider a simple array of
996 trivial types, e.g. an array of arrays of ints (for a "map from int to
997 int"), or an array of pairs (e.g. pairs of <code>int</code> and <code>const
998 char*</code>). For small collections, linear search is entirely sufficient
999 (and efficient, due to memory locality). If necessary, keep the collection in
1000 sorted order and use a binary search algorithm. If you do really prefer a
1001 dynamic container from the standard library, consider using a function-local
1002 static pointer, as described below.</li>
1003 <li>Smart pointers (<code>unique_ptr</code>, <code>shared_ptr</code>): smart
1004 pointers execute cleanup during destruction and are therefore forbidden.
1005 Consider whether your use case fits into one of the other patterns described
1006 in this section. One simple solution is to use a plain pointer to a
1007 dynamically allocated object and never delete it (see last item).</li>
1008 <li>Static variables of custom types: if you require static, constant data of
1009 a type that you need to define yourself, give the type a trivial destructor
1010 and a <code>constexpr</code> constructor.</li>
1011 <li>If all else fails, you can create an object dynamically and never delete
1012 it by binding the pointer to a function-local static pointer variable:
1013 <code>static const auto* const impl = new T(args...);</code> (If the
1014 initialization is more complex, it can be moved into a function or lambda
1015 expression.)</li>
1016</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05001017
1018</div>
1019
Victor Costan6dfd9d92018-02-05 18:30:35 -08001020<h3 id="thread_local">thread_local Variables</h3>
1021
1022<div class="summary">
1023<p><code>thread_local</code> variables that aren't declared inside a function
1024must be initialized with a true compile-time constant. Prefer
1025<code>thread_local</code> over other ways of defining thread-local data.</p>
1026</div>
1027
1028<div class="stylebody">
1029
1030<div class="definition">
1031<p>Starting with C++11, variables can be declared with the
1032<code>thread_local</code> specifier:</p>
1033<pre>thread_local Foo foo = ...;
1034</pre>
1035<p>Such a variable is actually a collection of objects, so that when different
1036threads access it, they are actually accessing different objects.
1037<code>thread_local</code> variables are much like
1038<a href="#Static_and_Global_Variables">static storage duration variables</a>
1039in many respects. For instance, they can be declared at namespace scope,
1040inside functions, or as static class members, but not as ordinary class
1041members.</p>
1042
1043<p><code>thread_local</code> variable instances are initialized much like
1044static variables, except that they must be initialized separately for each
1045thread, rather than once at program startup. This means that
1046<code>thread_local</code> variables declared within a function are safe, but
1047other <code>thread_local</code> variables are subject to the same
1048initialization-order issues as static variables (and more besides).</p>
1049
1050<p><code>thread_local</code> variable instances are destroyed when their thread
1051terminates, so they do not have the destruction-order issues of static
1052variables.</p>
1053</div>
1054
1055<div class="pros">
1056<ul>
1057 <li>Thread-local data is inherently safe from races (because only one thread
1058 can ordinarily access it), which makes <code>thread_local</code> useful for
1059 concurrent programming.</li>
1060 <li><code>thread_local</code> is the only standard-supported way of creating
1061 thread-local data.</li>
1062</ul>
1063</div>
1064
1065<div class="cons">
1066<ul>
1067 <li>Accessing a <code>thread_local</code> variable may trigger execution of
1068 an unpredictable and uncontrollable amount of other code.</li>
1069 <li><code>thread_local</code> variables are effectively global variables,
1070 and have all the drawbacks of global variables other than lack of
1071 thread-safety.</li>
1072 <li>The memory consumed by a <code>thread_local</code> variable scales with
1073 the number of running threads (in the worst case), which can be quite large
1074 in a program.</li>
1075 <li>An ordinary class member cannot be <code>thread_local</code>.</li>
1076 <li><code>thread_local</code> may not be as efficient as certain compiler
1077 intrinsics.</li>
1078</ul>
1079</div>
1080
1081<div class="decision">
1082 <p><code>thread_local</code> variables inside a function have no safety
1083 concerns, so they can be used without restriction. Note that you can use
1084 a function-scope <code>thread_local</code> to simulate a class- or
1085 namespace-scope <code>thread_local</code> by defining a function or
1086 static method that exposes it:</p>
1087
1088<pre>Foo&amp; MyThreadLocalFoo() {
1089 thread_local Foo result = ComplicatedInitialization();
1090 return result;
1091}
1092</pre>
1093
1094 <p><code>thread_local</code> variables at class or namespace scope must be
1095 initialized with a true compile-time constant (i.e. they must have no
1096 dynamic initialization). </p>
1097
1098
1099
1100 <p><code>thread_local</code> should be preferred over other mechanisms for
1101 defining thread-local data.</p>
1102</div>
1103
1104</div>
1105
1106
Ted Osborne505ba682018-01-30 12:36:50 -05001107<h2 id="Classes">Classes</h2>
1108
1109<p>Classes are the fundamental unit of code in C++. Naturally,
1110we use them extensively. This section lists the main dos and
1111don'ts you should follow when writing a class.</p>
1112
1113<h3 id="Doing_Work_in_Constructors">Doing Work in Constructors</h3>
1114
1115<div class="summary">
1116<p>Avoid virtual method calls in constructors, and avoid
1117initialization that can fail if you can't signal an error.</p>
1118</div>
1119
1120<div class="stylebody">
1121
1122<div class="definition">
1123<p>It is possible to perform arbitrary initialization in the body
1124of the constructor.</p>
1125</div>
1126
1127<div class="pros">
1128<ul>
1129 <li>No need to worry about whether the class has been initialized or
1130 not.</li>
1131
1132 <li>Objects that are fully initialized by constructor call can
1133 be <code>const</code> and may also be easier to use with standard containers
1134 or algorithms.</li>
1135</ul>
1136
1137</div>
1138
1139<div class="cons">
1140<ul>
1141 <li>If the work calls virtual functions, these calls
1142 will not get dispatched to the subclass
1143 implementations. Future modification to your class can
1144 quietly introduce this problem even if your class is
1145 not currently subclassed, causing much confusion.</li>
1146
1147 <li>There is no easy way for constructors to signal errors, short of
1148 crashing the program (not always appropriate) or using exceptions
1149 (which are <a href="#Exceptions">forbidden</a>).</li>
1150
1151 <li>If the work fails, we now have an object whose initialization
1152 code failed, so it may be an unusual state requiring a <code>bool
1153 IsValid()</code> state checking mechanism (or similar) which is easy
1154 to forget to call.</li>
1155
1156 <li>You cannot take the address of a constructor, so whatever work
1157 is done in the constructor cannot easily be handed off to, for
1158 example, another thread.</li>
1159</ul>
1160</div>
1161
1162
1163<div class="decision">
1164<p>Constructors should never call virtual functions. If appropriate
1165for your code
1166,
1167terminating the program may be an appropriate error handling
1168response. Otherwise, consider a factory function
1169or <code>Init()</code> method. Avoid <code>Init()</code> methods on objects with
1170no other states that affect which public methods may be called
1171(semi-constructed objects of this form are particularly hard to work
1172with correctly).</p>
1173</div>
1174
1175</div>
1176
1177<a id="Explicit_Constructors"></a>
1178<h3 id="Implicit_Conversions">Implicit Conversions</h3>
1179
1180<div class="summary">
1181<p>Do not define implicit conversions. Use the <code>explicit</code>
1182keyword for conversion operators and single-argument
1183constructors.</p>
1184</div>
1185
1186<div class="stylebody">
1187
1188<div class="definition">
1189<p>Implicit conversions allow an
1190object of one type (called the <dfn>source type</dfn>) to
1191be used where a different type (called the <dfn>destination
1192type</dfn>) is expected, such as when passing an
1193<code>int</code> argument to a function that takes a
1194<code>double</code> parameter.</p>
1195
1196<p>In addition to the implicit conversions defined by the language,
1197users can define their own, by adding appropriate members to the
1198class definition of the source or destination type. An implicit
1199conversion in the source type is defined by a type conversion operator
1200named after the destination type (e.g. <code>operator
1201bool()</code>). An implicit conversion in the destination
1202type is defined by a constructor that can take the source type as
1203its only argument (or only argument with no default value).</p>
1204
1205<p>The <code>explicit</code> keyword can be applied to a constructor
1206or (since C++11) a conversion operator, to ensure that it can only be
1207used when the destination type is explicit at the point of use,
1208e.g. with a cast. This applies not only to implicit conversions, but to
1209C++11's list initialization syntax:</p>
1210<pre>class Foo {
1211 explicit Foo(int x, double y);
1212 ...
1213};
1214
1215void Func(Foo f);
1216</pre>
1217<pre class="badcode">Func({42, 3.14}); // Error
1218</pre>
1219This kind of code isn't technically an implicit conversion, but the
1220language treats it as one as far as <code>explicit</code> is concerned.
1221</div>
1222
1223<div class="pros">
1224<ul>
1225<li>Implicit conversions can make a type more usable and
1226 expressive by eliminating the need to explicitly name a type
1227 when it's obvious.</li>
1228<li>Implicit conversions can be a simpler alternative to
1229 overloading.</li>
1230<li>List initialization syntax is a concise and expressive
1231 way of initializing objects.</li>
1232</ul>
1233</div>
1234
1235<div class="cons">
1236<ul>
1237<li>Implicit conversions can hide type-mismatch bugs, where the
1238 destination type does not match the user's expectation, or
1239 the user is unaware that any conversion will take place.</li>
1240
1241<li>Implicit conversions can make code harder to read, particularly
1242 in the presence of overloading, by making it less obvious what
1243 code is actually getting called.</li>
1244
1245<li>Constructors that take a single argument may accidentally
1246 be usable as implicit type conversions, even if they are not
1247 intended to do so.</li>
1248
1249<li>When a single-argument constructor is not marked
1250 <code>explicit</code>, there's no reliable way to tell whether
1251 it's intended to define an implicit conversion, or the author
1252 simply forgot to mark it.</li>
1253
1254<li>It's not always clear which type should provide the conversion,
1255 and if they both do, the code becomes ambiguous.</li>
1256
1257<li>List initialization can suffer from the same problems if
1258 the destination type is implicit, particularly if the
1259 list has only a single element.</li>
1260</ul>
1261</div>
1262
1263<div class="decision">
1264<p>Type conversion operators, and constructors that are
1265callable with a single argument, must be marked
1266<code>explicit</code> in the class definition. As an
1267exception, copy and move constructors should not be
1268<code>explicit</code>, since they do not perform type
1269conversion. Implicit conversions can sometimes be necessary and
1270appropriate for types that are designed to transparently wrap other
1271types. In that case, contact
1272your project leads to request
1273a waiver of this rule.</p>
1274
1275<p>Constructors that cannot be called with a single argument
Victor Costan6dfd9d92018-02-05 18:30:35 -08001276may omit <code>explicit</code>. Constructors that
Ted Osborne505ba682018-01-30 12:36:50 -05001277take a single <code>std::initializer_list</code> parameter should
1278also omit <code>explicit</code>, in order to support copy-initialization
1279(e.g. <code>MyType m = {1, 2};</code>).</p>
1280</div>
1281
1282</div>
1283
1284<h3 id="Copyable_Movable_Types">Copyable and Movable Types</h3>
1285<a id="Copy_Constructors"></a>
1286<div class="summary">
Victor Costan6dfd9d92018-02-05 18:30:35 -08001287<p>A class's public API should make explicit whether the class is copyable,
1288move-only, or neither copyable nor movable. Support copying and/or
1289moving if these operations are clear and meaningful for your type.</p>
1290</div>
Ted Osborne505ba682018-01-30 12:36:50 -05001291
1292<div class="stylebody">
1293
1294<div class="definition">
Ted Osborne505ba682018-01-30 12:36:50 -05001295<p>A movable type is one that can be initialized and assigned
Victor Costan6dfd9d92018-02-05 18:30:35 -08001296from temporaries.</p>
1297
1298<p>A copyable type is one that can be initialized or assigned from
1299any other object of the same type (so is also movable by definition), with the
1300stipulation that the value of the source does not change.
Ted Osborne505ba682018-01-30 12:36:50 -05001301<code>std::unique_ptr&lt;int&gt;</code> is an example of a movable but not
Victor Costan6dfd9d92018-02-05 18:30:35 -08001302copyable type (since the value of the source
1303<code>std::unique_ptr&lt;int&gt;</code> must be modified during assignment to
1304the destination). <code>int</code> and <code>string</code> are examples of
1305movable types that are also copyable. (For <code>int</code>, the move and copy
1306operations are the same; for <code>string</code>, there exists a move operation
1307that is less expensive than a copy.)</p>
1308
1309<p>For user-defined types, the copy behavior is defined by the copy
1310constructor and the copy-assignment operator. Move behavior is defined by the
1311move constructor and the move-assignment operator, if they exist, or by the
1312copy constructor and the copy-assignment operator otherwise.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001313
1314<p>The copy/move constructors can be implicitly invoked by the compiler
1315in some situations, e.g. when passing objects by value.</p>
1316</div>
1317
1318<div class="pros">
1319<p>Objects of copyable and movable types can be passed and returned by value,
1320which makes APIs simpler, safer, and more general. Unlike when passing objects
1321by pointer or reference, there's no risk of confusion over ownership,
1322lifetime, mutability, and similar issues, and no need to specify them in the
1323contract. It also prevents non-local interactions between the client and the
1324implementation, which makes them easier to understand, maintain, and optimize by
1325the compiler. Further, such objects can be used with generic APIs that
1326require pass-by-value, such as most containers, and they allow for additional
1327flexibility in e.g., type composition.</p>
1328
1329<p>Copy/move constructors and assignment operators are usually
1330easier to define correctly than alternatives
1331like <code>Clone()</code>, <code>CopyFrom()</code> or <code>Swap()</code>,
1332because they can be generated by the compiler, either implicitly or
1333with <code>= default</code>. They are concise, and ensure
1334that all data members are copied. Copy and move
1335constructors are also generally more efficient, because they don't
1336require heap allocation or separate initialization and assignment
1337steps, and they're eligible for optimizations such as
1338
1339<a href="http://en.cppreference.com/w/cpp/language/copy_elision">
1340copy elision</a>.</p>
1341
1342<p>Move operations allow the implicit and efficient transfer of
1343resources out of rvalue objects. This allows a plainer coding style
1344in some cases.</p>
1345</div>
1346
1347<div class="cons">
1348<p>Some types do not need to be copyable, and providing copy
1349operations for such types can be confusing, nonsensical, or outright
1350incorrect. Types representing singleton objects (<code>Registerer</code>),
1351objects tied to a specific scope (<code>Cleanup</code>), or closely coupled to
1352object identity (<code>Mutex</code>) cannot be copied meaningfully.
1353Copy operations for base class types that are to be used
1354polymorphically are hazardous, because use of them can lead to
1355<a href="https://en.wikipedia.org/wiki/Object_slicing">object slicing</a>.
1356Defaulted or carelessly-implemented copy operations can be incorrect, and the
1357resulting bugs can be confusing and difficult to diagnose.</p>
1358
1359<p>Copy constructors are invoked implicitly, which makes the
1360invocation easy to miss. This may cause confusion for programmers used to
1361languages where pass-by-reference is conventional or mandatory. It may also
1362encourage excessive copying, which can cause performance problems.</p>
1363</div>
1364
1365<div class="decision">
1366
Victor Costan6dfd9d92018-02-05 18:30:35 -08001367<p>Every class's public interface should make explicit which copy and move
1368operations the class supports. This should usually take the form of explicitly
1369declaring and/or deleting the appropriate operations in the <code>public</code>
1370section of the declaration.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001371
Victor Costan6dfd9d92018-02-05 18:30:35 -08001372<p>Specifically, a copyable class should explicitly declare the copy
1373operations, a move-only class should explicitly declare the move operations,
1374and a non-copyable/movable class should explicitly delete the copy operations.
1375Explicitly declaring or deleting all four copy/move operations is permitted,
1376but not required. If you provide a copy or move assignment operator, you
1377must also provide the corresponding constructor.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001378
Victor Costan6dfd9d92018-02-05 18:30:35 -08001379<pre>class Copyable {
Ted Osborne505ba682018-01-30 12:36:50 -05001380 public:
Victor Costan6dfd9d92018-02-05 18:30:35 -08001381 Copyable(const Copyable&amp; rhs) = default;
1382 Copyable&amp; operator=(const Copyable&amp; rhs) = default;
Ted Osborne505ba682018-01-30 12:36:50 -05001383
Victor Costan6dfd9d92018-02-05 18:30:35 -08001384 // The implicit move operations are suppressed by the declarations above.
1385};
1386
1387class MoveOnly {
1388 public:
1389 MoveOnly(MoveOnly&amp;&amp; rhs);
1390 MoveOnly&amp; operator=(MoveOnly&amp;&amp; rhs);
1391
1392 // The copy operations are implicitly deleted, but you can
1393 // spell that out explicitly if you want:
1394 MoveOnly(const MoveOnly&amp;) = delete;
1395 MoveOnly&amp; operator=(const MoveOnly&amp;) = delete;
1396};
1397
1398class NotCopyableOrMovable {
1399 public:
1400 // Not copyable or movable
1401 NotCopyableOrMovable(const NotCopyableOrMovable&amp;) = delete;
1402 NotCopyableOrMovable&amp; operator=(const NotCopyableOrMovable&amp;)
1403 = delete;
1404
1405 // The move operations are implicitly disabled, but you can
1406 // spell that out explicitly if you want:
1407 NotCopyableOrMovable(NotCopyableOrMovable&amp;&amp;) = delete;
1408 NotCopyableOrMovable&amp; operator=(NotCopyableOrMovable&amp;&amp;)
1409 = delete;
Ted Osborne505ba682018-01-30 12:36:50 -05001410};
1411</pre>
1412
Victor Costan6dfd9d92018-02-05 18:30:35 -08001413<p>These declarations/deletions can be omitted only if they are obvious: for
1414example, if a base class isn't copyable or movable, derived classes naturally
1415won't be either. Similarly, a <a href="#Structs_vs._Classes">struct</a>'s
1416copyability/movability is normally determined by the copyability/movability
1417of its data members (this does not apply to classes because in Google code
1418their data members are not public). Note that if you explicitly declare or
1419delete any of the copy/move operations, the others are not obvious, and so
1420this paragraph does not apply (in particular, the rules in this section
1421that apply to "classes" also apply to structs that declare or delete any
1422copy/move operations).</p>
1423
1424<p>A type should not be copyable/movable if the meaning of
1425copying/moving is unclear to a casual user, or if it incurs unexpected
1426costs. Move operations for copyable types are strictly a performance
1427optimization and are a potential source of bugs and complexity, so
1428avoid defining them unless they are significantly more efficient than
1429the corresponding copy operations. If your type provides copy operations, it is
1430recommended that you design your class so that the default implementation of
1431those operations is correct. Remember to review the correctness of any
1432defaulted operations as you would any other code.</p>
1433
1434<p>Due to the risk of slicing, prefer to avoid providing a public assignment
1435operator or copy/move constructor for a class that's
1436intended to be derived from (and prefer to avoid deriving from a class
Ted Osborne505ba682018-01-30 12:36:50 -05001437with such members). If your base class needs to be
1438copyable, provide a public virtual <code>Clone()</code>
1439method, and a protected copy constructor that derived classes
1440can use to implement it.</p>
1441
Ted Osborne505ba682018-01-30 12:36:50 -05001442
Ted Osborne505ba682018-01-30 12:36:50 -05001443
1444</div>
1445</div>
1446
1447<h3 id="Structs_vs._Classes">Structs vs. Classes</h3>
1448
1449<div class="summary">
1450<p>Use a <code>struct</code> only for passive objects that
1451 carry data; everything else is a <code>class</code>.</p>
1452</div>
1453
1454<div class="stylebody">
1455
1456<p>The <code>struct</code> and <code>class</code>
1457keywords behave almost identically in C++. We add our own
1458semantic meanings to each keyword, so you should use the
1459appropriate keyword for the data-type you're
1460defining.</p>
1461
1462<p><code>structs</code> should be used for passive
1463objects that carry data, and may have associated
1464constants, but lack any functionality other than
1465access/setting the data members. The accessing/setting of
1466fields is done by directly accessing the fields rather
1467than through method invocations. Methods should not
1468provide behavior but should only be used to set up the
1469data members, e.g., constructor, destructor,
1470<code>Initialize()</code>, <code>Reset()</code>,
1471<code>Validate()</code>.</p>
1472
1473<p>If more functionality is required, a
1474<code>class</code> is more appropriate. If in doubt, make
1475it a <code>class</code>.</p>
1476
1477<p>For consistency with STL, you can use
1478<code>struct</code> instead of <code>class</code> for
1479functors and traits.</p>
1480
1481<p>Note that member variables in structs and classes have
1482<a href="#Variable_Names">different naming rules</a>.</p>
1483
1484</div>
1485
1486<h3 id="Inheritance">Inheritance</h3>
1487
1488<div class="summary">
1489<p>Composition is often more appropriate than inheritance.
1490When using inheritance, make it <code>public</code>.</p>
1491</div>
1492
1493<div class="stylebody">
1494
1495<div class="definition">
1496<p> When a sub-class
1497inherits from a base class, it includes the definitions
1498of all the data and operations that the parent base class
1499defines. In practice, inheritance is used in two major
1500ways in C++: implementation inheritance, in which actual
1501code is inherited by the child, and
1502<a href="#Interfaces">interface inheritance</a>, in which
1503only method names are inherited.</p>
1504</div>
1505
1506<div class="pros">
1507<p>Implementation inheritance reduces code size by re-using
1508the base class code as it specializes an existing type.
1509Because inheritance is a compile-time declaration, you
1510and the compiler can understand the operation and detect
1511errors. Interface inheritance can be used to
1512programmatically enforce that a class expose a particular
1513API. Again, the compiler can detect errors, in this case,
1514when a class does not define a necessary method of the
1515API.</p>
1516</div>
1517
1518<div class="cons">
1519<p>For implementation inheritance, because the code
1520implementing a sub-class is spread between the base and
1521the sub-class, it can be more difficult to understand an
1522implementation. The sub-class cannot override functions
1523that are not virtual, so the sub-class cannot change
Victor Costan6dfd9d92018-02-05 18:30:35 -08001524implementation.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001525</div>
1526
1527<div class="decision">
1528
1529<p>All inheritance should be <code>public</code>. If you
1530want to do private inheritance, you should be including
1531an instance of the base class as a member instead.</p>
1532
1533<p>Do not overuse implementation inheritance. Composition
1534is often more appropriate. Try to restrict use of
1535inheritance to the "is-a" case: <code>Bar</code>
1536subclasses <code>Foo</code> if it can reasonably be said
1537that <code>Bar</code> "is a kind of"
1538<code>Foo</code>.</p>
1539
Ted Osborne505ba682018-01-30 12:36:50 -05001540<p>Limit the use of <code>protected</code> to those
1541member functions that might need to be accessed from
1542subclasses. Note that <a href="#Access_Control">data
1543members should be private</a>.</p>
1544
Victor Costan6dfd9d92018-02-05 18:30:35 -08001545<p>Explicitly annotate overrides of virtual functions or virtual
1546destructors with exactly one of an <code>override</code> or (less
1547frequently) <code>final</code> specifier. Do not
1548use <code>virtual</code> when declaring an override.
Ted Osborne505ba682018-01-30 12:36:50 -05001549Rationale: A function or destructor marked
1550<code>override</code> or <code>final</code> that is
1551not an override of a base class virtual function will
1552not compile, and this helps catch common errors. The
1553specifiers serve as documentation; if no specifier is
1554present, the reader has to check all ancestors of the
1555class in question to determine if the function or
1556destructor is virtual or not.</p>
1557</div>
1558
1559</div>
1560
1561<h3 id="Multiple_Inheritance">Multiple Inheritance</h3>
1562
1563<div class="summary">
1564<p>Only very rarely is multiple implementation inheritance
1565actually useful. We allow multiple inheritance only when at
1566most one of the base classes has an implementation; all
1567other base classes must be <a href="#Interfaces">pure
1568interface</a> classes tagged with the
1569<code>Interface</code> suffix.</p>
1570</div>
1571
1572<div class="stylebody">
1573
1574<div class="definition">
1575<p>Multiple inheritance allows a sub-class to have more than
1576one base class. We distinguish between base classes that are
1577<em>pure interfaces</em> and those that have an
1578<em>implementation</em>.</p>
1579</div>
1580
1581<div class="pros">
1582<p>Multiple implementation inheritance may let you re-use
1583even more code than single inheritance (see <a href="#Inheritance">Inheritance</a>).</p>
1584</div>
1585
1586<div class="cons">
1587<p>Only very rarely is multiple <em>implementation</em>
1588inheritance actually useful. When multiple implementation
1589inheritance seems like the solution, you can usually find
1590a different, more explicit, and cleaner solution.</p>
1591</div>
1592
1593<div class="decision">
1594<p> Multiple inheritance is allowed only when all
1595superclasses, with the possible exception of the first one,
1596are <a href="#Interfaces">pure interfaces</a>. In order to
1597ensure that they remain pure interfaces, they must end with
1598the <code>Interface</code> suffix.</p>
1599</div>
1600
1601<div class="note">
1602<p>There is an <a href="#Windows_Code">exception</a> to
1603this rule on Windows.</p>
1604</div>
1605
1606</div>
1607
1608<h3 id="Interfaces">Interfaces</h3>
1609
1610<div class="summary">
1611<p>Classes that satisfy certain conditions are allowed, but
1612not required, to end with an <code>Interface</code> suffix.</p>
1613</div>
1614
1615<div class="stylebody">
1616
1617<div class="definition">
1618<p>A class is a pure interface if it meets the following
1619requirements:</p>
1620
1621<ul>
1622 <li>It has only public pure virtual ("<code>=
1623 0</code>") methods and static methods (but see below
1624 for destructor).</li>
1625
1626 <li>It may not have non-static data members.</li>
1627
1628 <li>It need not have any constructors defined. If a
1629 constructor is provided, it must take no arguments and
1630 it must be protected.</li>
1631
1632 <li>If it is a subclass, it may only be derived from
1633 classes that satisfy these conditions and are tagged
1634 with the <code>Interface</code> suffix.</li>
1635</ul>
1636
1637<p>An interface class can never be directly instantiated
1638because of the pure virtual method(s) it declares. To
1639make sure all implementations of the interface can be
1640destroyed correctly, the interface must also declare a
1641virtual destructor (in an exception to the first rule,
1642this should not be pure). See Stroustrup, <cite>The C++
1643Programming Language</cite>, 3rd edition, section 12.4
1644for details.</p>
1645</div>
1646
1647<div class="pros">
1648<p>Tagging a class with the <code>Interface</code> suffix
1649lets others know that they must not add implemented
1650methods or non static data members. This is particularly
1651important in the case of <a href="#Multiple_Inheritance">multiple inheritance</a>.
1652Additionally, the interface concept is already
1653well-understood by Java programmers.</p>
1654</div>
1655
1656<div class="cons">
1657<p>The <code>Interface</code> suffix lengthens the class
1658name, which can make it harder to read and understand.
1659Also, the interface property may be considered an
1660implementation detail that shouldn't be exposed to
1661clients.</p>
1662</div>
1663
1664<div class="decision">
1665<p>A class may end
1666with <code>Interface</code> only if it meets the above
1667requirements. We do not require the converse, however:
1668classes that meet the above requirements are not required
1669to end with <code>Interface</code>.</p>
1670</div>
1671
1672</div>
1673
1674<h3 id="Operator_Overloading">Operator Overloading</h3>
1675
1676<div class="summary">
1677<p>Overload operators judiciously. Do not create user-defined literals.</p>
1678</div>
1679
1680<div class="stylebody">
1681
1682<div class="definition">
1683<p>C++ permits user code to
1684<a href="http://en.cppreference.com/w/cpp/language/operators">declare
1685overloaded versions of the built-in operators</a> using the
1686<code>operator</code> keyword, so long as one of the parameters
1687is a user-defined type. The <code>operator</code> keyword also
1688permits user code to define new kinds of literals using
1689<code>operator""</code>, and to define type-conversion functions
1690such as <code>operator bool()</code>.</p>
1691</div>
1692
1693<div class="pros">
1694<p>Operator overloading can make code more concise and
1695intuitive by enabling user-defined types to behave the same
1696as built-in types. Overloaded operators are the idiomatic names
1697for certain operations (e.g. <code>==</code>, <code>&lt;</code>,
1698<code>=</code>, and <code>&lt;&lt;</code>), and adhering to
1699those conventions can make user-defined types more readable
1700and enable them to interoperate with libraries that expect
1701those names.</p>
1702
1703<p>User-defined literals are a very concise notation for
1704creating objects of user-defined types.</p>
1705</div>
1706
1707<div class="cons">
1708<ul>
1709 <li>Providing a correct, consistent, and unsurprising
1710 set of operator overloads requires some care, and failure
1711 to do so can lead to confusion and bugs.</li>
1712
1713 <li>Overuse of operators can lead to obfuscated code,
1714 particularly if the overloaded operator's semantics
1715 don't follow convention.</li>
1716
1717 <li>The hazards of function overloading apply just as
1718 much to operator overloading, if not more so.</li>
1719
1720 <li>Operator overloads can fool our intuition into
1721 thinking that expensive operations are cheap, built-in
1722 operations.</li>
1723
1724 <li>Finding the call sites for overloaded operators may
1725 require a search tool that's aware of C++ syntax, rather
1726 than e.g. grep.</li>
1727
1728 <li>If you get the argument type of an overloaded operator
1729 wrong, you may get a different overload rather than a
1730 compiler error. For example, <code>foo &lt; bar</code>
1731 may do one thing, while <code>&amp;foo &lt; &amp;bar</code>
1732 does something totally different.</li>
1733
1734 <li>Certain operator overloads are inherently hazardous.
1735 Overloading unary <code>&amp;</code> can cause the same
1736 code to have different meanings depending on whether
1737 the overload declaration is visible. Overloads of
1738 <code>&amp;&amp;</code>, <code>||</code>, and <code>,</code>
1739 (comma) cannot match the evaluation-order semantics of the
1740 built-in operators.</li>
1741
1742 <li>Operators are often defined outside the class,
1743 so there's a risk of different files introducing
1744 different definitions of the same operator. If both
1745 definitions are linked into the same binary, this results
1746 in undefined behavior, which can manifest as subtle
1747 run-time bugs.</li>
1748
1749 <li>User-defined literals allow the creation of new
1750 syntactic forms that are unfamiliar even to experienced C++
1751 programmers.</li>
1752</ul>
1753</div>
1754
1755<div class="decision">
1756<p>Define overloaded operators only if their meaning is
1757obvious, unsurprising, and consistent with the corresponding
1758built-in operators. For example, use <code>|</code> as a
1759bitwise- or logical-or, not as a shell-style pipe.</p>
1760
1761<p>Define operators only on your own types. More precisely,
1762define them in the same headers, .cc files, and namespaces
1763as the types they operate on. That way, the operators are available
1764wherever the type is, minimizing the risk of multiple
1765definitions. If possible, avoid defining operators as templates,
1766because they must satisfy this rule for any possible template
1767arguments. If you define an operator, also define
1768any related operators that make sense, and make sure they
1769are defined consistently. For example, if you overload
1770<code>&lt;</code>, overload all the comparison operators,
1771and make sure <code>&lt;</code> and <code>&gt;</code> never
1772return true for the same arguments.</p>
1773
1774<p>Prefer to define non-modifying binary operators as
1775non-member functions. If a binary operator is defined as a
1776class member, implicit conversions will apply to the
1777right-hand argument, but not the left-hand one. It will
1778confuse your users if <code>a &lt; b</code> compiles but
1779<code>b &lt; a</code> doesn't.</p>
1780
1781<p>Don't go out of your way to avoid defining operator
1782overloads. For example, prefer to define <code>==</code>,
1783<code>=</code>, and <code>&lt;&lt;</code>, rather than
1784<code>Equals()</code>, <code>CopyFrom()</code>, and
1785<code>PrintTo()</code>. Conversely, don't define
1786operator overloads just because other libraries expect
1787them. For example, if your type doesn't have a natural
1788ordering, but you want to store it in a <code>std::set</code>,
1789use a custom comparator rather than overloading
1790<code>&lt;</code>.</p>
1791
1792<p>Do not overload <code>&amp;&amp;</code>, <code>||</code>,
1793<code>,</code> (comma), or unary <code>&amp;</code>. Do not overload
1794<code>operator""</code>, i.e. do not introduce user-defined
1795literals.</p>
1796
1797<p>Type conversion operators are covered in the section on
1798<a href="#Implicit_Conversions">implicit conversions</a>.
1799The <code>=</code> operator is covered in the section on
1800<a href="#Copy_Constructors">copy constructors</a>. Overloading
1801<code>&lt;&lt;</code> for use with streams is covered in the
1802section on <a href="#Streams">streams</a>. See also the rules on
1803<a href="#Function_Overloading">function overloading</a>, which
1804apply to operator overloading as well.</p>
1805</div>
1806
1807</div>
1808
1809<h3 id="Access_Control">Access Control</h3>
1810
1811<div class="summary">
1812<p> Make data members <code>private</code>, unless they are
1813<code>static const</code> (and follow the <a href="#Constant_Names">
Victor Costan6dfd9d92018-02-05 18:30:35 -08001814naming convention for constants</a>).</p>
1815</div>
1816
1817<div class="stylebody">
1818
1819<p>For technical
Ted Osborne505ba682018-01-30 12:36:50 -05001820reasons, we allow data members of a test fixture class to
1821be <code>protected</code> when using
1822
1823
1824<a href="https://github.com/google/googletest">Google
1825Test</a>).</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001826
1827</div>
Ted Osborne505ba682018-01-30 12:36:50 -05001828
1829<h3 id="Declaration_Order">Declaration Order</h3>
1830
1831<div class="summary">
1832<p>Group similar declarations together, placing public parts
1833earlier.</p>
1834</div>
1835
1836<div class="stylebody">
1837
1838<p>A class definition should usually start with a
1839<code>public:</code> section, followed by
1840<code>protected:</code>, then <code>private:</code>. Omit
1841sections that would be empty.</p>
1842
1843<p>Within each section, generally prefer grouping similar
1844kinds of declarations together, and generally prefer the
1845following order: types (including <code>typedef</code>,
1846<code>using</code>, and nested structs and classes),
1847constants, factory functions, constructors, assignment
1848operators, destructor, all other methods, data members.</p>
1849
1850<p>Do not put large method definitions inline in the
1851class definition. Usually, only trivial or
1852performance-critical, and very short, methods may be
1853defined inline. See <a href="#Inline_Functions">Inline
1854Functions</a> for more details.</p>
1855
1856</div>
1857
1858<h2 id="Functions">Functions</h2>
1859
Victor Costan6dfd9d92018-02-05 18:30:35 -08001860<a id="Function_Parameter_Ordering"></a>
1861<h3 id="Output_Parameters">Output Parameters</h3>
Ted Osborne505ba682018-01-30 12:36:50 -05001862
1863<div class="summary">
Victor Costan6dfd9d92018-02-05 18:30:35 -08001864<p>Prefer using return values rather than output parameters.
1865If output-only parameters are used they should appear after
1866input parameters.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001867</div>
1868
1869<div class="stylebody">
Victor Costan6dfd9d92018-02-05 18:30:35 -08001870<p>The output of a C++ function is naturally provided via
1871a return value and sometimes via output parameters.</p>
1872
1873<p>Prefer using return values instead of output parameters
1874since they improve readability and oftentimes provide the same
1875or better performance.</p>
1876
1877<p>Parameters are either input to the function, output from the
1878function, or both. Input parameters are usually values or
1879<code>const</code> references, while output and input/output
1880parameters will be pointers to non-<code>const</code>.</p>
1881
1882<p>When ordering function parameters, put all input-only
1883parameters before any output parameters. In particular,
1884do not add new parameters to the end of the function just
1885because they are new; place new input-only parameters before
1886the output parameters.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001887
1888<p>This is not a hard-and-fast rule. Parameters that are
1889both input and output (often classes/structs) muddy the
1890waters, and, as always, consistency with related
1891functions may require you to bend the rule.</p>
1892
1893</div>
1894
1895<h3 id="Write_Short_Functions">Write Short Functions</h3>
1896
1897<div class="summary">
1898<p>Prefer small and focused functions.</p>
1899</div>
1900
1901<div class="stylebody">
1902<p>We recognize that long functions are sometimes
1903appropriate, so no hard limit is placed on functions
1904length. If a function exceeds about 40 lines, think about
1905whether it can be broken up without harming the structure
1906of the program.</p>
1907
1908<p>Even if your long function works perfectly now,
1909someone modifying it in a few months may add new
1910behavior. This could result in bugs that are hard to
1911find. Keeping your functions short and simple makes it
1912easier for other people to read and modify your code.</p>
1913
1914<p>You could find long and complicated functions when
1915working with
1916some code. Do not be
1917intimidated by modifying existing code: if working with
1918such a function proves to be difficult, you find that
1919errors are hard to debug, or you want to use a piece of
1920it in several different contexts, consider breaking up
1921the function into smaller and more manageable pieces.</p>
1922
1923</div>
1924
1925<h3 id="Reference_Arguments">Reference Arguments</h3>
1926
1927<div class="summary">
1928<p>All parameters passed by reference must be labeled
1929<code>const</code>.</p>
1930</div>
1931
1932<div class="stylebody">
1933
1934<div class="definition">
1935<p>In C, if a
1936function needs to modify a variable, the parameter must
1937use a pointer, eg <code>int foo(int *pval)</code>. In
1938C++, the function can alternatively declare a reference
1939parameter: <code>int foo(int &amp;val)</code>.</p>
1940</div>
1941
1942<div class="pros">
1943<p>Defining a parameter as reference avoids ugly code like
1944<code>(*pval)++</code>. Necessary for some applications
1945like copy constructors. Makes it clear, unlike with
1946pointers, that a null pointer is not a possible
1947value.</p>
1948</div>
1949
1950<div class="cons">
1951<p>References can be confusing, as they have value syntax
1952but pointer semantics.</p>
1953</div>
1954
1955<div class="decision">
1956<p>Within function parameter lists all references must be
1957<code>const</code>:</p>
1958
1959<pre>void Foo(const string &amp;in, string *out);
1960</pre>
1961
1962<p>In fact it is a very strong convention in Google code
1963that input arguments are values or <code>const</code>
1964references while output arguments are pointers. Input
1965parameters may be <code>const</code> pointers, but we
1966never allow non-<code>const</code> reference parameters
1967except when required by convention, e.g.,
1968<code>swap()</code>.</p>
1969
1970<p>However, there are some instances where using
1971<code>const T*</code> is preferable to <code>const
1972T&amp;</code> for input parameters. For example:</p>
1973
1974<ul>
1975 <li>You want to pass in a null pointer.</li>
1976
1977 <li>The function saves a pointer or reference to the
1978 input.</li>
1979</ul>
1980
1981<p> Remember that most of the time input
1982parameters are going to be specified as <code>const
1983T&amp;</code>. Using <code>const T*</code> instead
1984communicates to the reader that the input is somehow
1985treated differently. So if you choose <code>const
1986T*</code> rather than <code>const T&amp;</code>, do so
1987for a concrete reason; otherwise it will likely confuse
1988readers by making them look for an explanation that
1989doesn't exist.</p>
1990</div>
1991
1992</div>
1993
1994<h3 id="Function_Overloading">Function Overloading</h3>
1995
1996<div class="summary">
1997<p>Use overloaded functions (including constructors) only if a
1998reader looking at a call site can get a good idea of what
1999is happening without having to first figure out exactly
2000which overload is being called.</p>
2001</div>
2002
2003<div class="stylebody">
2004
2005<div class="definition">
2006<p>You may write a function that takes a <code>const
2007string&amp;</code> and overload it with another that
Victor Costan6dfd9d92018-02-05 18:30:35 -08002008takes <code>const char*</code>. However, in this case consider
2009std::string_view
2010 instead.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002011
2012<pre>class MyClass {
2013 public:
2014 void Analyze(const string &amp;text);
2015 void Analyze(const char *text, size_t textlen);
2016};
2017</pre>
2018</div>
2019
2020<div class="pros">
2021<p>Overloading can make code more intuitive by allowing an
2022identically-named function to take different arguments.
2023It may be necessary for templatized code, and it can be
2024convenient for Visitors.</p>
2025</div>
2026
2027<div class="cons">
2028<p>If a function is overloaded by the argument types alone,
2029a reader may have to understand C++'s complex matching
2030rules in order to tell what's going on. Also many people
2031are confused by the semantics of inheritance if a derived
2032class overrides only some of the variants of a
2033function.</p>
2034</div>
2035
2036<div class="decision">
Victor Costan6dfd9d92018-02-05 18:30:35 -08002037<p>You may overload a function when there are no semantic
2038differences between variants, or when the differences are
2039clear at the callsite.</p>
2040
2041<p>If you are overloading a function to support variable
2042number of arguments of the same type, consider making it
2043take a <code>std::vector</code> so that the user can use an
Ted Osborne505ba682018-01-30 12:36:50 -05002044<a href="#Braced_Initializer_List">initializer list
2045</a> to specify the arguments.</p>
2046</div>
2047
2048</div>
2049
2050<h3 id="Default_Arguments">Default Arguments</h3>
2051
2052<div class="summary">
2053<p>Default arguments are allowed on non-virtual functions
2054when the default is guaranteed to always have the same
2055value. Follow the same restrictions as for <a href="#Function_Overloading">function overloading</a>, and
2056prefer overloaded functions if the readability gained with
2057default arguments doesn't outweigh the downsides below.</p>
2058</div>
2059
2060<div class="stylebody">
2061
2062<div class="pros">
2063<p>Often you have a function that uses default values, but
2064occasionally you want to override the defaults. Default
2065parameters allow an easy way to do this without having to
2066define many functions for the rare exceptions. Compared
2067to overloading the function, default arguments have a
2068cleaner syntax, with less boilerplate and a clearer
2069distinction between 'required' and 'optional'
2070arguments.</p>
2071</div>
2072
2073<div class="cons">
2074<p>Defaulted arguments are another way to achieve the
2075semantics of overloaded functions, so all the <a href="#Function_Overloading">reasons not to overload
2076functions</a> apply.</p>
2077
2078<p>The defaults for arguments in a virtual function call are
2079determined by the static type of the target object, and
2080there's no guarantee that all overrides of a given function
2081declare the same defaults.</p>
2082
2083<p>Default parameters are re-evaluated at each call site,
2084which can bloat the generated code. Readers may also expect
2085the default's value to be fixed at the declaration instead
2086of varying at each call.</p>
2087
2088<p>Function pointers are confusing in the presence of
2089default arguments, since the function signature often
2090doesn't match the call signature. Adding
2091function overloads avoids these problems.</p>
2092</div>
2093
2094<div class="decision">
2095<p>Default arguments are banned on virtual functions, where
2096they don't work properly, and in cases where the specified
2097default might not evaluate to the same value depending on
2098when it was evaluated. (For example, don't write <code>void
2099f(int n = counter++);</code>.)</p>
2100
2101<p>In some other cases, default arguments can improve the
2102readability of their function declarations enough to
2103overcome the downsides above, so they are allowed. When in
2104doubt, use overloads.</p>
2105</div>
2106
2107</div>
2108
2109<h3 id="trailing_return">Trailing Return Type Syntax</h3>
2110<div class="summary">
2111<p>Use trailing return types only where using the ordinary syntax (leading
2112 return types) is impractical or much less readable.</p>
2113</div>
2114
2115<div class="definition">
2116<p>C++ allows two different forms of function declarations. In the older
2117 form, the return type appears before the function name. For example:</p>
2118<pre>int foo(int x);
2119</pre>
2120<p>The new form, introduced in C++11, uses the <code>auto</code>
2121 keyword before the function name and a trailing return type after
2122 the argument list. For example, the declaration above could
2123 equivalently be written:</p>
2124<pre>auto foo(int x) -&gt; int;
2125</pre>
2126<p>The trailing return type is in the function's scope. This doesn't
2127 make a difference for a simple case like <code>int</code> but it matters
2128 for more complicated cases, like types declared in class scope or
2129 types written in terms of the function parameters.</p>
2130</div>
2131
2132<div class="stylebody">
2133<div class="pros">
2134<p>Trailing return types are the only way to explicitly specify the
2135 return type of a <a href="#Lambda_expressions">lambda expression</a>.
2136 In some cases the compiler is able to deduce a lambda's return type,
2137 but not in all cases. Even when the compiler can deduce it automatically,
2138 sometimes specifying it explicitly would be clearer for readers.
2139</p>
2140<p>Sometimes it's easier and more readable to specify a return type
2141 after the function's parameter list has already appeared. This is
2142 particularly true when the return type depends on template parameters.
2143 For example:</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002144 <pre> template &lt;typename T, typename U&gt;
2145 auto add(T t, U u) -&gt; decltype(t + u);
2146 </pre>
Ted Osborne505ba682018-01-30 12:36:50 -05002147 versus
Victor Costan6dfd9d92018-02-05 18:30:35 -08002148 <pre> template &lt;typename T, typename U&gt;
2149 decltype(declval&lt;T&amp;&gt;() + declval&lt;U&amp;&gt;()) add(T t, U u);
2150 </pre>
Ted Osborne505ba682018-01-30 12:36:50 -05002151</div>
2152
2153<div class="cons">
2154<p>Trailing return type syntax is relatively new and it has no
2155 analogue in C++-like languages like C and Java, so some readers may
2156 find it unfamiliar.</p>
2157<p>Existing code bases have an enormous number of function
2158 declarations that aren't going to get changed to use the new syntax,
2159 so the realistic choices are using the old syntax only or using a mixture
2160 of the two. Using a single version is better for uniformity of style.</p>
2161</div>
2162
2163<div class="decision">
2164<p>In most cases, continue to use the older style of function
2165 declaration where the return type goes before the function name.
2166 Use the new trailing-return-type form only in cases where it's
2167 required (such as lambdas) or where, by putting the type after the
2168 function's parameter list, it allows you to write the type in a much
2169 more readable way. The latter case should be rare; it's mostly an
2170 issue in fairly complicated template code, which is
2171 <a href="#Template_metaprogramming">discouraged in most cases</a>.</p>
2172
2173</div>
2174</div>
2175
2176<h2 id="Google-Specific_Magic">Google-Specific Magic</h2>
2177
2178
2179
2180<p>There are various tricks and utilities that
2181we use to make C++ code more robust, and various ways we use
2182C++ that may differ from what you see elsewhere.</p>
2183
2184
2185
2186<h3 id="Ownership_and_Smart_Pointers">Ownership and Smart Pointers</h3>
2187
2188<div class="summary">
2189<p>Prefer to have single, fixed owners for dynamically
2190allocated objects. Prefer to transfer ownership with smart
2191pointers.</p>
2192</div>
2193
2194<div class="stylebody">
2195
2196<div class="definition">
2197<p>"Ownership" is a bookkeeping technique for managing
2198dynamically allocated memory (and other resources). The
2199owner of a dynamically allocated object is an object or
2200function that is responsible for ensuring that it is
2201deleted when no longer needed. Ownership can sometimes be
2202shared, in which case the last owner is typically
2203responsible for deleting it. Even when ownership is not
2204shared, it can be transferred from one piece of code to
2205another.</p>
2206
2207<p>"Smart" pointers are classes that act like pointers,
2208e.g. by overloading the <code>*</code> and
2209<code>-&gt;</code> operators. Some smart pointer types
2210can be used to automate ownership bookkeeping, to ensure
2211these responsibilities are met.
2212<a href="http://en.cppreference.com/w/cpp/memory/unique_ptr">
2213<code>std::unique_ptr</code></a> is a smart pointer type
2214introduced in C++11, which expresses exclusive ownership
2215of a dynamically allocated object; the object is deleted
2216when the <code>std::unique_ptr</code> goes out of scope.
2217It cannot be copied, but can be <em>moved</em> to
2218represent ownership transfer.
2219<a href="http://en.cppreference.com/w/cpp/memory/shared_ptr">
2220<code>std::shared_ptr</code></a> is a smart pointer type
2221that expresses shared ownership of
2222a dynamically allocated object. <code>std::shared_ptr</code>s
2223can be copied; ownership of the object is shared among
2224all copies, and the object is deleted when the last
2225<code>std::shared_ptr</code> is destroyed. </p>
2226</div>
2227
2228<div class="pros">
2229<ul>
2230 <li>It's virtually impossible to manage dynamically
2231 allocated memory without some sort of ownership
2232 logic.</li>
2233
2234 <li>Transferring ownership of an object can be cheaper
2235 than copying it (if copying it is even possible).</li>
2236
2237 <li>Transferring ownership can be simpler than
2238 'borrowing' a pointer or reference, because it reduces
2239 the need to coordinate the lifetime of the object
2240 between the two users.</li>
2241
2242 <li>Smart pointers can improve readability by making
2243 ownership logic explicit, self-documenting, and
2244 unambiguous.</li>
2245
2246 <li>Smart pointers can eliminate manual ownership
2247 bookkeeping, simplifying the code and ruling out large
2248 classes of errors.</li>
2249
2250 <li>For const objects, shared ownership can be a simple
2251 and efficient alternative to deep copying.</li>
2252</ul>
2253</div>
2254
2255<div class="cons">
2256<ul>
2257 <li>Ownership must be represented and transferred via
2258 pointers (whether smart or plain). Pointer semantics
2259 are more complicated than value semantics, especially
2260 in APIs: you have to worry not just about ownership,
2261 but also aliasing, lifetime, and mutability, among
2262 other issues.</li>
2263
2264 <li>The performance costs of value semantics are often
2265 overestimated, so the performance benefits of ownership
2266 transfer might not justify the readability and
2267 complexity costs.</li>
2268
2269 <li>APIs that transfer ownership force their clients
2270 into a single memory management model.</li>
2271
2272 <li>Code using smart pointers is less explicit about
2273 where the resource releases take place.</li>
2274
2275 <li><code>std::unique_ptr</code> expresses ownership
2276 transfer using C++11's move semantics, which are
2277 relatively new and may confuse some programmers.</li>
2278
2279 <li>Shared ownership can be a tempting alternative to
2280 careful ownership design, obfuscating the design of a
2281 system.</li>
2282
2283 <li>Shared ownership requires explicit bookkeeping at
2284 run-time, which can be costly.</li>
2285
2286 <li>In some cases (e.g. cyclic references), objects
2287 with shared ownership may never be deleted.</li>
2288
2289 <li>Smart pointers are not perfect substitutes for
2290 plain pointers.</li>
2291</ul>
2292</div>
2293
2294<div class="decision">
2295<p>If dynamic allocation is necessary, prefer to keep
2296ownership with the code that allocated it. If other code
2297needs access to the object, consider passing it a copy,
2298or passing a pointer or reference without transferring
2299ownership. Prefer to use <code>std::unique_ptr</code> to
2300make ownership transfer explicit. For example:</p>
2301
2302<pre>std::unique_ptr&lt;Foo&gt; FooFactory();
2303void FooConsumer(std::unique_ptr&lt;Foo&gt; ptr);
2304</pre>
2305
2306
2307
2308<p>Do not design your code to use shared ownership
2309without a very good reason. One such reason is to avoid
2310expensive copy operations, but you should only do this if
2311the performance benefits are significant, and the
2312underlying object is immutable (i.e.
2313<code>std::shared_ptr&lt;const Foo&gt;</code>). If you
2314do use shared ownership, prefer to use
2315<code>std::shared_ptr</code>.</p>
2316
2317<p>Never use <code>std::auto_ptr</code>. Instead, use
2318<code>std::unique_ptr</code>.</p>
2319</div>
2320
2321</div>
2322
2323<h3 id="cpplint">cpplint</h3>
2324
2325<div class="summary">
Victor Costan6dfd9d92018-02-05 18:30:35 -08002326<p>Use <code>cpplint.py</code> to detect style errors.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002327</div>
2328
2329<div class="stylebody">
2330
2331<p><code>cpplint.py</code>
2332is a tool that reads a source file and identifies many
2333style errors. It is not perfect, and has both false
2334positives and false negatives, but it is still a valuable
2335tool. False positives can be ignored by putting <code>//
2336NOLINT</code> at the end of the line or
2337<code>// NOLINTNEXTLINE</code> in the previous line.</p>
2338
2339
2340
2341<p>Some projects have instructions on
2342how to run <code>cpplint.py</code> from their project
2343tools. If the project you are contributing to does not,
2344you can download
2345<a href="https://raw.githubusercontent.com/google/styleguide/gh-pages/cpplint/cpplint.py">
2346<code>cpplint.py</code></a> separately.</p>
2347
2348</div>
2349
2350
2351
2352<h2 id="Other_C++_Features">Other C++ Features</h2>
2353
2354<h3 id="Rvalue_references">Rvalue References</h3>
2355
2356<div class="summary">
2357<p>Use rvalue references only to define move constructors and move assignment
2358operators, or for perfect forwarding.
2359</p>
2360</div>
2361
2362<div class="stylebody">
2363
2364<div class="definition">
2365<p> Rvalue references
2366are a type of reference that can only bind to temporary
2367objects. The syntax is similar to traditional reference
2368syntax. For example, <code>void f(string&amp;&amp;
2369s);</code> declares a function whose argument is an
2370rvalue reference to a string.</p>
2371</div>
2372
2373<div class="pros">
2374<ul>
2375 <li>Defining a move constructor (a constructor taking
2376 an rvalue reference to the class type) makes it
2377 possible to move a value instead of copying it. If
2378 <code>v1</code> is a <code>std::vector&lt;string&gt;</code>,
2379 for example, then <code>auto v2(std::move(v1))</code>
2380 will probably just result in some simple pointer
2381 manipulation instead of copying a large amount of data.
2382 In some cases this can result in a major performance
2383 improvement.</li>
2384
2385 <li>Rvalue references make it possible to write a
2386 generic function wrapper that forwards its arguments to
2387 another function, and works whether or not its
2388 arguments are temporary objects. (This is sometimes called
2389 "perfect forwarding".)</li>
2390
2391 <li>Rvalue references make it possible to implement
2392 types that are movable but not copyable, which can be
2393 useful for types that have no sensible definition of
2394 copying but where you might still want to pass them as
2395 function arguments, put them in containers, etc.</li>
2396
2397 <li><code>std::move</code> is necessary to make
2398 effective use of some standard-library types, such as
2399 <code>std::unique_ptr</code>.</li>
2400</ul>
2401</div>
2402
2403<div class="cons">
2404<ul>
2405 <li>Rvalue references are a relatively new feature
2406 (introduced as part of C++11), and not yet widely
2407 understood. Rules like reference collapsing, and
2408 automatic synthesis of move constructors, are
2409 complicated.</li>
2410</ul>
2411</div>
2412
2413<div class="decision">
2414 <p>Use rvalue references only to define move constructors and move assignment
2415 operators (as described in <a href="#Copyable_Movable_Types">Copyable and
2416 Movable Types</a>) and, in conjunction with <code><a href="http://en.cppreference.com/w/cpp/utility/forward">std::forward</a></code>,
2417to support perfect forwarding. You may use <code>std::move</code> to express
2418moving a value from one object to another rather than copying it. </p>
2419</div>
2420
2421</div>
2422
2423<h3 id="Friends">Friends</h3>
2424
2425<div class="summary">
2426<p>We allow use of <code>friend</code> classes and functions,
2427within reason.</p>
2428</div>
2429
2430<div class="stylebody">
2431
2432<p>Friends should usually be defined in the same file so
2433that the reader does not have to look in another file to
2434find uses of the private members of a class. A common use
2435of <code>friend</code> is to have a
2436<code>FooBuilder</code> class be a friend of
2437<code>Foo</code> so that it can construct the inner state
2438of <code>Foo</code> correctly, without exposing this
2439state to the world. In some cases it may be useful to
2440make a unittest class a friend of the class it tests.</p>
2441
2442<p>Friends extend, but do not break, the encapsulation
2443boundary of a class. In some cases this is better than
2444making a member public when you want to give only one
2445other class access to it. However, most classes should
2446interact with other classes solely through their public
2447members.</p>
2448
2449</div>
2450
2451<h3 id="Exceptions">Exceptions</h3>
2452
2453<div class="summary">
2454<p>We do not use C++ exceptions.</p>
2455</div>
2456
2457<div class="stylebody">
2458
2459<div class="pros">
2460<ul>
2461 <li>Exceptions allow higher levels of an application to
2462 decide how to handle "can't happen" failures in deeply
2463 nested functions, without the obscuring and error-prone
2464 bookkeeping of error codes.</li>
2465
2466
2467
2468 <li>Exceptions are used by most other
2469 modern languages. Using them in C++ would make it more
2470 consistent with Python, Java, and the C++ that others
2471 are familiar with.</li>
2472
2473 <li>Some third-party C++ libraries use exceptions, and
2474 turning them off internally makes it harder to
2475 integrate with those libraries.</li>
2476
2477 <li>Exceptions are the only way for a constructor to
2478 fail. We can simulate this with a factory function or
2479 an <code>Init()</code> method, but these require heap
2480 allocation or a new "invalid" state, respectively.</li>
2481
2482 <li>Exceptions are really handy in testing
2483 frameworks.</li>
2484</ul>
2485</div>
2486
2487<div class="cons">
2488<ul>
2489 <li>When you add a <code>throw</code> statement to an
2490 existing function, you must examine all of its
2491 transitive callers. Either they must make at least the
2492 basic exception safety guarantee, or they must never
2493 catch the exception and be happy with the program
2494 terminating as a result. For instance, if
2495 <code>f()</code> calls <code>g()</code> calls
2496 <code>h()</code>, and <code>h</code> throws an
2497 exception that <code>f</code> catches, <code>g</code>
2498 has to be careful or it may not clean up properly.</li>
2499
2500 <li>More generally, exceptions make the control flow of
2501 programs difficult to evaluate by looking at code:
2502 functions may return in places you don't expect. This
2503 causes maintainability and debugging difficulties. You
2504 can minimize this cost via some rules on how and where
2505 exceptions can be used, but at the cost of more that a
2506 developer needs to know and understand.</li>
2507
2508 <li>Exception safety requires both RAII and different
2509 coding practices. Lots of supporting machinery is
2510 needed to make writing correct exception-safe code
2511 easy. Further, to avoid requiring readers to understand
2512 the entire call graph, exception-safe code must isolate
2513 logic that writes to persistent state into a "commit"
2514 phase. This will have both benefits and costs (perhaps
2515 where you're forced to obfuscate code to isolate the
2516 commit). Allowing exceptions would force us to always
2517 pay those costs even when they're not worth it.</li>
2518
2519 <li>Turning on exceptions adds data to each binary
2520 produced, increasing compile time (probably slightly)
2521 and possibly increasing address space pressure.
2522 </li>
2523
2524 <li>The availability of exceptions may encourage
2525 developers to throw them when they are not appropriate
2526 or recover from them when it's not safe to do so. For
2527 example, invalid user input should not cause exceptions
2528 to be thrown. We would need to make the style guide
2529 even longer to document these restrictions!</li>
2530</ul>
2531</div>
2532
2533<div class="decision">
2534<p>On their face, the benefits of using exceptions
2535outweigh the costs, especially in new projects. However,
2536for existing code, the introduction of exceptions has
2537implications on all dependent code. If exceptions can be
2538propagated beyond a new project, it also becomes
2539problematic to integrate the new project into existing
2540exception-free code. Because most existing C++ code at
2541Google is not prepared to deal with exceptions, it is
2542comparatively difficult to adopt new code that generates
2543exceptions.</p>
2544
2545<p>Given that Google's existing code is not
2546exception-tolerant, the costs of using exceptions are
2547somewhat greater than the costs in a new project. The
2548conversion process would be slow and error-prone. We
2549don't believe that the available alternatives to
2550exceptions, such as error codes and assertions, introduce
2551a significant burden. </p>
2552
2553<p>Our advice against using exceptions is not predicated
2554on philosophical or moral grounds, but practical ones.
2555 Because we'd like to use our open-source
2556projects at Google and it's difficult to do so if those
2557projects use exceptions, we need to advise against
2558exceptions in Google open-source projects as well.
2559Things would probably be different if we had to do it all
2560over again from scratch.</p>
2561
Victor Costan6dfd9d92018-02-05 18:30:35 -08002562<p>This prohibition also applies to the exception handling related
2563features added in C++11, such as
2564<code>std::exception_ptr</code> and
Ted Osborne505ba682018-01-30 12:36:50 -05002565<code>std::nested_exception</code>.</p>
2566
2567<p>There is an <a href="#Windows_Code">exception</a> to
2568this rule (no pun intended) for Windows code.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002569
2570</div>
2571
2572</div>
2573
2574<h3 id="noexcept"><code>noexcept</code></h3>
2575
2576<div class="summary">
2577<p>Specify <code>noexcept</code> when it is useful and correct.</p>
2578</div>
2579
2580<div class="stylebody">
2581<div class="definition">
2582<p>The <code>noexcept</code> specifier is used to specify whether
2583a function will throw exceptions or not. If an exception
2584escapes from a function marked <code>noexcept</code>, the program
2585crashes via <code>std::terminate</code>.</p>
2586
2587<p>The <code>noexcept</code> operator performs a compile-time
2588check that returns true if an expression is declared to not
2589throw any exceptions.</p>
2590
2591</div>
2592
2593<div class="pros">
2594<ul>
2595 <li>Specifying move constructors as <code>noexcept</code>
2596 improves performance in some cases, e.g.
2597 <code>std::vector&lt;T&gt;::resize()</code> moves rather than
2598 copies the objects if T's move constructor is
2599 <code>noexcept</code>.</li>
2600
2601 <li>Specifying <code>noexcept</code> on a function can
2602 trigger compiler optimizations in environments where
2603 exceptions are enabled, e.g. compiler does not have to
2604 generate extra code for stack-unwinding, if it knows
2605 that no exceptions can be thrown due to a
2606 <code>noexcept</code> specifier.</li>
2607</ul>
2608</div>
2609
2610<div class="cons">
2611<ul>
2612 <li>
2613
2614 In projects following this guide
2615 that have exceptions disabled it is hard
2616 to ensure that <code>noexcept</code>
2617 specifiers are correct, and hard to define what
2618 correctness even means.</li>
2619
2620 <li>It's hard, if not impossible, to undo <code>noexcept</code>
2621 because it eliminates a guarantee that callers may be relying
2622 on, in ways that are hard to detect.</li>
2623</ul>
2624</div>
2625
2626<div class="decision">
2627<p>You may use <code>noexcept</code> when it is useful for
2628performance if it accurately reflects the intended semantics
2629of your function, i.e. that if an exception is somehow thrown
2630from within the function body then it represents a fatal error.
2631You can assume that <code>noexcept</code> on move constructors
2632has a meaningful performance benefit. If you think
2633there is significant performance benefit from specifying
2634<code>noexcept</code> on some other function, please discuss it
2635with
2636your project leads.</p>
2637
2638<p>Prefer unconditional <code>noexcept</code> if exceptions are
2639completely disabled (i.e. most Google C++ environments).
2640Otherwise, use conditional <code>noexcept</code> specifiers
2641with simple conditions, in ways that evaluate false only in
2642the few cases where the function could potentially throw.
2643The tests might include type traits check on whether the
2644involved operation might throw (e.g.
2645<code>std::is_nothrow_move_constructible</code> for
2646move-constructing objects), or on whether allocation can throw
2647(e.g. <code>absl::default_allocator_is_nothrow</code> for
2648standard default allocation). Note in many cases the only
2649possible cause for an exception is allocation failure (we
2650believe move constructors should not throw except due to
2651allocation failure), and there are many applications where it&#8217;s
2652appropriate to treat memory exhaustion as a fatal error rather
2653than an exceptional condition that your program should attempt
2654to recover from. Even for other
2655potential failures you should prioritize interface simplicity
2656over supporting all possible exception throwing scenarios:
2657instead of writing a complicated <code>noexcept</code> clause
2658that depends on whether a hash function can throw, for example,
2659simply document that your component doesn&#8217;t support hash
2660functions throwing and make it unconditionally
2661<code>noexcept</code>.</p>
2662
Ted Osborne505ba682018-01-30 12:36:50 -05002663</div>
2664
2665</div>
2666
2667<h3 id="Run-Time_Type_Information__RTTI_">Run-Time Type
2668Information (RTTI)</h3>
2669
2670<div class="summary">
2671<p>Avoid using Run Time Type Information (RTTI).</p>
2672</div>
2673
2674<div class="stylebody">
2675
2676<div class="definition">
2677<p> RTTI allows a
2678programmer to query the C++ class of an object at run
2679time. This is done by use of <code>typeid</code> or
2680<code>dynamic_cast</code>.</p>
2681</div>
2682
2683<div class="cons">
2684<p>Querying the type of an object at run-time frequently
2685means a design problem. Needing to know the type of an
2686object at runtime is often an indication that the design
2687of your class hierarchy is flawed.</p>
2688
2689<p>Undisciplined use of RTTI makes code hard to maintain.
2690It can lead to type-based decision trees or switch
2691statements scattered throughout the code, all of which
2692must be examined when making further changes.</p>
2693</div>
2694
2695<div class="pros">
2696<p>The standard alternatives to RTTI (described below)
2697require modification or redesign of the class hierarchy
2698in question. Sometimes such modifications are infeasible
2699or undesirable, particularly in widely-used or mature
2700code.</p>
2701
2702<p>RTTI can be useful in some unit tests. For example, it
2703is useful in tests of factory classes where the test has
2704to verify that a newly created object has the expected
2705dynamic type. It is also useful in managing the
2706relationship between objects and their mocks.</p>
2707
2708<p>RTTI is useful when considering multiple abstract
2709objects. Consider</p>
2710
2711<pre>bool Base::Equal(Base* other) = 0;
2712bool Derived::Equal(Base* other) {
2713 Derived* that = dynamic_cast&lt;Derived*&gt;(other);
Victor Costan6dfd9d92018-02-05 18:30:35 -08002714 if (that == nullptr)
Ted Osborne505ba682018-01-30 12:36:50 -05002715 return false;
2716 ...
2717}
2718</pre>
2719</div>
2720
2721<div class="decision">
2722<p>RTTI has legitimate uses but is prone to abuse, so you
2723must be careful when using it. You may use it freely in
2724unittests, but avoid it when possible in other code. In
2725particular, think twice before using RTTI in new code. If
2726you find yourself needing to write code that behaves
2727differently based on the class of an object, consider one
2728of the following alternatives to querying the type:</p>
2729
2730<ul>
2731 <li>Virtual methods are the preferred way of executing
2732 different code paths depending on a specific subclass
2733 type. This puts the work within the object itself.</li>
2734
2735 <li>If the work belongs outside the object and instead
2736 in some processing code, consider a double-dispatch
2737 solution, such as the Visitor design pattern. This
2738 allows a facility outside the object itself to
2739 determine the type of class using the built-in type
2740 system.</li>
2741</ul>
2742
2743<p>When the logic of a program guarantees that a given
2744instance of a base class is in fact an instance of a
2745particular derived class, then a
2746<code>dynamic_cast</code> may be used freely on the
2747object. Usually one
2748can use a <code>static_cast</code> as an alternative in
2749such situations.</p>
2750
2751<p>Decision trees based on type are a strong indication
2752that your code is on the wrong track.</p>
2753
2754<pre class="badcode">if (typeid(*data) == typeid(D1)) {
2755 ...
2756} else if (typeid(*data) == typeid(D2)) {
2757 ...
2758} else if (typeid(*data) == typeid(D3)) {
2759...
2760</pre>
2761
2762<p>Code such as this usually breaks when additional
2763subclasses are added to the class hierarchy. Moreover,
2764when properties of a subclass change, it is difficult to
2765find and modify all the affected code segments.</p>
2766
2767<p>Do not hand-implement an RTTI-like workaround. The
2768arguments against RTTI apply just as much to workarounds
2769like class hierarchies with type tags. Moreover,
2770workarounds disguise your true intent.</p>
2771</div>
2772
2773</div>
2774
2775<h3 id="Casting">Casting</h3>
2776
2777<div class="summary">
2778<p>Use C++-style casts
2779like <code>static_cast&lt;float&gt;(double_value)</code>, or brace
2780initialization for conversion of arithmetic types like
2781<code>int64 y = int64{1} &lt;&lt; 42</code>. Do not use
2782cast formats like
2783<code>int y = (int)x</code> or <code>int y = int(x)</code> (but the latter
2784is okay when invoking a constructor of a class type).</p>
2785</div>
2786
2787<div class="stylebody">
2788
2789<div class="definition">
2790<p> C++ introduced a
2791different cast system from C that distinguishes the types
2792of cast operations.</p>
2793</div>
2794
2795<div class="pros">
2796<p>The problem with C casts is the ambiguity of the operation;
2797sometimes you are doing a <em>conversion</em>
2798(e.g., <code>(int)3.5</code>) and sometimes you are doing
2799a <em>cast</em> (e.g., <code>(int)"hello"</code>). Brace
2800initialization and C++ casts can often help avoid this
2801ambiguity. Additionally, C++ casts are more visible when searching for
2802them.</p>
2803</div>
2804
2805<div class="cons">
2806<p>The C++-style cast syntax is verbose and cumbersome.</p>
2807</div>
2808
2809<div class="decision">
2810<p>Do not use C-style casts. Instead, use these C++-style casts when
2811explicit type conversion is necessary. </p>
2812
2813<ul>
2814 <li>Use brace initialization to convert arithmetic types
2815 (e.g. <code>int64{x}</code>). This is the safest approach because code
2816 will not compile if conversion can result in information loss. The
2817 syntax is also concise.</li>
2818
2819
2820
2821 <li>Use <code>static_cast</code> as the equivalent of a C-style cast
2822 that does value conversion, when you need to
2823 explicitly up-cast a pointer from a class to its superclass, or when
2824 you need to explicitly cast a pointer from a superclass to a
2825 subclass. In this last case, you must be sure your object is
2826 actually an instance of the subclass.</li>
2827
2828
2829
2830 <li>Use <code>const_cast</code> to remove the
2831 <code>const</code> qualifier (see <a href="#Use_of_const">const</a>).</li>
2832
2833 <li>Use <code>reinterpret_cast</code> to do unsafe
2834 conversions of pointer types to and from integer and
2835 other pointer types. Use this only if you know what you
2836 are doing and you understand the aliasing issues.
2837 </li>
2838
2839
2840</ul>
2841
2842<p>See the <a href="#Run-Time_Type_Information__RTTI_">
2843RTTI section</a> for guidance on the use of
2844<code>dynamic_cast</code>.</p>
2845</div>
2846
2847</div>
2848
2849<h3 id="Streams">Streams</h3>
2850
2851<div class="summary">
2852<p>Use streams where appropriate, and stick to "simple"
Victor Costan6dfd9d92018-02-05 18:30:35 -08002853usages. Overload <code>&lt;&lt;</code> for streaming only for types
2854representing values, and write only the user-visible value, not any
2855implementation details.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002856</div>
2857
2858<div class="stylebody">
2859
2860<div class="definition">
2861<p>Streams are the standard I/O abstraction in C++, as
2862exemplified by the standard header <code>&lt;iostream&gt;</code>.
2863They are widely used in Google code, but only for debug logging
2864and test diagnostics.</p>
2865</div>
2866
2867<div class="pros">
2868<p>The <code>&lt;&lt;</code> and <code>&gt;&gt;</code>
2869stream operators provide an API for formatted I/O that
2870is easily learned, portable, reusable, and extensible.
2871<code>printf</code>, by contrast, doesn't even support
2872<code>string</code>, to say nothing of user-defined types,
2873and is very difficult to use portably.
2874<code>printf</code> also obliges you to choose among the
2875numerous slightly different versions of that function,
2876and navigate the dozens of conversion specifiers.</p>
2877
2878<p>Streams provide first-class support for console I/O
2879via <code>std::cin</code>, <code>std::cout</code>,
2880<code>std::cerr</code>, and <code>std::clog</code>.
2881The C APIs do as well, but are hampered by the need to
2882manually buffer the input. </p>
2883</div>
2884
2885<div class="cons">
2886<ul>
2887<li>Stream formatting can be configured by mutating the
2888state of the stream. Such mutations are persistent, so
2889the behavior of your code can be affected by the entire
2890previous history of the stream, unless you go out of your
2891way to restore it to a known state every time other code
2892might have touched it. User code can not only modify the
2893built-in state, it can add new state variables and behaviors
2894through a registration system.</li>
2895
2896<li>It is difficult to precisely control stream output, due
2897to the above issues, the way code and data are mixed in
2898streaming code, and the use of operator overloading (which
2899may select a different overload than you expect).</li>
2900
2901<li>The practice of building up output through chains
2902of <code>&lt;&lt;</code> operators interferes with
2903internationalization, because it bakes word order into the
2904code, and streams' support for localization is <a href="http://www.boost.org/doc/libs/1_48_0/libs/locale/doc/html/rationale.html#rationale_why">
2905flawed</a>.</li>
2906
2907
2908
2909
2910
2911<li>The streams API is subtle and complex, so programmers must
Victor Costan6dfd9d92018-02-05 18:30:35 -08002912develop experience with it in order to use it effectively.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05002913
2914<li>Resolving the many overloads of <code>&lt;&lt;</code> is
2915extremely costly for the compiler. When used pervasively in a
2916large code base, it can consume as much as 20% of the parsing
2917and semantic analysis time.</li>
2918</ul>
2919</div>
2920
2921<div class="decision">
2922<p>Use streams only when they are the best tool for the job.
2923This is typically the case when the I/O is ad-hoc, local,
2924human-readable, and targeted at other developers rather than
2925end-users. Be consistent with the code around you, and with the
2926codebase as a whole; if there's an established tool for
2927your problem, use that tool instead. </p>
2928
2929<p>Avoid using streams for I/O that faces external users or
2930handles untrusted data. Instead, find and use the appropriate
2931templating libraries to handle issues like internationalization,
2932localization, and security hardening.</p>
2933
2934<p>If you do use streams, avoid the stateful parts of the
2935streams API (other than error state), such as <code>imbue()</code>,
2936<code>xalloc()</code>, and <code>register_callback()</code>.
2937Use explicit formatting functions rather than
2938stream manipulators or formatting flags to control formatting
2939details such as number base, precision, or padding.</p>
2940
2941<p>Overload <code>&lt;&lt;</code> as a streaming operator
2942for your type only if your type represents a value, and
2943<code>&lt;&lt;</code> writes out a human-readable string
2944representation of that value. Avoid exposing implementation
2945details in the output of <code>&lt;&lt;</code>; if you need to print
2946object internals for debugging, use named functions instead
2947(a method named <code>DebugString()</code> is the most common
2948convention).</p>
2949</div>
2950
2951</div>
2952
2953<h3 id="Preincrement_and_Predecrement">Preincrement and Predecrement</h3>
2954
2955<div class="summary">
2956<p>Use prefix form (<code>++i</code>) of the increment and
2957decrement operators with iterators and other template
2958objects.</p>
2959</div>
2960
2961<div class="stylebody">
2962
2963<div class="definition">
2964<p> When a variable
2965is incremented (<code>++i</code> or <code>i++</code>) or
2966decremented (<code>--i</code> or <code>i--</code>) and
2967the value of the expression is not used, one must decide
2968whether to preincrement (decrement) or postincrement
2969(decrement).</p>
2970</div>
2971
2972<div class="pros">
2973<p>When the return value is ignored, the "pre" form
2974(<code>++i</code>) is never less efficient than the
2975"post" form (<code>i++</code>), and is often more
2976efficient. This is because post-increment (or decrement)
2977requires a copy of <code>i</code> to be made, which is
2978the value of the expression. If <code>i</code> is an
2979iterator or other non-scalar type, copying <code>i</code>
2980could be expensive. Since the two types of increment
2981behave the same when the value is ignored, why not just
2982always pre-increment?</p>
2983</div>
2984
2985<div class="cons">
2986<p>The tradition developed, in C, of using post-increment
2987when the expression value is not used, especially in
2988<code>for</code> loops. Some find post-increment easier
2989to read, since the "subject" (<code>i</code>) precedes
2990the "verb" (<code>++</code>), just like in English.</p>
2991</div>
2992
2993<div class="decision">
2994<p> For simple scalar
2995(non-object) values there is no reason to prefer one form
2996and we allow either. For iterators and other template
2997types, use pre-increment.</p>
2998</div>
2999
3000</div>
3001
3002<h3 id="Use_of_const">Use of const</h3>
3003
3004<div class="summary">
3005<p>Use <code>const</code> whenever it makes sense. With C++11,
3006<code>constexpr</code> is a better choice for some uses of
3007const.</p>
3008</div>
3009
3010<div class="stylebody">
3011
3012<div class="definition">
3013<p> Declared variables and parameters can be preceded
3014by the keyword <code>const</code> to indicate the variables
3015are not changed (e.g., <code>const int foo</code>). Class
3016functions can have the <code>const</code> qualifier to
3017indicate the function does not change the state of the
3018class member variables (e.g., <code>class Foo { int
3019Bar(char c) const; };</code>).</p>
3020</div>
3021
3022<div class="pros">
3023<p>Easier for people to understand how variables are being
3024used. Allows the compiler to do better type checking,
3025and, conceivably, generate better code. Helps people
3026convince themselves of program correctness because they
3027know the functions they call are limited in how they can
3028modify your variables. Helps people know what functions
3029are safe to use without locks in multi-threaded
3030programs.</p>
3031</div>
3032
3033<div class="cons">
3034<p><code>const</code> is viral: if you pass a
3035<code>const</code> variable to a function, that function
3036must have <code>const</code> in its prototype (or the
3037variable will need a <code>const_cast</code>). This can
3038be a particular problem when calling library
3039functions.</p>
3040</div>
3041
3042<div class="decision">
3043<p><code>const</code> variables, data members, methods
3044and arguments add a level of compile-time type checking;
3045it is better to detect errors as soon as possible.
3046Therefore we strongly recommend that you use
3047<code>const</code> whenever it makes sense to do so:</p>
3048
3049<ul>
3050 <li>If a function guarantees that it will not modify an argument
3051 passed by reference or by pointer, the corresponding function parameter
3052 should be a reference-to-const (<code>const T&amp;</code>) or
3053 pointer-to-const (<code>const T*</code>), respectively.</li>
3054
3055 <li>Declare methods to be <code>const</code> whenever
3056 possible. Accessors should almost always be
3057 <code>const</code>. Other methods should be const if
3058 they do not modify any data members, do not call any
3059 non-<code>const</code> methods, and do not return a
3060 non-<code>const</code> pointer or
3061 non-<code>const</code> reference to a data member.</li>
3062
3063 <li>Consider making data members <code>const</code>
3064 whenever they do not need to be modified after
3065 construction.</li>
3066</ul>
3067
3068<p>The <code>mutable</code> keyword is allowed but is
3069unsafe when used with threads, so thread safety should be
3070carefully considered first.</p>
3071</div>
3072
3073<div class="stylepoint_subsection">
3074<h4>Where to put the const</h4>
3075
3076<p>Some people favor the form <code>int const *foo</code>
3077to <code>const int* foo</code>. They argue that this is
3078more readable because it's more consistent: it keeps the
3079rule that <code>const</code> always follows the object
3080it's describing. However, this consistency argument
3081doesn't apply in codebases with few deeply-nested pointer
3082expressions since most <code>const</code> expressions
3083have only one <code>const</code>, and it applies to the
3084underlying value. In such cases, there's no consistency
3085to maintain. Putting the <code>const</code> first is
3086arguably more readable, since it follows English in
3087putting the "adjective" (<code>const</code>) before the
3088"noun" (<code>int</code>).</p>
3089
3090<p>That said, while we encourage putting
3091<code>const</code> first, we do not require it. But be
3092consistent with the code around you!</p>
3093</div>
3094
3095</div>
3096
3097<h3 id="Use_of_constexpr">Use of constexpr</h3>
3098
3099<div class="summary">
3100<p>In C++11, use <code>constexpr</code> to define true
3101constants or to ensure constant initialization.</p>
3102</div>
3103
3104<div class="stylebody">
3105
3106<div class="definition">
3107<p> Some variables can be declared <code>constexpr</code>
3108to indicate the variables are true constants, i.e. fixed at
3109compilation/link time. Some functions and constructors
3110can be declared <code>constexpr</code> which enables them
3111to be used in defining a <code>constexpr</code>
3112variable.</p>
3113</div>
3114
3115<div class="pros">
3116<p>Use of <code>constexpr</code> enables definition of
3117constants with floating-point expressions rather than
3118just literals; definition of constants of user-defined
3119types; and definition of constants with function
3120calls.</p>
3121</div>
3122
3123<div class="cons">
3124<p>Prematurely marking something as constexpr may cause
3125migration problems if later on it has to be downgraded.
3126Current restrictions on what is allowed in constexpr
3127functions and constructors may invite obscure workarounds
3128in these definitions.</p>
3129</div>
3130
3131<div class="decision">
3132<p><code>constexpr</code> definitions enable a more
3133robust specification of the constant parts of an
3134interface. Use <code>constexpr</code> to specify true
3135constants and the functions that support their
3136definitions. Avoid complexifying function definitions to
3137enable their use with <code>constexpr</code>. Do not use
3138<code>constexpr</code> to force inlining.</p>
3139</div>
3140
3141</div>
3142
3143<h3 id="Integer_Types">Integer Types</h3>
3144
3145<div class="summary">
3146<p>Of the built-in C++ integer types, the only one used
3147 is
3148<code>int</code>. If a program needs a variable of a
3149different size, use
3150a precise-width integer type from
3151<code>&lt;stdint.h&gt;</code>, such as
3152<code>int16_t</code>. If your variable represents a
3153value that could ever be greater than or equal to 2^31
3154(2GiB), use a 64-bit type such as
3155<code>int64_t</code>.
3156Keep in mind that even if your value won't ever be too large
3157for an <code>int</code>, it may be used in intermediate
3158calculations which may require a larger type. When in doubt,
3159choose a larger type.</p>
3160</div>
3161
3162<div class="stylebody">
3163
3164<div class="definition">
Victor Costan6dfd9d92018-02-05 18:30:35 -08003165<p> C++ does not specify the sizes of integer types
3166like <code>int</code>. Typically people assume
3167that <code>short</code> is 16 bits,
Ted Osborne505ba682018-01-30 12:36:50 -05003168<code>int</code> is 32 bits, <code>long</code> is 32 bits
3169and <code>long long</code> is 64 bits.</p>
3170</div>
3171
3172<div class="pros">
3173<p>Uniformity of declaration.</p>
3174</div>
3175
3176<div class="cons">
3177<p>The sizes of integral types in C++ can vary based on
3178compiler and architecture.</p>
3179</div>
3180
3181<div class="decision">
3182
3183<p>
3184<code>&lt;stdint.h&gt;</code> defines types
3185like <code>int16_t</code>, <code>uint32_t</code>,
3186<code>int64_t</code>, etc. You should always use
3187those in preference to <code>short</code>, <code>unsigned
3188long long</code> and the like, when you need a guarantee
3189on the size of an integer. Of the C integer types, only
3190<code>int</code> should be used. When appropriate, you
3191are welcome to use standard types like
3192<code>size_t</code> and <code>ptrdiff_t</code>.</p>
3193
3194<p>We use <code>int</code> very often, for integers we
3195know are not going to be too big, e.g., loop counters.
3196Use plain old <code>int</code> for such things. You
3197should assume that an <code>int</code> is
3198
3199at least 32 bits, but don't
3200assume that it has more than 32 bits. If you need a 64-bit
3201integer type, use
3202<code>int64_t</code>
3203or
3204<code>uint64_t</code>.</p>
3205
3206<p>For integers we know can be "big",
3207 use
3208<code>int64_t</code>.
3209</p>
3210
3211<p>You should not use the unsigned integer types such as
3212<code>uint32_t</code>, unless there is a valid
3213reason such as representing a bit pattern rather than a
3214number, or you need defined overflow modulo 2^N. In
3215particular, do not use unsigned types to say a number
3216will never be negative. Instead, use
3217assertions for this.</p>
3218
3219
3220
3221<p>If your code is a container that returns a size, be
3222sure to use a type that will accommodate any possible
3223usage of your container. When in doubt, use a larger type
3224rather than a smaller type.</p>
3225
Victor Costan6dfd9d92018-02-05 18:30:35 -08003226<p>Use care when converting integer types. Integer conversions and
3227promotions can cause undefined behavior, leading to security bugs and
3228other problems.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003229</div>
3230
3231<div class="stylepoint_subsection">
3232
3233<h4>On Unsigned Integers</h4>
3234
Victor Costan6dfd9d92018-02-05 18:30:35 -08003235<p>Unsigned integers are good for representing bitfields and modular
3236arithmetic. Because of historical accident, the C++ standard also uses
3237unsigned integers to represent the size of containers - many members
3238of the standards body believe this to be a mistake, but it is
3239effectively impossible to fix at this point. The fact that unsigned
3240arithmetic doesn't model the behavior of a simple integer, but is
3241instead defined by the standard to model modular arithmetic (wrapping
3242around on overflow/underflow), means that a significant class of bugs
3243cannot be diagnosed by the compiler. In other cases, the defined
3244behavior impedes optimization.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003245
Victor Costan6dfd9d92018-02-05 18:30:35 -08003246<p>That said, mixing signedness of integer types is responsible for an
3247equally large class of problems. The best advice we can provide: try
3248to use iterators and containers rather than pointers and sizes, try
3249not to mix signedness, and try to avoid unsigned types (except for
3250representing bitfields or modular arithmetic). Do not use an unsigned
3251type merely to assert that a variable is non-negative.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003252</div>
3253
3254</div>
3255
3256<h3 id="64-bit_Portability">64-bit Portability</h3>
3257
3258<div class="summary">
3259<p>Code should be 64-bit and 32-bit friendly. Bear in mind
3260problems of printing, comparisons, and structure alignment.</p>
3261</div>
3262
3263<div class="stylebody">
3264
3265<ul>
3266 <li>
Victor Costan6dfd9d92018-02-05 18:30:35 -08003267 <p>Correct portable <code>printf()</code> conversion specifiers for
3268 some integral typedefs rely on macro expansions that we find unpleasant to
3269 use and impractical to require (the <code>PRI</code> macros from
3270 <code>&lt;cinttypes&gt;</code>). Unless there is no reasonable alternative
3271 for your particular case, try to avoid or even upgrade APIs that rely on the
3272 <code>printf</code> family. Instead use a library supporting typesafe numeric
3273 formatting, such as
Ted Osborne505ba682018-01-30 12:36:50 -05003274
Victor Costan6dfd9d92018-02-05 18:30:35 -08003275 <a href="#Streams"><code>std::ostream</code></a>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003276
Victor Costan6dfd9d92018-02-05 18:30:35 -08003277 <p>Unfortunately, the <code>PRI</code> macros are the only portable way to
3278 specify a conversion for the standard bitwidth typedefs (e.g.
3279 <code>int64_t</code>, <code>uint64_t</code>, <code>int32_t</code>,
3280 <code>uint32_t</code>, etc).
Ted Osborne505ba682018-01-30 12:36:50 -05003281
Victor Costan6dfd9d92018-02-05 18:30:35 -08003282 Where possible, avoid passing arguments of types specified by bitwidth
3283 typedefs to <code>printf</code>-based APIs. Note that it is acceptable
3284 to use typedefs for which printf has dedicated length modifiers, such as
3285 <code>size_t</code> (<code>z</code>),
3286 <code>ptrdiff_t</code> (<code>t</code>), and
3287 <code>maxint_t</code> (<code>j</code>).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003288 </li>
3289
3290 <li>Remember that <code>sizeof(void *)</code> !=
3291 <code>sizeof(int)</code>. Use <code>intptr_t</code> if
3292 you want a pointer-sized integer.</li>
3293
3294 <li>You may need to be careful with structure
3295 alignments, particularly for structures being stored on
3296 disk. Any class/structure with a
3297 <code>int64_t</code>/<code>uint64_t</code>
3298 member will by default end up being 8-byte aligned on a
3299 64-bit system. If you have such structures being shared
3300 on disk between 32-bit and 64-bit code, you will need
3301 to ensure that they are packed the same on both
3302 architectures.
3303 Most compilers offer a way to
3304 alter structure alignment. For gcc, you can use
3305 <code>__attribute__((packed))</code>. MSVC offers
3306 <code>#pragma pack()</code> and
3307 <code>__declspec(align())</code>.</li>
3308
3309 <li>
Victor Costan6dfd9d92018-02-05 18:30:35 -08003310 <p>Use <a href="#Casting">braced-initialization</a> as needed to create
3311 64-bit constants. For example:</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003312
3313
Victor Costan6dfd9d92018-02-05 18:30:35 -08003314<pre>int64_t my_value{0x123456789};
3315uint64_t my_mask{3ULL &lt;&lt; 48};
Ted Osborne505ba682018-01-30 12:36:50 -05003316</pre>
3317 </li>
3318</ul>
3319
3320</div>
3321
3322<h3 id="Preprocessor_Macros">Preprocessor Macros</h3>
3323
3324<div class="summary">
3325<p>Avoid defining macros, especially in headers; prefer
3326inline functions, enums, and <code>const</code> variables.
3327Name macros with a project-specific prefix. Do not use
3328macros to define pieces of a C++ API.</p>
3329</div>
3330
3331<div class="stylebody">
3332
3333<p>Macros mean that the code you see is not the same as
3334the code the compiler sees. This can introduce unexpected
3335behavior, especially since macros have global scope.</p>
3336
3337<p>The problems introduced by macros are especially severe
3338when they are used to define pieces of a C++ API,
3339and still more so for public APIs. Every error message from
3340the compiler when developers incorrectly use that interface
3341now must explain how the macros formed the interface.
3342Refactoring and analysis tools have a dramatically harder
3343time updating the interface. As a consequence, we
3344specifically disallow using macros in this way.
3345For example, avoid patterns like:</p>
3346
3347<pre class="badcode">class WOMBAT_TYPE(Foo) {
3348 // ...
3349
3350 public:
3351 EXPAND_PUBLIC_WOMBAT_API(Foo)
3352
3353 EXPAND_WOMBAT_COMPARISONS(Foo, ==, &lt;)
3354};
3355</pre>
3356
3357<p>Luckily, macros are not nearly as necessary in C++ as
3358they are in C. Instead of using a macro to inline
3359performance-critical code, use an inline function.
3360Instead of using a macro to store a constant, use a
3361<code>const</code> variable. Instead of using a macro to
3362"abbreviate" a long variable name, use a reference.
3363Instead of using a macro to conditionally compile code
3364... well, don't do that at all (except, of course, for
3365the <code>#define</code> guards to prevent double
3366inclusion of header files). It makes testing much more
3367difficult.</p>
3368
3369<p>Macros can do things these other techniques cannot,
3370and you do see them in the codebase, especially in the
3371lower-level libraries. And some of their special features
3372(like stringifying, concatenation, and so forth) are not
3373available through the language proper. But before using a
3374macro, consider carefully whether there's a non-macro way
3375to achieve the same result. If you need to use a macro to
3376define an interface, contact
3377your project leads to request
3378a waiver of this rule.</p>
3379
3380<p>The following usage pattern will avoid many problems
3381with macros; if you use macros, follow it whenever
3382possible:</p>
3383
3384<ul>
3385 <li>Don't define macros in a <code>.h</code> file.</li>
3386
3387 <li><code>#define</code> macros right before you use
3388 them, and <code>#undef</code> them right after.</li>
3389
3390 <li>Do not just <code>#undef</code> an existing macro
3391 before replacing it with your own; instead, pick a name
3392 that's likely to be unique.</li>
3393
3394 <li>Try not to use macros that expand to unbalanced C++
3395 constructs, or at least document that behavior
3396 well.</li>
3397
3398 <li>Prefer not using <code>##</code> to generate
3399 function/class/variable names.</li>
3400</ul>
3401
3402<p>Exporting macros from headers (i.e. defining them in a header
3403without <code>#undef</code>ing them before the end of the header)
3404is extremely strongly discouraged. If you do export a macro from a
3405header, it must have a globally unique name. To achieve this, it
3406must be named with a prefix consisting of your project's namespace
3407name (but upper case). </p>
3408
3409</div>
3410
3411<h3 id="0_and_nullptr/NULL">0 and nullptr/NULL</h3>
3412
3413<div class="summary">
Victor Costan6dfd9d92018-02-05 18:30:35 -08003414<p>Use <code>0</code> for integers, <code>0.0</code> for reals,
3415<code>nullptr</code> for pointers, and <code>'\0'</code> for chars.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003416</div>
3417
3418<div class="stylebody">
3419
Victor Costan6dfd9d92018-02-05 18:30:35 -08003420<p>Use <code>0</code> for integers and <code>0.0</code> for reals.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003421
Victor Costan6dfd9d92018-02-05 18:30:35 -08003422<p>For pointers (address values), there is a choice between <code>0</code>,
3423<code>NULL</code>, and <code>nullptr</code>. For projects that allow C++11
3424features, use <code>nullptr</code>, as this provides type-safety.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003425
Victor Costan6dfd9d92018-02-05 18:30:35 -08003426<p>For C++03 projects, prefer <code>NULL</code> to <code>0</code>. While the
3427values are equivalent, <code>NULL</code> looks more like a pointer to the
3428reader, and some C++ compilers provide special definitions of <code>NULL</code>
3429which enable them to give useful warnings.</p>
3430
3431<p>Use <code>'\0'</code> for the null character. Using the correct type makes
3432the code more readable.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003433
3434</div>
3435
3436<h3 id="sizeof">sizeof</h3>
3437
3438<div class="summary">
3439<p>Prefer <code>sizeof(<var>varname</var>)</code> to
3440<code>sizeof(<var>type</var>)</code>.</p>
3441</div>
3442
3443<div class="stylebody">
3444
3445<p>Use <code>sizeof(<var>varname</var>)</code> when you
3446take the size of a particular variable.
3447<code>sizeof(<var>varname</var>)</code> will update
3448appropriately if someone changes the variable type either
3449now or later. You may use
3450<code>sizeof(<var>type</var>)</code> for code unrelated
3451to any particular variable, such as code that manages an
3452external or internal data format where a variable of an
3453appropriate C++ type is not convenient.</p>
3454
3455<pre>Struct data;
3456memset(&amp;data, 0, sizeof(data));
3457</pre>
3458
3459<pre class="badcode">memset(&amp;data, 0, sizeof(Struct));
3460</pre>
3461
3462<pre>if (raw_size &lt; sizeof(int)) {
3463 LOG(ERROR) &lt;&lt; "compressed record not big enough for count: " &lt;&lt; raw_size;
3464 return false;
3465}
3466</pre>
3467
3468</div>
3469
3470<h3 id="auto">auto</h3>
3471
3472<div class="summary">
3473<p>Use <code>auto</code> to avoid type names that are noisy, obvious,
3474or unimportant - cases where the type doesn't aid in clarity for the
3475reader. Continue to use manifest type declarations when it helps
3476readability.</p>
3477</div>
3478
3479<div class="stylebody">
3480
3481<div class="pros">
Victor Costan6dfd9d92018-02-05 18:30:35 -08003482
3483<ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003484<li>C++ type names can be long and cumbersome, especially when they
3485involve templates or namespaces.</li>
3486<li>When a C++ type name is repeated within a single declaration or a
3487small code region, the repetition may not be aiding readability.</li>
3488<li>It is sometimes safer to let the type be specified by the type of
3489the initialization expression, since that avoids the possibility of
3490unintended copies or type conversions.</li>
3491</ul>
3492</div>
3493<div class="cons">
3494
3495<p>Sometimes code is clearer when types are manifest,
3496especially when a variable's initialization depends on
3497things that were declared far away. In expressions
3498like:</p>
3499
3500<pre class="badcode">auto foo = x.add_foo();
3501auto i = y.Find(key);
3502</pre>
3503
3504<p>it may not be obvious what the resulting types are if the type
3505of <code>y</code> isn't very well known, or if <code>y</code> was
3506declared many lines earlier.</p>
3507
3508<p>Programmers have to understand the difference between
3509<code>auto</code> and <code>const auto&amp;</code> or
3510they'll get copies when they didn't mean to.</p>
3511
3512<p>If an <code>auto</code> variable is used as part of an
3513interface, e.g. as a constant in a header, then a
3514programmer might change its type while only intending to
3515change its value, leading to a more radical API change
3516than intended.</p>
3517</div>
3518
3519<div class="decision">
3520
3521<p><code>auto</code> is permitted when it increases readability,
3522particularly as described below. Never initialize an <code>auto</code>-typed
3523variable with a braced initializer list.</p>
3524
3525<p>Specific cases where <code>auto</code> is allowed or encouraged:
3526</p><ul>
3527<li>(Encouraged) For iterators and other long/cluttery type names, particularly
3528when the type is clear from context (calls
3529to <code>find</code>, <code>begin</code>, or <code>end</code> for
3530instance).</li>
3531<li>(Allowed) When the type is clear from local context (in the same expression
3532or within a few lines). Initialization of a pointer or smart pointer
3533with calls
3534to <code>new</code>
3535commonly falls into this category, as does use of <code>auto</code> in
3536a range-based loop over a container whose type is spelled out
3537nearby.</li>
3538<li>(Allowed) When the type doesn't matter because it isn't being used for
3539anything other than equality comparison.</li>
3540<li>(Encouraged) When iterating over a map with a range-based loop
3541(because it is often assumed that the correct type
3542is <code>std::pair&lt;KeyType, ValueType&gt;</code> whereas it is actually
3543<code>std::pair&lt;const KeyType, ValueType&gt;</code>). This is
3544particularly well paired with local <code>key</code>
3545and <code>value</code> aliases for <code>.first</code>
3546and <code>.second</code> (often const-ref).
3547<pre class="code">for (const auto&amp; item : some_map) {
3548 const KeyType&amp; key = item.first;
3549 const ValType&amp; value = item.second;
3550 // The rest of the loop can now just refer to key and value,
3551 // a reader can see the types in question, and we've avoided
3552 // the too-common case of extra copies in this iteration.
3553}
3554</pre>
3555</li>
3556</ul>
3557
3558</div>
3559
3560</div>
3561
3562<h3 id="Braced_Initializer_List">Braced Initializer List</h3>
3563
3564<div class="summary">
3565<p>You may use braced initializer lists.</p>
3566</div>
3567
3568<div class="stylebody">
3569
3570<p>In C++03, aggregate types (arrays and structs with no
3571constructor) could be initialized with braced initializer lists.</p>
3572
3573<pre>struct Point { int x; int y; };
3574Point p = {1, 2};
3575</pre>
3576
3577<p>In C++11, this syntax was generalized, and any object type can now
3578be created with a braced initializer list, known as a
3579<i>braced-init-list</i> in the C++ grammar. Here are a few examples
3580of its use.</p>
3581
3582<pre>// Vector takes a braced-init-list of elements.
3583std::vector&lt;string&gt; v{"foo", "bar"};
3584
3585// Basically the same, ignoring some small technicalities.
3586// You may choose to use either form.
3587std::vector&lt;string&gt; v = {"foo", "bar"};
3588
3589// Usable with 'new' expressions.
Victor Costan6dfd9d92018-02-05 18:30:35 -08003590auto p = new std::vector&lt;string&gt;{"foo", "bar"};
Ted Osborne505ba682018-01-30 12:36:50 -05003591
3592// A map can take a list of pairs. Nested braced-init-lists work.
3593std::map&lt;int, string&gt; m = {{1, "one"}, {2, "2"}};
3594
3595// A braced-init-list can be implicitly converted to a return type.
3596std::vector&lt;int&gt; test_function() { return {1, 2, 3}; }
3597
3598// Iterate over a braced-init-list.
3599for (int i : {-1, -2, -3}) {}
3600
3601// Call a function using a braced-init-list.
3602void TestFunction2(std::vector&lt;int&gt; v) {}
3603TestFunction2({1, 2, 3});
3604</pre>
3605
3606<p>A user-defined type can also define a constructor and/or assignment operator
3607that take <code>std::initializer_list&lt;T&gt;</code>, which is automatically
3608created from <i>braced-init-list</i>:</p>
3609
3610<pre>class MyType {
3611 public:
3612 // std::initializer_list references the underlying init list.
3613 // It should be passed by value.
3614 MyType(std::initializer_list&lt;int&gt; init_list) {
3615 for (int i : init_list) append(i);
3616 }
3617 MyType&amp; operator=(std::initializer_list&lt;int&gt; init_list) {
3618 clear();
3619 for (int i : init_list) append(i);
3620 }
3621};
3622MyType m{2, 3, 5, 7};
3623</pre>
3624
3625<p>Finally, brace initialization can also call ordinary
3626constructors of data types, even if they do not have
3627<code>std::initializer_list&lt;T&gt;</code> constructors.</p>
3628
3629<pre>double d{1.23};
3630// Calls ordinary constructor as long as MyOtherType has no
3631// std::initializer_list constructor.
3632class MyOtherType {
3633 public:
3634 explicit MyOtherType(string);
3635 MyOtherType(int, string);
3636};
3637MyOtherType m = {1, "b"};
3638// If the constructor is explicit, you can't use the "= {}" form.
3639MyOtherType m{"b"};
3640</pre>
3641
3642<p>Never assign a <i>braced-init-list</i> to an auto
3643local variable. In the single element case, what this
3644means can be confusing.</p>
3645
3646<pre class="badcode">auto d = {1.23}; // d is a std::initializer_list&lt;double&gt;
3647</pre>
3648
3649<pre>auto d = double{1.23}; // Good -- d is a double, not a std::initializer_list.
3650</pre>
3651
3652<p>See <a href="#Braced_Initializer_List_Format">Braced_Initializer_List_Format</a> for formatting.</p>
3653
3654</div>
3655
3656<h3 id="Lambda_expressions">Lambda expressions</h3>
3657
3658<div class="summary">
3659<p>Use lambda expressions where appropriate. Prefer explicit captures
3660when the lambda will escape the current scope.</p>
3661</div>
3662
3663<div class="stylebody">
3664
3665<div class="definition">
3666
3667<p> Lambda expressions are a concise way of creating anonymous
3668function objects. They're often useful when passing
3669functions as arguments. For example:</p>
3670
3671<pre>std::sort(v.begin(), v.end(), [](int x, int y) {
3672 return Weight(x) &lt; Weight(y);
3673});
3674</pre>
3675
3676<p> They further allow capturing variables from the enclosing scope either
3677explicitly by name, or implicitly using a default capture. Explicit captures
3678require each variable to be listed, as
3679either a value or reference capture:</p>
3680
3681<pre>int weight = 3;
3682int sum = 0;
3683// Captures `weight` by value and `sum` by reference.
3684std::for_each(v.begin(), v.end(), [weight, &amp;sum](int x) {
3685 sum += weight * x;
3686});
3687</pre>
3688
3689
3690Default captures implicitly capture any variable referenced in the
3691lambda body, including <code>this</code> if any members are used:
3692
3693<pre>const std::vector&lt;int&gt; lookup_table = ...;
3694std::vector&lt;int&gt; indices = ...;
3695// Captures `lookup_table` by reference, sorts `indices` by the value
3696// of the associated element in `lookup_table`.
3697std::sort(indices.begin(), indices.end(), [&amp;](int a, int b) {
3698 return lookup_table[a] &lt; lookup_table[b];
3699});
3700</pre>
3701
3702<p>Lambdas were introduced in C++11 along with a set of utilities
3703for working with function objects, such as the polymorphic
3704wrapper <code>std::function</code>.
3705</p>
3706</div>
3707
3708<div class="pros">
3709<ul>
3710 <li>Lambdas are much more concise than other ways of
3711 defining function objects to be passed to STL
3712 algorithms, which can be a readability
3713 improvement.</li>
3714
3715 <li>Appropriate use of default captures can remove
3716 redundancy and highlight important exceptions from
3717 the default.</li>
3718
3719 <li>Lambdas, <code>std::function</code>, and
3720 <code>std::bind</code> can be used in combination as a
3721 general purpose callback mechanism; they make it easy
3722 to write functions that take bound functions as
3723 arguments.</li>
3724</ul>
3725</div>
3726
3727<div class="cons">
3728<ul>
3729 <li>Variable capture in lambdas can be a source of dangling-pointer
3730 bugs, particularly if a lambda escapes the current scope.</li>
3731
3732 <li>Default captures by value can be misleading because they do not prevent
3733 dangling-pointer bugs. Capturing a pointer by value doesn't cause a deep
3734 copy, so it often has the same lifetime issues as capture by reference.
3735 This is especially confusing when capturing 'this' by value, since the use
3736 of 'this' is often implicit.</li>
3737
3738 <li>It's possible for use of lambdas to get out of
3739 hand; very long nested anonymous functions can make
3740 code harder to understand.</li>
3741
3742</ul>
3743</div>
3744
3745<div class="decision">
3746<ul>
3747<li>Use lambda expressions where appropriate, with formatting as
3748described <a href="#Formatting_Lambda_Expressions">below</a>.</li>
3749<li>Prefer explicit captures if the lambda may escape the current scope.
3750For example, instead of:
3751<pre class="badcode">{
3752 Foo foo;
3753 ...
3754 executor-&gt;Schedule([&amp;] { Frobnicate(foo); })
3755 ...
3756}
3757// BAD! The fact that the lambda makes use of a reference to `foo` and
3758// possibly `this` (if `Frobnicate` is a member function) may not be
3759// apparent on a cursory inspection. If the lambda is invoked after
3760// the function returns, that would be bad, because both `foo`
3761// and the enclosing object could have been destroyed.
3762</pre>
3763prefer to write:
3764<pre>{
3765 Foo foo;
3766 ...
3767 executor-&gt;Schedule([&amp;foo] { Frobnicate(foo); })
3768 ...
3769}
3770// BETTER - The compile will fail if `Frobnicate` is a member
3771// function, and it's clearer that `foo` is dangerously captured by
3772// reference.
3773</pre>
3774</li>
3775<li>Use default capture by reference ([&amp;]) only when the
3776lifetime of the lambda is obviously shorter than any potential
3777captures.
3778</li>
3779<li>Use default capture by value ([=]) only as a means of binding a
3780few variables for a short lambda, where the set of captured
3781variables is obvious at a glance. Prefer not to write long or
3782complex lambdas with default capture by value.
3783</li>
3784<li>Keep unnamed lambdas short. If a lambda body is more than
3785maybe five lines long, prefer to give the lambda a name, or to
3786use a named function instead of a lambda.</li>
3787<li>Specify the return type of the lambda explicitly if that will
3788make it more obvious to readers, as with
3789<a href="#auto"><code>auto</code></a>.</li>
3790
3791</ul>
3792</div>
3793
3794</div>
3795
3796<h3 id="Template_metaprogramming">Template metaprogramming</h3>
3797<div class="summary">
3798<p>Avoid complicated template programming.</p>
3799</div>
3800
3801<div class="stylebody">
3802
3803<div class="definition">
3804<p>Template metaprogramming refers to a family of techniques that
3805exploit the fact that the C++ template instantiation mechanism is
3806Turing complete and can be used to perform arbitrary compile-time
3807computation in the type domain.</p>
3808</div>
3809
3810<div class="pros">
3811<p>Template metaprogramming allows extremely flexible interfaces that
3812are type safe and high performance. Facilities like
3813
3814<a href="https://code.google.com/p/googletest/">Google Test</a>,
3815<code>std::tuple</code>, <code>std::function</code>, and
3816Boost.Spirit would be impossible without it.</p>
3817</div>
3818
3819<div class="cons">
3820<p>The techniques used in template metaprogramming are often obscure
3821to anyone but language experts. Code that uses templates in
3822complicated ways is often unreadable, and is hard to debug or
3823maintain.</p>
3824
3825<p>Template metaprogramming often leads to extremely poor compiler
3826time error messages: even if an interface is simple, the complicated
3827implementation details become visible when the user does something
3828wrong.</p>
3829
3830<p>Template metaprogramming interferes with large scale refactoring by
3831making the job of refactoring tools harder. First, the template code
3832is expanded in multiple contexts, and it's hard to verify that the
3833transformation makes sense in all of them. Second, some refactoring
3834tools work with an AST that only represents the structure of the code
3835after template expansion. It can be difficult to automatically work
3836back to the original source construct that needs to be
3837rewritten.</p>
3838</div>
3839
3840<div class="decision">
3841<p>Template metaprogramming sometimes allows cleaner and easier-to-use
3842interfaces than would be possible without it, but it's also often a
3843temptation to be overly clever. It's best used in a small number of
3844low level components where the extra maintenance burden is spread out
3845over a large number of uses.</p>
3846
3847<p>Think twice before using template metaprogramming or other
3848complicated template techniques; think about whether the average
3849member of your team will be able to understand your code well enough
3850to maintain it after you switch to another project, or whether a
3851non-C++ programmer or someone casually browsing the code base will be
3852able to understand the error messages or trace the flow of a function
3853they want to call. If you're using recursive template instantiations
3854or type lists or metafunctions or expression templates, or relying on
3855SFINAE or on the <code>sizeof</code> trick for detecting function
3856overload resolution, then there's a good chance you've gone too
3857far.</p>
3858
3859<p>If you use template metaprogramming, you should expect to put
3860considerable effort into minimizing and isolating the complexity. You
3861should hide metaprogramming as an implementation detail whenever
3862possible, so that user-facing headers are readable, and you should
3863make sure that tricky code is especially well commented. You should
3864carefully document how the code is used, and you should say something
3865about what the "generated" code looks like. Pay extra attention to the
3866error messages that the compiler emits when users make mistakes. The
3867error messages are part of your user interface, and your code should
3868be tweaked as necessary so that the error messages are understandable
3869and actionable from a user point of view.</p>
3870
3871</div>
3872</div>
3873
3874
3875<h3 id="Boost">Boost</h3>
3876
3877<div class="summary">
3878<p>Use only approved libraries from the Boost library
3879collection.</p>
3880</div>
3881
3882<div class="stylebody">
3883
3884<div class="definition">
3885<p> The
3886<a href="https://www.boost.org/">
3887Boost library collection</a> is a popular collection of
3888peer-reviewed, free, open-source C++ libraries.</p>
3889</div>
3890
3891<div class="pros">
3892<p>Boost code is generally very high-quality, is widely
3893portable, and fills many important gaps in the C++
3894standard library, such as type traits and better binders.</p>
3895</div>
3896
3897<div class="cons">
3898<p>Some Boost libraries encourage coding practices which can
3899hamper readability, such as metaprogramming and other
3900advanced template techniques, and an excessively
3901"functional" style of programming. </p>
3902</div>
3903
3904<div class="decision">
3905
3906
3907
3908<div>
3909<p>In order to maintain a high level of readability for
3910all contributors who might read and maintain code, we
3911only allow an approved subset of Boost features.
3912Currently, the following libraries are permitted:</p>
3913
3914<ul>
3915 <li>
3916 <a href="https://www.boost.org/libs/utility/call_traits.htm">
3917 Call Traits</a> from <code>boost/call_traits.hpp</code></li>
3918
3919 <li><a href="https://www.boost.org/libs/utility/compressed_pair.htm">
3920 Compressed Pair</a> from <code>boost/compressed_pair.hpp</code></li>
3921
3922 <li><a href="https://www.boost.org/libs/graph/">
3923 The Boost Graph Library (BGL)</a> from <code>boost/graph</code>,
3924 except serialization (<code>adj_list_serialize.hpp</code>) and
3925 parallel/distributed algorithms and data structures
3926 (<code>boost/graph/parallel/*</code> and
3927 <code>boost/graph/distributed/*</code>).</li>
3928
3929 <li><a href="https://www.boost.org/libs/property_map/">
3930 Property Map</a> from <code>boost/property_map</code>, except
3931 parallel/distributed property maps (<code>boost/property_map/parallel/*</code>).</li>
3932
3933 <li><a href="https://www.boost.org/libs/iterator/">
3934 Iterator</a> from <code>boost/iterator</code></li>
3935
3936 <li>The part of <a href="https://www.boost.org/libs/polygon/">
3937 Polygon</a> that deals with Voronoi diagram
3938 construction and doesn't depend on the rest of
3939 Polygon:
3940 <code>boost/polygon/voronoi_builder.hpp</code>,
3941 <code>boost/polygon/voronoi_diagram.hpp</code>, and
3942 <code>boost/polygon/voronoi_geometry_type.hpp</code></li>
3943
3944 <li><a href="https://www.boost.org/libs/bimap/">
3945 Bimap</a> from <code>boost/bimap</code></li>
3946
3947 <li><a href="https://www.boost.org/libs/math/doc/html/dist.html">
3948 Statistical Distributions and Functions</a> from
3949 <code>boost/math/distributions</code></li>
3950
3951 <li><a href="https://www.boost.org/libs/math/doc/html/special.html">
3952 Special Functions</a> from <code>boost/math/special_functions</code></li>
3953
3954 <li><a href="https://www.boost.org/libs/multi_index/">
3955 Multi-index</a> from <code>boost/multi_index</code></li>
3956
3957 <li><a href="https://www.boost.org/libs/heap/">
3958 Heap</a> from <code>boost/heap</code></li>
3959
3960 <li>The flat containers from
3961 <a href="https://www.boost.org/libs/container/">Container</a>:
3962 <code>boost/container/flat_map</code>, and
3963 <code>boost/container/flat_set</code></li>
3964
3965 <li><a href="https://www.boost.org/libs/intrusive/">Intrusive</a>
3966 from <code>boost/intrusive</code>.</li>
3967
3968 <li><a href="https://www.boost.org/libs/sort/">The
3969 <code>boost/sort</code> library</a>.</li>
3970
3971 <li><a href="https://www.boost.org/libs/preprocessor/">Preprocessor</a>
3972 from <code>boost/preprocessor</code>.</li>
3973</ul>
3974
3975<p>We are actively considering adding other Boost
3976features to the list, so this list may be expanded in
3977the future.</p>
3978</div>
3979
3980<p>The following libraries are permitted, but their use
3981is discouraged because they've been superseded by
3982standard libraries in C++11:</p>
3983
3984<ul>
3985 <li><a href="https://www.boost.org/libs/array/">
3986 Array</a> from <code>boost/array.hpp</code>: use
3987 <a href="http://en.cppreference.com/w/cpp/container/array">
3988 <code>std::array</code></a> instead.</li>
3989
3990 <li><a href="https://www.boost.org/libs/ptr_container/">
3991 Pointer Container</a> from <code>boost/ptr_container</code>: use containers of
3992 <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr">
3993 <code>std::unique_ptr</code></a> instead.</li>
3994</ul>
3995</div>
3996
3997</div>
3998
3999
4000
4001<h3 id="std_hash">std::hash</h3>
4002
4003<div class="summary">
4004<p>Do not define specializations of <code>std::hash</code>.</p>
4005</div>
4006
4007<div class="stylebody">
4008
4009<div class="definition">
4010<p><code>std::hash&lt;T&gt;</code> is the function object that the
4011C++11 hash containers use to hash keys of type <code>T</code>,
4012unless the user explicitly specifies a different hash function. For
4013example, <code>std::unordered_map&lt;int, string&gt;</code> is a hash
4014map that uses <code>std::hash&lt;int&gt;</code> to hash its keys,
4015whereas <code>std::unordered_map&lt;int, string, MyIntHash&gt;</code>
4016uses <code>MyIntHash</code>.</p>
4017
4018<p><code>std::hash</code> is defined for all integral, floating-point,
4019pointer, and <code>enum</code> types, as well as some standard library
4020types such as <code>string</code> and <code>unique_ptr</code>. Users
4021can enable it to work for their own types by defining specializations
4022of it for those types.</p>
4023</div>
4024
4025<div class="pros">
4026<p><code>std::hash</code> is easy to use, and simplifies the code
4027since you don't have to name it explicitly. Specializing
4028<code>std::hash</code> is the standard way of specifying how to
4029hash a type, so it's what outside resources will teach, and what
4030new engineers will expect.</p>
4031</div>
4032
4033<div class="cons">
4034<p><code>std::hash</code> is hard to specialize. It requires a lot
4035of boilerplate code, and more importantly, it combines responsibility
4036for identifying the hash inputs with responsibility for executing the
4037hashing algorithm itself. The type author has to be responsible for
4038the former, but the latter requires expertise that a type author
4039usually doesn't have, and shouldn't need. The stakes here are high
4040because low-quality hash functions can be security vulnerabilities,
4041due to the emergence of
4042<a href="https://emboss.github.io/blog/2012/12/14/breaking-murmur-hash-flooding-dos-reloaded/">
4043hash flooding attacks</a>.</p>
4044
4045<p>Even for experts, <code>std::hash</code> specializations are
4046inordinately difficult to implement correctly for compound types,
4047because the implementation cannot recursively call <code>std::hash</code>
4048on data members. High-quality hash algorithms maintain large
4049amounts of internal state, and reducing that state to the
4050<code>size_t</code> bytes that <code>std::hash</code>
4051returns is usually the slowest part of the computation, so it
4052should not be done more than once.</p>
4053
4054<p>Due to exactly that issue, <code>std::hash</code> does not work
4055with <code>std::pair</code> or <code>std::tuple</code>, and the
4056language does not allow us to extend it to support them.</p>
4057</div>
4058
4059<div class="decision">
4060<p>You can use <code>std::hash</code> with the types that it supports
4061"out of the box", but do not specialize it to support additional types.
4062If you need a hash table with a key type that <code>std::hash</code>
4063does not support, consider using legacy hash containers (e.g.
4064<code>hash_map</code>) for now; they use a different default hasher,
4065which is unaffected by this prohibition.</p>
4066
4067<p>If you want to use the standard hash containers anyway, you will
4068need to specify a custom hasher for the key type, e.g.</p>
4069<pre>std::unordered_map&lt;MyKeyType, Value, MyKeyTypeHasher&gt; my_map;
4070</pre><p>
4071Consult with the type's owners to see if there is an existing hasher
4072that you can use; otherwise work with them to provide one,
4073 or roll your own.</p>
4074
4075<p>We are planning to provide a hash function that can work with any type,
4076using a new customization mechanism that doesn't have the drawbacks of
4077<code>std::hash</code>.</p>
4078</div>
4079
4080</div>
4081
4082<h3 id="C++11">C++11</h3>
4083
4084<div class="summary">
4085<p>Use libraries and language extensions from C++11 when appropriate.
4086Consider portability to other environments
4087before using C++11 features in your
4088project. </p>
4089
4090</div>
4091
4092<div class="stylebody">
4093
4094<div class="definition">
4095<p> C++11 contains <a href="https://en.wikipedia.org/wiki/C%2B%2B11">
4096significant changes</a> both to the language and
4097libraries. </p>
4098</div>
4099
4100<div class="pros">
4101<p>C++11 was the official standard until august 2014, and
4102is supported by most C++ compilers. It standardizes
4103some common C++ extensions that we use already, allows
4104shorthands for some operations, and has some performance
4105and safety improvements.</p>
4106</div>
4107
4108<div class="cons">
4109<p>The C++11 standard is substantially more complex than
4110its predecessor (1,300 pages versus 800 pages), and is
4111unfamiliar to many developers. The long-term effects of
4112some features on code readability and maintenance are
4113unknown. We cannot predict when its various features will
4114be implemented uniformly by tools that may be of
4115interest, particularly in the case of projects that are
4116forced to use older versions of tools.</p>
4117
4118<p>As with <a href="#Boost">Boost</a>, some C++11
4119extensions encourage coding practices that hamper
4120readability&#8212;for example by removing
4121checked redundancy (such as type names) that may be
4122helpful to readers, or by encouraging template
4123metaprogramming. Other extensions duplicate functionality
4124available through existing mechanisms, which may lead to confusion
4125and conversion costs.</p>
4126
4127
4128</div>
4129
4130<div class="decision">
4131
4132<p>C++11 features may be used unless specified otherwise.
4133In addition to what's described in the rest of the style
4134guide, the following C++11 features may not be used:</p>
4135
4136<ul>
4137
4138
4139
4140
4141
4142
4143
4144
4145 <li>Compile-time rational numbers
4146 (<code>&lt;ratio&gt;</code>), because of concerns that
4147 it's tied to a more template-heavy interface
4148 style.</li>
4149
4150 <li>The <code>&lt;cfenv&gt;</code> and
4151 <code>&lt;fenv.h&gt;</code> headers, because many
4152 compilers do not support those features reliably.</li>
4153
4154 <li>Ref-qualifiers on member functions, such as <code>void X::Foo()
4155 &amp;</code> or <code>void X::Foo() &amp;&amp;</code>, because of concerns
4156 that they're an overly obscure feature.</li>
4157
4158
4159
4160
4161</ul>
4162</div>
4163
4164</div>
4165
4166<h3 id="Nonstandard_Extensions">Nonstandard Extensions</h3>
4167
4168<div class="summary">
4169<p>Nonstandard extensions to C++ may not be used unless otherwise specified.</p>
4170</div>
4171<div class="stylebody">
4172<div class="definition">
4173<p>Compilers support various extensions that are not part of standard C++. Such
4174 extensions include GCC's <code>__attribute__</code>, intrinsic functions such
4175 as <code>__builtin_prefetch</code>, designated initializers (e.g.
4176 <code>Foo f = {.field = 3}</code>), inline assembly, <code>__COUNTER__</code>,
4177 <code>__PRETTY_FUNCTION__</code>, compound statement expressions (e.g.
4178 <code>foo = ({ int x; Bar(&amp;x); x })</code>, variable-length arrays and
Victor Costan6dfd9d92018-02-05 18:30:35 -08004179 <code>alloca()</code>, and the "<a href="https://en.wikipedia.org/wiki/Elvis_operator">Elvis Operator</a>"
4180 <code>a?:b</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004181</div>
4182
4183<div class="pros">
4184 <ul>
4185 <li>Nonstandard extensions may provide useful features that do not exist
4186 in standard C++. For example, some people think that designated
4187 initializers are more readable than standard C++ features like
4188 constructors.</li>
4189 <li>Important performance guidance to the compiler can only be specified
4190 using extensions.</li>
4191 </ul>
4192</div>
4193
4194<div class="cons">
4195 <ul>
4196 <li>Nonstandard extensions do not work in all compilers. Use of nonstandard
4197 extensions reduces portability of code.</li>
4198 <li>Even if they are supported in all targeted compilers, the extensions
4199 are often not well-specified, and there may be subtle behavior differences
4200 between compilers.</li>
4201 <li>Nonstandard extensions add to the language features that a reader must
4202 know to understand the code.</li>
4203 </ul>
4204</div>
4205
4206<div class="decision">
4207<p>Do not use nonstandard extensions. You may use portability wrappers that
4208 are implemented using nonstandard extensions, so long as those wrappers
4209
4210 are provided by a designated project-wide
4211 portability header.</p>
4212</div>
4213</div>
4214
4215<h3 id="Aliases">Aliases</h3>
4216
4217<div class="summary">
4218<p>Public aliases are for the benefit of an API's user, and should be clearly documented.</p>
4219</div>
4220<div class="stylebody">
4221<div class="definition">
4222<p>There are several ways to create names that are aliases of other entities:</p>
4223<pre>typedef Foo Bar;
4224using Bar = Foo;
4225using other_namespace::Foo;
4226</pre>
4227
Victor Costan6dfd9d92018-02-05 18:30:35 -08004228 <p>In new code, <code>using</code> is preferable to <code>typedef</code>,
4229 because it provides a more consistent syntax with the rest of C++ and works
4230 with templates.</p>
4231
Ted Osborne505ba682018-01-30 12:36:50 -05004232 <p>Like other declarations, aliases declared in a header file are part of that
4233 header's public API unless they're in a function definition, in the private portion of a class,
4234 or in an explicitly-marked internal namespace. Aliases in such areas or in .cc files are
4235 implementation details (because client code can't refer to them), and are not restricted by this
4236 rule.</p>
4237</div>
4238
4239<div class="pros">
4240 <ul>
4241 <li>Aliases can improve readability by simplifying a long or complicated name.</li>
4242 <li>Aliases can reduce duplication by naming in one place a type used repeatedly in an API,
4243 which <em>might</em> make it easier to change the type later.
4244 </li>
4245 </ul>
4246</div>
4247
4248<div class="cons">
4249 <ul>
4250 <li>When placed in a header where client code can refer to them, aliases increase the
4251 number of entities in that header's API, increasing its complexity.</li>
4252 <li>Clients can easily rely on unintended details of public aliases, making
4253 changes difficult.</li>
4254 <li>It can be tempting to create a public alias that is only intended for use
4255 in the implementation, without considering its impact on the API, or on maintainability.</li>
4256 <li>Aliases can create risk of name collisions</li>
4257 <li>Aliases can reduce readability by giving a familiar construct an unfamiliar name</li>
4258 <li>Type aliases can create an unclear API contract:
4259 it is unclear whether the alias is guaranteed to be identical to the type it aliases,
4260 to have the same API, or only to be usable in specified narrow ways</li>
4261 </ul>
4262</div>
4263
4264<div class="decision">
4265<p>Don't put an alias in your public API just to save typing in the implementation;
4266 do so only if you intend it to be used by your clients.</p>
4267<p>When defining a public alias, document the intent of
4268the new name, including whether it is guaranteed to always be the same as the type
4269it's currently aliased to, or whether a more limited compatibility is
4270intended. This lets the user know whether they can treat the types as
4271substitutable or whether more specific rules must be followed, and can help the
4272implementation retain some degree of freedom to change the alias.</p>
4273<p>Don't put namespace aliases in your public API. (See also <a href="#Namespaces">Namespaces</a>).
4274</p>
4275
4276<p>For example, these aliases document how they are intended to be used in client code:</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08004277<pre>namespace mynamespace {
Ted Osborne505ba682018-01-30 12:36:50 -05004278// Used to store field measurements. DataPoint may change from Bar* to some internal type.
4279// Client code should treat it as an opaque pointer.
Victor Costan6dfd9d92018-02-05 18:30:35 -08004280using DataPoint = foo::Bar*;
Ted Osborne505ba682018-01-30 12:36:50 -05004281
4282// A set of measurements. Just an alias for user convenience.
4283using TimeSeries = std::unordered_set&lt;DataPoint, std::hash&lt;DataPoint&gt;, DataPointComparator&gt;;
Victor Costan6dfd9d92018-02-05 18:30:35 -08004284} // namespace mynamespace
Ted Osborne505ba682018-01-30 12:36:50 -05004285</pre>
4286
4287<p>These aliases don't document intended use, and half of them aren't meant for client use:</p>
4288
Victor Costan6dfd9d92018-02-05 18:30:35 -08004289<pre class="badcode">namespace mynamespace {
Ted Osborne505ba682018-01-30 12:36:50 -05004290// Bad: none of these say how they should be used.
Victor Costan6dfd9d92018-02-05 18:30:35 -08004291using DataPoint = foo::Bar*;
Ted Osborne505ba682018-01-30 12:36:50 -05004292using std::unordered_set; // Bad: just for local convenience
4293using std::hash; // Bad: just for local convenience
4294typedef unordered_set&lt;DataPoint, hash&lt;DataPoint&gt;, DataPointComparator&gt; TimeSeries;
Victor Costan6dfd9d92018-02-05 18:30:35 -08004295} // namespace mynamespace
Ted Osborne505ba682018-01-30 12:36:50 -05004296</pre>
4297
4298<p>However, local convenience aliases are fine in function definitions, private sections of
4299 classes, explicitly marked internal namespaces, and in .cc files:</p>
4300
4301<pre>// In a .cc file
Victor Costan6dfd9d92018-02-05 18:30:35 -08004302using foo::Bar;
Ted Osborne505ba682018-01-30 12:36:50 -05004303</pre>
4304
4305</div>
4306</div>
4307
4308<h2 id="Naming">Naming</h2>
4309
4310<p>The most important consistency rules are those that govern
4311naming. The style of a name immediately informs us what sort of
4312thing the named entity is: a type, a variable, a function, a
4313constant, a macro, etc., without requiring us to search for the
4314declaration of that entity. The pattern-matching engine in our
4315brains relies a great deal on these naming rules.
4316</p>
4317
4318<p>Naming rules are pretty arbitrary, but
4319 we feel that
4320consistency is more important than individual preferences in this
4321area, so regardless of whether you find them sensible or not,
4322the rules are the rules.</p>
4323
4324<h3 id="General_Naming_Rules">General Naming Rules</h3>
4325
4326<div class="summary">
4327<p>Names should be descriptive; avoid abbreviation.</p>
4328</div>
4329
4330<div class="stylebody">
4331<p>Give as descriptive a name as possible, within reason.
4332Do not worry about saving horizontal space as it is far
4333more important to make your code immediately
4334understandable by a new reader. Do not use abbreviations
4335that are ambiguous or unfamiliar to readers outside your
4336project, and do not abbreviate by deleting letters within
Victor Costan6dfd9d92018-02-05 18:30:35 -08004337a word. Abbreviations that would be familiar to someone
4338outside your project with relevant domain knowledge are OK.
4339As a rule of thumb, an abbreviation is probably OK if it's listed
4340in
4341
4342Wikipedia.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004343
4344<pre>int price_count_reader; // No abbreviation.
4345int num_errors; // "num" is a widespread convention.
4346int num_dns_connections; // Most people know what "DNS" stands for.
Victor Costan6dfd9d92018-02-05 18:30:35 -08004347int lstm_size; // "LSTM" is a common machine learning abbreviation.
Ted Osborne505ba682018-01-30 12:36:50 -05004348</pre>
4349
4350<pre class="badcode">int n; // Meaningless.
4351int nerr; // Ambiguous abbreviation.
4352int n_comp_conns; // Ambiguous abbreviation.
4353int wgc_connections; // Only your group knows what this stands for.
4354int pc_reader; // Lots of things can be abbreviated "pc".
4355int cstmr_id; // Deletes internal letters.
Victor Costan6dfd9d92018-02-05 18:30:35 -08004356FooBarRequestInfo fbri; // Not even a word.
Ted Osborne505ba682018-01-30 12:36:50 -05004357</pre>
4358
4359<p>Note that certain universally-known abbreviations are OK, such as
4360<code>i</code> for an iteration variable and <code>T</code> for a
4361template parameter.</p>
4362
Victor Costan6dfd9d92018-02-05 18:30:35 -08004363<p>For some symbols, this style guide recommends names to start with a capital
4364letter and to have a capital letter for each new word (a.k.a.
4365"<a href="https://en.wikipedia.org/wiki/Camel_case">Camel Case</a>"
4366or "Pascal case"). When abbreviations appear in such names, prefer to
4367capitalize the abbreviations as single words (i.e. <code>StartRpc()</code>,
4368not <code>StartRPC()</code>).</p>
4369
Ted Osborne505ba682018-01-30 12:36:50 -05004370<p>Template parameters should follow the naming style for their
4371category: type template parameters should follow the rules for
4372<a href="#Type_Names">type names</a>, and non-type template
4373parameters should follow the rules for <a href="#Variable_Names">
4374variable names</a>.
4375
4376</p></div>
4377
4378<h3 id="File_Names">File Names</h3>
4379
4380<div class="summary">
4381<p>Filenames should be all lowercase and can include
4382underscores (<code>_</code>) or dashes (<code>-</code>).
4383Follow the convention that your
4384
4385project uses. If there is no consistent
4386local pattern to follow, prefer "_".</p>
4387</div>
4388
4389<div class="stylebody">
4390
4391<p>Examples of acceptable file names:</p>
4392
4393<ul>
4394 <li><code>my_useful_class.cc</code></li>
4395 <li><code>my-useful-class.cc</code></li>
4396 <li><code>myusefulclass.cc</code></li>
4397 <li><code>myusefulclass_test.cc // _unittest and _regtest are deprecated.</code></li>
4398</ul>
4399
4400<p>C++ files should end in <code>.cc</code> and header files should end in
4401<code>.h</code>. Files that rely on being textually included at specific points
4402should end in <code>.inc</code> (see also the section on
4403<a href="#Self_contained_Headers">self-contained headers</a>).</p>
4404
4405<p>Do not use filenames that already exist in
4406<code>/usr/include</code>, such as <code>db.h</code>.</p>
4407
4408<p>In general, make your filenames very specific. For
4409example, use <code>http_server_logs.h</code> rather than
4410<code>logs.h</code>. A very common case is to have a pair
4411of files called, e.g., <code>foo_bar.h</code> and
4412<code>foo_bar.cc</code>, defining a class called
4413<code>FooBar</code>.</p>
4414
4415<p>Inline functions must be in a <code>.h</code> file. If
4416your inline functions are very short, they should go
4417directly into your <code>.h</code> file. </p>
4418
4419</div>
4420
4421<h3 id="Type_Names">Type Names</h3>
4422
4423<div class="summary">
4424<p>Type names start with a capital letter and have a capital
4425letter for each new word, with no underscores:
4426<code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.</p>
4427</div>
4428
4429<div class="stylebody">
4430
4431<p>The names of all types &#8212; classes, structs, type aliases,
4432enums, and type template parameters &#8212; have the same naming convention.
4433Type names should start with a capital letter and have a capital letter
4434for each new word. No underscores. For example:</p>
4435
4436<pre>// classes and structs
4437class UrlTable { ...
4438class UrlTableTester { ...
4439struct UrlTableProperties { ...
4440
4441// typedefs
4442typedef hash_map&lt;UrlTableProperties *, string&gt; PropertiesMap;
4443
4444// using aliases
4445using PropertiesMap = hash_map&lt;UrlTableProperties *, string&gt;;
4446
4447// enums
4448enum UrlTableErrors { ...
4449</pre>
4450
4451</div>
4452
4453<h3 id="Variable_Names">Variable Names</h3>
4454
4455<div class="summary">
4456<p>The names of variables (including function parameters) and data members are
4457all lowercase, with underscores between words. Data members of classes (but not
4458structs) additionally have trailing underscores. For instance:
4459<code>a_local_variable</code>, <code>a_struct_data_member</code>,
4460<code>a_class_data_member_</code>.</p>
4461</div>
4462
4463<div class="stylebody">
4464
4465<h4 class="stylepoint_subsection">Common Variable names</h4>
4466
4467<p>For example:</p>
4468
4469<pre>string table_name; // OK - uses underscore.
4470string tablename; // OK - all lowercase.
4471</pre>
4472
4473<pre class="badcode">string tableName; // Bad - mixed case.
4474</pre>
4475
4476<h4 class="stylepoint_subsection">Class Data Members</h4>
4477
4478<p>Data members of classes, both static and non-static, are
4479named like ordinary nonmember variables, but with a
4480trailing underscore.</p>
4481
4482<pre>class TableInfo {
4483 ...
4484 private:
4485 string table_name_; // OK - underscore at end.
4486 string tablename_; // OK.
4487 static Pool&lt;TableInfo&gt;* pool_; // OK.
4488};
4489</pre>
4490
4491<h4 class="stylepoint_subsection">Struct Data Members</h4>
4492
4493<p>Data members of structs, both static and non-static,
4494are named like ordinary nonmember variables. They do not have
4495the trailing underscores that data members in classes have.</p>
4496
4497<pre>struct UrlTableProperties {
4498 string name;
4499 int num_entries;
4500 static Pool&lt;UrlTableProperties&gt;* pool;
4501};
4502</pre>
4503
4504
4505<p>See <a href="#Structs_vs._Classes">Structs vs.
4506Classes</a> for a discussion of when to use a struct
4507versus a class.</p>
4508
4509</div>
4510
4511<h3 id="Constant_Names">Constant Names</h3>
4512
4513<div class="summary">
4514 <p>Variables declared constexpr or const, and whose value is fixed for
4515 the duration of the program, are named with a leading "k" followed
4516 by mixed case. For example:</p>
4517</div>
4518
4519<pre>const int kDaysInAWeek = 7;
4520</pre>
4521
4522<div class="stylebody">
4523
4524 <p>All such variables with static storage duration (i.e. statics and globals,
4525 see <a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration">
4526 Storage Duration</a> for details) should be named this way. This
4527 convention is optional for variables of other storage classes, e.g. automatic
Victor Costan6dfd9d92018-02-05 18:30:35 -08004528 variables, otherwise the usual variable naming rules apply.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004529
Victor Costan6dfd9d92018-02-05 18:30:35 -08004530</div>
Ted Osborne505ba682018-01-30 12:36:50 -05004531
4532<h3 id="Function_Names">Function Names</h3>
4533
4534<div class="summary">
4535<p>Regular functions have mixed case; accessors and mutators may be named
4536like variables.</p>
4537</div>
4538
4539<div class="stylebody">
4540
4541<p>Ordinarily, functions should start with a capital letter and have a
Victor Costan6dfd9d92018-02-05 18:30:35 -08004542capital letter for each new word.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004543
4544<pre>AddTableEntry()
4545DeleteUrl()
4546OpenFileOrDie()
4547</pre>
4548
4549<p>(The same naming rule applies to class- and namespace-scope
4550constants that are exposed as part of an API and that are intended to look
Victor Costan6dfd9d92018-02-05 18:30:35 -08004551like functions, because the fact that they're objects rather than functions
4552is an unimportant implementation detail.)</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004553
4554<p>Accessors and mutators (get and set functions) may be named like
4555variables. These often correspond to actual member variables, but this is
4556not required. For example, <code>int count()</code> and <code>void
4557set_count(int count)</code>.</p>
4558
4559</div>
4560
4561<h3 id="Namespace_Names">Namespace Names</h3>
4562
4563<div class="summary">
4564Namespace names are all lower-case. Top-level namespace names are
4565based on the project name
4566. Avoid collisions
4567between nested namespaces and well-known top-level namespaces.
4568</div>
4569
4570<div class="stylebody">
4571<p>The name of a top-level namespace should usually be the
4572name of the project or team whose code is contained in that
4573namespace. The code in that namespace should usually be in
Victor Costan6dfd9d92018-02-05 18:30:35 -08004574a directory whose basename matches the namespace name (or in
Ted Osborne505ba682018-01-30 12:36:50 -05004575subdirectories thereof).</p>
4576
4577
4578
4579
4580
4581<p>Keep in mind that the <a href="#General_Naming_Rules">rule
4582against abbreviated names</a> applies to namespaces just as much
4583as variable names. Code inside the namespace seldom needs to
4584mention the namespace name, so there's usually no particular need
4585for abbreviation anyway.</p>
4586
4587<p>Avoid nested namespaces that match well-known top-level
4588namespaces. Collisions between namespace names can lead to surprising
4589build breaks because of name lookup rules. In particular, do not
4590create any nested <code>std</code> namespaces. Prefer unique project
4591identifiers
4592(<code>websearch::index</code>, <code>websearch::index_util</code>)
4593over collision-prone names like <code>websearch::util</code>.</p>
4594
4595<p>For <code>internal</code> namespaces, be wary of other code being
4596added to the same <code>internal</code> namespace causing a collision
4597(internal helpers within a team tend to be related and may lead to
4598collisions). In such a situation, using the filename to make a unique
4599internal name is helpful
4600(<code>websearch::index::frobber_internal</code> for use
4601in <code>frobber.h</code>)</p>
4602
4603</div>
4604
4605<h3 id="Enumerator_Names">Enumerator Names</h3>
4606
4607<div class="summary">
4608<p>Enumerators (for both scoped and unscoped enums) should be named <i>either</i> like
4609<a href="#Constant_Names">constants</a> or like
4610<a href="#Macro_Names">macros</a>: either <code>kEnumName</code> or
4611<code>ENUM_NAME</code>.</p>
4612</div>
4613
4614<div class="stylebody">
4615
4616<p>Preferably, the individual enumerators should be named
4617like <a href="#Constant_Names">constants</a>. However, it
4618is also acceptable to name them like
4619<a href="#Macro_Names">macros</a>. The enumeration name,
4620<code>UrlTableErrors</code> (and
4621<code>AlternateUrlTableErrors</code>), is a type, and
4622therefore mixed case.</p>
4623
4624<pre>enum UrlTableErrors {
4625 kOK = 0,
4626 kErrorOutOfMemory,
4627 kErrorMalformedInput,
4628};
4629enum AlternateUrlTableErrors {
4630 OK = 0,
4631 OUT_OF_MEMORY = 1,
4632 MALFORMED_INPUT = 2,
4633};
4634</pre>
4635
4636<p>Until January 2009, the style was to name enum values
4637like <a href="#Macro_Names">macros</a>. This caused
4638problems with name collisions between enum values and
4639macros. Hence, the change to prefer constant-style naming
4640was put in place. New code should prefer constant-style
4641naming if possible. However, there is no reason to change
4642old code to use constant-style names, unless the old
4643names are actually causing a compile-time problem.</p>
4644
4645
4646
4647</div>
4648
4649<h3 id="Macro_Names">Macro Names</h3>
4650
4651<div class="summary">
4652<p>You're not really going to <a href="#Preprocessor_Macros">
4653define a macro</a>, are you? If you do, they're like this:
Victor Costan6dfd9d92018-02-05 18:30:35 -08004654<code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN_AND_ADULTS_ALIKE</code>.
4655</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004656</div>
4657
4658<div class="stylebody">
4659
4660<p>Please see the <a href="#Preprocessor_Macros">description
4661of macros</a>; in general macros should <em>not</em> be used.
4662However, if they are absolutely needed, then they should be
4663named with all capitals and underscores.</p>
4664
4665<pre>#define ROUND(x) ...
4666#define PI_ROUNDED 3.0
4667</pre>
4668
4669</div>
4670
4671<h3 id="Exceptions_to_Naming_Rules">Exceptions to Naming Rules</h3>
4672
4673<div class="summary">
4674<p>If you are naming something that is analogous to an
4675existing C or C++ entity then you can follow the existing
4676naming convention scheme.</p>
4677</div>
4678
4679<div class="stylebody">
4680
4681<dl>
4682 <dt><code>bigopen()</code></dt>
4683 <dd>function name, follows form of <code>open()</code></dd>
4684
4685 <dt><code>uint</code></dt>
4686 <dd><code>typedef</code></dd>
4687
4688 <dt><code>bigpos</code></dt>
4689 <dd><code>struct</code> or <code>class</code>, follows
4690 form of <code>pos</code></dd>
4691
4692 <dt><code>sparse_hash_map</code></dt>
4693 <dd>STL-like entity; follows STL naming conventions</dd>
4694
4695 <dt><code>LONGLONG_MAX</code></dt>
4696 <dd>a constant, as in <code>INT_MAX</code></dd>
4697</dl>
4698
4699</div>
4700
4701<h2 id="Comments">Comments</h2>
4702
4703<p>Though a pain to write, comments are absolutely vital to
4704keeping our code readable. The following rules describe what
4705you should comment and where. But remember: while comments are
4706very important, the best code is self-documenting. Giving
4707sensible names to types and variables is much better than using
4708obscure names that you must then explain through comments.</p>
4709
4710<p>When writing your comments, write for your audience: the
4711next
4712contributor who will need to
4713understand your code. Be generous &#8212; the next
4714one may be you!</p>
4715
4716<h3 id="Comment_Style">Comment Style</h3>
4717
4718<div class="summary">
4719<p>Use either the <code>//</code> or <code>/* */</code>
4720syntax, as long as you are consistent.</p>
4721</div>
4722
4723<div class="stylebody">
4724
4725<p>You can use either the <code>//</code> or the <code>/*
4726*/</code> syntax; however, <code>//</code> is
4727<em>much</em> more common. Be consistent with how you
4728comment and what style you use where.</p>
4729
4730</div>
4731
4732<h3 id="File_Comments">File Comments</h3>
4733
4734<div class="summary">
4735<p>Start each file with license boilerplate.</p>
4736
4737<p>File comments describe the contents of a file. If a file declares,
4738implements, or tests exactly one abstraction that is documented by a comment
4739at the point of declaration, file comments are not required. All other files
4740must have file comments.</p>
4741
4742</div>
4743
4744<div class="stylebody">
4745
4746<h4 class="stylepoint_subsection">Legal Notice and Author
4747Line</h4>
4748
4749
4750
4751<p>Every file should contain license
4752boilerplate. Choose the appropriate boilerplate for the
4753license used by the project (for example, Apache 2.0,
4754BSD, LGPL, GPL).</p>
4755
4756<p>If you make significant changes to a file with an
Victor Costan6dfd9d92018-02-05 18:30:35 -08004757author line, consider deleting the author line.
4758New files should usually not contain copyright notice or
4759author line.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004760
4761<h4 class="stylepoint_subsection">File Contents</h4>
4762
4763<p>If a <code>.h</code> declares multiple abstractions, the file-level comment
4764should broadly describe the contents of the file, and how the abstractions are
4765related. A 1 or 2 sentence file-level comment may be sufficient. The detailed
4766documentation about individual abstractions belongs with those abstractions,
4767not at the file level.</p>
4768
4769<p>Do not duplicate comments in both the <code>.h</code> and the
4770<code>.cc</code>. Duplicated comments diverge.</p>
4771
4772</div>
4773
4774<h3 id="Class_Comments">Class Comments</h3>
4775
4776<div class="summary">
4777<p>Every non-obvious class declaration should have an accompanying
4778comment that describes what it is for and how it should be used.</p>
4779</div>
4780
4781<div class="stylebody">
4782
4783<pre>// Iterates over the contents of a GargantuanTable.
4784// Example:
4785// GargantuanTableIterator* iter = table-&gt;NewIterator();
4786// for (iter-&gt;Seek("foo"); !iter-&gt;done(); iter-&gt;Next()) {
4787// process(iter-&gt;key(), iter-&gt;value());
4788// }
4789// delete iter;
4790class GargantuanTableIterator {
4791 ...
4792};
4793</pre>
4794
4795<p>The class comment should provide the reader with enough information to know
4796how and when to use the class, as well as any additional considerations
4797necessary to correctly use the class. Document the synchronization assumptions
4798the class makes, if any. If an instance of the class can be accessed by
4799multiple threads, take extra care to document the rules and invariants
4800surrounding multithreaded use.</p>
4801
4802<p>The class comment is often a good place for a small example code snippet
4803demonstrating a simple and focused usage of the class.</p>
4804
4805<p>When sufficiently separated (e.g. <code>.h</code> and <code>.cc</code>
4806files), comments describing the use of the class should go together with its
4807interface definition; comments about the class operation and implementation
4808should accompany the implementation of the class's methods.</p>
4809
4810</div>
4811
4812<h3 id="Function_Comments">Function Comments</h3>
4813
4814<div class="summary">
4815<p>Declaration comments describe use of the function (when it is
4816non-obvious); comments at the definition of a function describe
4817operation.</p>
4818</div>
4819
4820<div class="stylebody">
4821
4822<h4 class="stylepoint_subsection">Function Declarations</h4>
4823
4824<p>Almost every function declaration should have comments immediately
4825preceding it that describe what the function does and how to use
4826it. These comments may be omitted only if the function is simple and
4827obvious (e.g. simple accessors for obvious properties of the
4828class). These comments should be descriptive ("Opens the file")
4829rather than imperative ("Open the file"); the comment describes the
4830function, it does not tell the function what to do. In general, these
4831comments do not describe how the function performs its task. Instead,
4832that should be left to comments in the function definition.</p>
4833
4834<p>Types of things to mention in comments at the function
4835declaration:</p>
4836
4837<ul>
4838 <li>What the inputs and outputs are.</li>
4839
4840 <li>For class member functions: whether the object
4841 remembers reference arguments beyond the duration of
4842 the method call, and whether it will free them or
4843 not.</li>
4844
4845 <li>If the function allocates memory that the caller
4846 must free.</li>
4847
4848 <li>Whether any of the arguments can be a null
4849 pointer.</li>
4850
4851 <li>If there are any performance implications of how a
4852 function is used.</li>
4853
4854 <li>If the function is re-entrant. What are its
4855 synchronization assumptions?</li>
4856 </ul>
4857
4858<p>Here is an example:</p>
4859
4860<pre>// Returns an iterator for this table. It is the client's
4861// responsibility to delete the iterator when it is done with it,
4862// and it must not use the iterator once the GargantuanTable object
4863// on which the iterator was created has been deleted.
4864//
4865// The iterator is initially positioned at the beginning of the table.
4866//
4867// This method is equivalent to:
4868// Iterator* iter = table-&gt;NewIterator();
4869// iter-&gt;Seek("");
4870// return iter;
4871// If you are going to immediately seek to another place in the
4872// returned iterator, it will be faster to use NewIterator()
4873// and avoid the extra seek.
4874Iterator* GetIterator() const;
4875</pre>
4876
4877<p>However, do not be unnecessarily verbose or state the
Victor Costan6dfd9d92018-02-05 18:30:35 -08004878completely obvious.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004879
4880<p>When documenting function overrides, focus on the
4881specifics of the override itself, rather than repeating
4882the comment from the overridden function. In many of these
4883cases, the override needs no additional documentation and
4884thus no comment is required.</p>
4885
4886<p>When commenting constructors and destructors, remember
4887that the person reading your code knows what constructors
4888and destructors are for, so comments that just say
4889something like "destroys this object" are not useful.
4890Document what constructors do with their arguments (for
4891example, if they take ownership of pointers), and what
4892cleanup the destructor does. If this is trivial, just
4893skip the comment. It is quite common for destructors not
4894to have a header comment.</p>
4895
4896<h4 class="stylepoint_subsection">Function Definitions</h4>
4897
4898<p>If there is anything tricky about how a function does
4899its job, the function definition should have an
4900explanatory comment. For example, in the definition
4901comment you might describe any coding tricks you use,
4902give an overview of the steps you go through, or explain
4903why you chose to implement the function in the way you
4904did rather than using a viable alternative. For instance,
4905you might mention why it must acquire a lock for the
4906first half of the function but why it is not needed for
4907the second half.</p>
4908
4909<p>Note you should <em>not</em> just repeat the comments
4910given with the function declaration, in the
4911<code>.h</code> file or wherever. It's okay to
4912recapitulate briefly what the function does, but the
4913focus of the comments should be on how it does it.</p>
4914
4915</div>
4916
4917<h3 id="Variable_Comments">Variable Comments</h3>
4918
4919<div class="summary">
4920<p>In general the actual name of the variable should be
4921descriptive enough to give a good idea of what the variable
4922is used for. In certain cases, more comments are required.</p>
4923</div>
4924
4925<div class="stylebody">
4926
4927<h4 class="stylepoint_subsection">Class Data Members</h4>
4928
4929<p>The purpose of each class data member (also called an instance
4930variable or member variable) must be clear. If there are any
4931invariants (special values, relationships between members, lifetime
4932requirements) not clearly expressed by the type and name, they must be
4933commented. However, if the type and name suffice (<code>int
4934num_events_;</code>), no comment is needed.</p>
4935
4936<p>In particular, add comments to describe the existence and meaning
4937of sentinel values, such as nullptr or -1, when they are not
4938obvious. For example:</p>
4939
4940<pre>private:
4941 // Used to bounds-check table accesses. -1 means
4942 // that we don't yet know how many entries the table has.
4943 int num_total_entries_;
4944</pre>
4945
4946<h4 class="stylepoint_subsection">Global Variables</h4>
4947
4948<p>All global variables should have a comment describing what they
4949are, what they are used for, and (if unclear) why it needs to be
4950global. For example:</p>
4951
4952<pre>// The total number of tests cases that we run through in this regression test.
4953const int kNumTestCases = 6;
4954</pre>
4955
4956</div>
4957
4958<h3 id="Implementation_Comments">Implementation Comments</h3>
4959
4960<div class="summary">
4961<p>In your implementation you should have comments in tricky,
4962non-obvious, interesting, or important parts of your code.</p>
4963</div>
4964
4965<div class="stylebody">
4966
4967<h4 class="stylepoint_subsection">Explanatory Comments</h4>
4968
4969<p>Tricky or complicated code blocks should have comments
4970before them. Example:</p>
4971
4972<pre>// Divide result by two, taking into account that x
4973// contains the carry from the add.
4974for (int i = 0; i &lt; result-&gt;size(); i++) {
4975 x = (x &lt;&lt; 8) + (*result)[i];
4976 (*result)[i] = x &gt;&gt; 1;
4977 x &amp;= 1;
4978}
4979</pre>
4980
4981<h4 class="stylepoint_subsection">Line Comments</h4>
4982
4983<p>Also, lines that are non-obvious should get a comment
4984at the end of the line. These end-of-line comments should
4985be separated from the code by 2 spaces. Example:</p>
4986
4987<pre>// If we have enough memory, mmap the data portion too.
4988mmap_budget = max&lt;int64&gt;(0, mmap_budget - index_-&gt;length());
4989if (mmap_budget &gt;= data_size_ &amp;&amp; !MmapData(mmap_chunk_bytes, mlock))
4990 return; // Error already logged.
4991</pre>
4992
4993<p>Note that there are both comments that describe what
4994the code is doing, and comments that mention that an
4995error has already been logged when the function
4996returns.</p>
4997
4998<p>If you have several comments on subsequent lines, it
4999can often be more readable to line them up:</p>
5000
5001<pre>DoSomething(); // Comment here so the comments line up.
5002DoSomethingElseThatIsLonger(); // Two spaces between the code and the comment.
5003{ // One space before comment when opening a new scope is allowed,
5004 // thus the comment lines up with the following comments and code.
5005 DoSomethingElse(); // Two spaces before line comments normally.
5006}
5007std::vector&lt;string&gt; list{
5008 // Comments in braced lists describe the next element...
5009 "First item",
5010 // .. and should be aligned appropriately.
5011 "Second item"};
5012DoSomething(); /* For trailing block comments, one space is fine. */
5013</pre>
5014
5015<h4 class="stylepoint_subsection">Function Argument Comments</h4>
5016
5017<p>When the meaning of a function argument is nonobvious, consider
5018one of the following remedies:</p>
5019
5020<ul>
5021 <li>If the argument is a literal constant, and the same constant is
5022 used in multiple function calls in a way that tacitly assumes they're
5023 the same, you should use a named constant to make that constraint
5024 explicit, and to guarantee that it holds.</li>
5025
5026 <li>Consider changing the function signature to replace a <code>bool</code>
5027 argument with an <code>enum</code> argument. This will make the argument
5028 values self-describing.</li>
5029
5030 <li>For functions that have several configuration options, consider
5031 defining a single class or struct to hold all the options
5032 ,
5033 and pass an instance of that.
5034 This approach has several advantages. Options are referenced by name
5035 at the call site, which clarifies their meaning. It also reduces
5036 function argument count, which makes function calls easier to read and
5037 write. As an added benefit, you don't have to change call sites when
5038 you add another option.
5039 </li>
5040
5041 <li>Replace large or complex nested expressions with named variables.</li>
5042
5043 <li>As a last resort, use comments to clarify argument meanings at the
Victor Costan6dfd9d92018-02-05 18:30:35 -08005044 call site. </li>
Ted Osborne505ba682018-01-30 12:36:50 -05005045</ul>
5046
5047Consider the following example:
5048
5049<pre class="badcode">// What are these arguments?
5050const DecimalNumber product = CalculateProduct(values, 7, false, nullptr);
5051</pre>
5052
5053<p>versus:</p>
5054
5055<pre>ProductOptions options;
5056options.set_precision_decimals(7);
5057options.set_use_cache(ProductOptions::kDontUseCache);
5058const DecimalNumber product =
5059 CalculateProduct(values, options, /*completion_callback=*/nullptr);
5060</pre>
5061
5062<h4 class="stylepoint_subsection">Don'ts</h4>
5063
5064<p>Do not state the obvious. In particular, don't literally describe what
5065code does, unless the behavior is nonobvious to a reader who understands
5066C++ well. Instead, provide higher level comments that describe <i>why</i>
5067the code does what it does, or make the code self describing.</p>
5068
5069Compare this:
5070
5071<pre class="badcode">// Find the element in the vector. &lt;-- Bad: obvious!
5072auto iter = std::find(v.begin(), v.end(), element);
5073if (iter != v.end()) {
5074 Process(element);
5075}
5076</pre>
5077
5078To this:
5079
5080<pre>// Process "element" unless it was already processed.
5081auto iter = std::find(v.begin(), v.end(), element);
5082if (iter != v.end()) {
5083 Process(element);
5084}
5085</pre>
5086
5087Self-describing code doesn't need a comment. The comment from
5088the example above would be obvious:
5089
5090<pre>if (!IsAlreadyProcessed(element)) {
5091 Process(element);
5092}
5093</pre>
5094
5095</div>
5096
5097<h3 id="Punctuation,_Spelling_and_Grammar">Punctuation, Spelling and Grammar</h3>
5098
5099<div class="summary">
5100<p>Pay attention to punctuation, spelling, and grammar; it is
5101easier to read well-written comments than badly written
5102ones.</p>
5103</div>
5104
5105<div class="stylebody">
5106
5107<p>Comments should be as readable as narrative text, with
5108proper capitalization and punctuation. In many cases,
5109complete sentences are more readable than sentence
5110fragments. Shorter comments, such as comments at the end
5111of a line of code, can sometimes be less formal, but you
5112should be consistent with your style.</p>
5113
5114<p>Although it can be frustrating to have a code reviewer
5115point out that you are using a comma when you should be
5116using a semicolon, it is very important that source code
5117maintain a high level of clarity and readability. Proper
5118punctuation, spelling, and grammar help with that
5119goal.</p>
5120
5121</div>
5122
5123<h3 id="TODO_Comments">TODO Comments</h3>
5124
5125<div class="summary">
5126<p>Use <code>TODO</code> comments for code that is temporary,
5127a short-term solution, or good-enough but not perfect.</p>
5128</div>
5129
5130<div class="stylebody">
5131
5132<p><code>TODO</code>s should include the string
5133<code>TODO</code> in all caps, followed by the
5134
5135name, e-mail address, bug ID, or other
5136identifier
5137of the person or issue with the best context
5138about the problem referenced by the <code>TODO</code>. The
5139main purpose is to have a consistent <code>TODO</code> that
5140can be searched to find out how to get more details upon
5141request. A <code>TODO</code> is not a commitment that the
5142person referenced will fix the problem. Thus when you create
5143a <code>TODO</code> with a name, it is almost always your
5144name that is given.</p>
5145
5146
5147
5148<div>
5149<pre>// TODO(kl@gmail.com): Use a "*" here for concatenation operator.
5150// TODO(Zeke) change this to use relations.
5151// TODO(bug 12345): remove the "Last visitors" feature
5152</pre>
5153</div>
5154
5155<p>If your <code>TODO</code> is of the form "At a future
5156date do something" make sure that you either include a
5157very specific date ("Fix by November 2005") or a very
5158specific event ("Remove this code when all clients can
5159handle XML responses.").</p>
5160
5161</div>
5162
5163<h3 id="Deprecation_Comments">Deprecation Comments</h3>
5164
5165<div class="summary">
5166<p>Mark deprecated interface points with <code>DEPRECATED</code>
5167comments.</p>
5168</div>
5169
5170<div class="stylebody">
5171
5172<p>You can mark an interface as deprecated by writing a
5173comment containing the word <code>DEPRECATED</code> in
5174all caps. The comment goes either before the declaration
5175of the interface or on the same line as the
5176declaration.</p>
5177
5178
5179
5180<p>After the word
5181<code>DEPRECATED</code>, write your name, e-mail address,
5182or other identifier in parentheses.</p>
5183
5184<p>A deprecation comment must include simple, clear
5185directions for people to fix their callsites. In C++, you
5186can implement a deprecated function as an inline function
5187that calls the new interface point.</p>
5188
5189<p>Marking an interface point <code>DEPRECATED</code>
5190will not magically cause any callsites to change. If you
5191want people to actually stop using the deprecated
5192facility, you will have to fix the callsites yourself or
5193recruit a crew to help you.</p>
5194
5195<p>New code should not contain calls to deprecated
5196interface points. Use the new interface point instead. If
5197you cannot understand the directions, find the person who
5198created the deprecation and ask them for help using the
5199new interface point.</p>
5200
5201
5202
5203</div>
5204
5205<h2 id="Formatting">Formatting</h2>
5206
5207<p>Coding style and formatting are pretty arbitrary, but a
5208
5209project is much easier to follow
5210if everyone uses the same style. Individuals may not agree with every
5211aspect of the formatting rules, and some of the rules may take
5212some getting used to, but it is important that all
5213
5214project contributors follow the
5215style rules so that
5216they can all read and understand
5217everyone's code easily.</p>
5218
5219
5220
5221<p>To help you format code correctly, we've
5222created a
5223<a href="https://raw.githubusercontent.com/google/styleguide/gh-pages/google-c-style.el">
5224settings file for emacs</a>.</p>
5225
5226<h3 id="Line_Length">Line Length</h3>
5227
5228<div class="summary">
5229<p>Each line of text in your code should be at most 80
5230characters long.</p>
5231</div>
5232
5233<div class="stylebody">
5234
5235
5236
5237 <p>We recognize that this rule is
5238controversial, but so much existing code already adheres
5239to it, and we feel that consistency is important.</p>
5240
5241<div class="pros">
5242<p>Those who favor this rule
5243argue that it is rude to force them to resize
5244their windows and there is no need for anything longer.
5245Some folks are used to having several code windows
5246side-by-side, and thus don't have room to widen their
5247windows in any case. People set up their work environment
5248assuming a particular maximum window width, and 80
5249columns has been the traditional standard. Why change
5250it?</p>
5251</div>
5252
5253<div class="cons">
5254<p>Proponents of change argue that a wider line can make
5255code more readable. The 80-column limit is an hidebound
5256throwback to 1960s mainframes; modern equipment has wide screens that
5257can easily show longer lines.</p>
5258</div>
5259
5260<div class="decision">
5261<p> 80 characters is the maximum.</p>
5262
5263<p class="exception">Comment lines can be longer than 80
5264characters if it is not feasible to split them without
5265harming readability, ease of cut and paste or auto-linking
5266-- e.g. if a line contains an example command or a literal
5267URL longer than 80 characters.</p>
5268
5269<p class="exception">A raw-string literal may have content
5270that exceeds 80 characters. Except for test code, such literals
5271should appear near the top of a file.</p>
5272
5273<p class="exception">An <code>#include</code> statement with a
5274long path may exceed 80 columns.</p>
5275
5276<p class="exception">You needn't be concerned about
5277<a href="#The__define_Guard">header guards</a> that exceed
5278the maximum length. </p>
5279</div>
5280
5281</div>
5282
5283<h3 id="Non-ASCII_Characters">Non-ASCII Characters</h3>
5284
5285<div class="summary">
5286<p>Non-ASCII characters should be rare, and must use UTF-8
5287formatting.</p>
5288</div>
5289
5290<div class="stylebody">
5291
5292<p>You shouldn't hard-code user-facing text in source,
5293even English, so use of non-ASCII characters should be
5294rare. However, in certain cases it is appropriate to
5295include such words in your code. For example, if your
5296code parses data files from foreign sources, it may be
5297appropriate to hard-code the non-ASCII string(s) used in
5298those data files as delimiters. More commonly, unittest
5299code (which does not need to be localized) might
5300contain non-ASCII strings. In such cases, you should use
5301UTF-8, since that is an encoding
5302understood by most tools able to handle more than just
5303ASCII.</p>
5304
5305<p>Hex encoding is also OK, and encouraged where it
5306enhances readability &#8212; for example,
5307<code>"\xEF\xBB\xBF"</code>, or, even more simply,
5308<code>u8"\uFEFF"</code>, is the Unicode zero-width
5309no-break space character, which would be invisible if
5310included in the source as straight UTF-8.</p>
5311
5312<p>Use the <code>u8</code> prefix
5313to guarantee that a string literal containing
5314<code>\uXXXX</code> escape sequences is encoded as UTF-8.
5315Do not use it for strings containing non-ASCII characters
5316encoded as UTF-8, because that will produce incorrect
5317output if the compiler does not interpret the source file
5318as UTF-8. </p>
5319
5320<p>You shouldn't use the C++11 <code>char16_t</code> and
5321<code>char32_t</code> character types, since they're for
5322non-UTF-8 text. For similar reasons you also shouldn't
5323use <code>wchar_t</code> (unless you're writing code that
5324interacts with the Windows API, which uses
5325<code>wchar_t</code> extensively).</p>
5326
5327</div>
5328
5329<h3 id="Spaces_vs._Tabs">Spaces vs. Tabs</h3>
5330
5331<div class="summary">
5332<p>Use only spaces, and indent 2 spaces at a time.</p>
5333</div>
5334
5335<div class="stylebody">
5336
5337<p>We use spaces for indentation. Do not use tabs in your
5338code. You should set your editor to emit spaces when you
5339hit the tab key.</p>
5340
5341</div>
5342
5343<h3 id="Function_Declarations_and_Definitions">Function Declarations and Definitions</h3>
5344
5345<div class="summary">
5346<p>Return type on the same line as function name, parameters
5347on the same line if they fit. Wrap parameter lists which do
5348not fit on a single line as you would wrap arguments in a
5349<a href="#Function_Calls">function call</a>.</p>
5350</div>
5351
5352<div class="stylebody">
5353
5354<p>Functions look like this:</p>
5355
5356
5357<pre>ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
5358 DoSomething();
5359 ...
5360}
5361</pre>
5362
5363<p>If you have too much text to fit on one line:</p>
5364
5365<pre>ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,
5366 Type par_name3) {
5367 DoSomething();
5368 ...
5369}
5370</pre>
5371
5372<p>or if you cannot fit even the first parameter:</p>
5373
5374<pre>ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
5375 Type par_name1, // 4 space indent
5376 Type par_name2,
5377 Type par_name3) {
5378 DoSomething(); // 2 space indent
5379 ...
5380}
5381</pre>
5382
5383<p>Some points to note:</p>
5384
5385<ul>
5386 <li>Choose good parameter names.</li>
5387
Victor Costan6dfd9d92018-02-05 18:30:35 -08005388 <li>A parameter name may be omitted only if the parameter is not used in the
5389 function's definition.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05005390
5391 <li>If you cannot fit the return type and the function
5392 name on a single line, break between them.</li>
5393
5394 <li>If you break after the return type of a function
5395 declaration or definition, do not indent.</li>
5396
5397 <li>The open parenthesis is always on the same line as
5398 the function name.</li>
5399
5400 <li>There is never a space between the function name
5401 and the open parenthesis.</li>
5402
5403 <li>There is never a space between the parentheses and
5404 the parameters.</li>
5405
5406 <li>The open curly brace is always on the end of the last line of the function
5407 declaration, not the start of the next line.</li>
5408
5409 <li>The close curly brace is either on the last line by
5410 itself or on the same line as the open curly brace.</li>
5411
5412 <li>There should be a space between the close
5413 parenthesis and the open curly brace.</li>
5414
5415 <li>All parameters should be aligned if possible.</li>
5416
5417 <li>Default indentation is 2 spaces.</li>
5418
5419 <li>Wrapped parameters have a 4 space indent.</li>
5420</ul>
5421
5422<p>Unused parameters that are obvious from context may be omitted:</p>
5423
5424<pre>class Foo {
5425 public:
5426 Foo(Foo&amp;&amp;);
5427 Foo(const Foo&amp;);
5428 Foo&amp; operator=(Foo&amp;&amp;);
5429 Foo&amp; operator=(const Foo&amp;);
5430};
5431</pre>
5432
5433<p>Unused parameters that might not be obvious should comment out the variable
5434name in the function definition:</p>
5435
5436<pre>class Shape {
5437 public:
5438 virtual void Rotate(double radians) = 0;
5439};
5440
5441class Circle : public Shape {
5442 public:
5443 void Rotate(double radians) override;
5444};
5445
5446void Circle::Rotate(double /*radians*/) {}
5447</pre>
5448
5449<pre class="badcode">// Bad - if someone wants to implement later, it's not clear what the
5450// variable means.
5451void Circle::Rotate(double) {}
5452</pre>
5453
5454<p>Attributes, and macros that expand to attributes, appear at the very
5455beginning of the function declaration or definition, before the
5456return type:</p>
5457<pre>MUST_USE_RESULT bool IsOK();
5458</pre>
5459
5460</div>
5461
5462<h3 id="Formatting_Lambda_Expressions">Lambda Expressions</h3>
5463
5464<div class="summary">
5465<p>Format parameters and bodies as for any other function, and capture
5466lists like other comma-separated lists.</p>
5467</div>
5468
5469<div class="stylebody">
5470<p>For by-reference captures, do not leave a space between the
5471ampersand (&amp;) and the variable name.</p>
5472<pre>int x = 0;
5473auto x_plus_n = [&amp;x](int n) -&gt; int { return x + n; }
5474</pre>
5475<p>Short lambdas may be written inline as function arguments.</p>
5476<pre>std::set&lt;int&gt; blacklist = {7, 8, 9};
5477std::vector&lt;int&gt; digits = {3, 9, 1, 8, 4, 7, 1};
5478digits.erase(std::remove_if(digits.begin(), digits.end(), [&amp;blacklist](int i) {
5479 return blacklist.find(i) != blacklist.end();
5480 }),
5481 digits.end());
5482</pre>
5483
5484</div>
5485
5486<h3 id="Function_Calls">Function Calls</h3>
5487
5488<div class="summary">
5489<p>Either write the call all on a single line, wrap the
5490arguments at the parenthesis, or start the arguments on a new
5491line indented by four spaces and continue at that 4 space
5492indent. In the absence of other considerations, use the
5493minimum number of lines, including placing multiple arguments
5494on each line where appropriate.</p>
5495</div>
5496
5497<div class="stylebody">
5498
5499<p>Function calls have the following format:</p>
5500<pre>bool result = DoSomething(argument1, argument2, argument3);
5501</pre>
5502
5503<p>If the arguments do not all fit on one line, they
5504should be broken up onto multiple lines, with each
5505subsequent line aligned with the first argument. Do not
5506add spaces after the open paren or before the close
5507paren:</p>
5508<pre>bool result = DoSomething(averyveryveryverylongargument1,
5509 argument2, argument3);
5510</pre>
5511
5512<p>Arguments may optionally all be placed on subsequent
5513lines with a four space indent:</p>
5514<pre>if (...) {
5515 ...
5516 ...
5517 if (...) {
5518 bool result = DoSomething(
5519 argument1, argument2, // 4 space indent
5520 argument3, argument4);
5521 ...
5522 }
5523</pre>
5524
5525<p>Put multiple arguments on a single line to reduce the
5526number of lines necessary for calling a function unless
5527there is a specific readability problem. Some find that
5528formatting with strictly one argument on each line is
5529more readable and simplifies editing of the arguments.
5530However, we prioritize for the reader over the ease of
5531editing arguments, and most readability problems are
5532better addressed with the following techniques.</p>
5533
5534<p>If having multiple arguments in a single line decreases
5535readability due to the complexity or confusing nature of the
5536expressions that make up some arguments, try creating
5537variables that capture those arguments in a descriptive name:</p>
5538<pre>int my_heuristic = scores[x] * y + bases[x];
5539bool result = DoSomething(my_heuristic, x, y, z);
5540</pre>
5541
5542<p>Or put the confusing argument on its own line with
5543an explanatory comment:</p>
5544<pre>bool result = DoSomething(scores[x] * y + bases[x], // Score heuristic.
5545 x, y, z);
5546</pre>
5547
5548<p>If there is still a case where one argument is
5549significantly more readable on its own line, then put it on
5550its own line. The decision should be specific to the argument
5551which is made more readable rather than a general policy.</p>
5552
5553<p>Sometimes arguments form a structure that is important
5554for readability. In those cases, feel free to format the
5555arguments according to that structure:</p>
5556<pre>// Transform the widget by a 3x3 matrix.
5557my_widget.Transform(x1, x2, x3,
5558 y1, y2, y3,
5559 z1, z2, z3);
5560</pre>
5561
5562</div>
5563
5564<h3 id="Braced_Initializer_List_Format">Braced Initializer List Format</h3>
5565
5566<div class="summary">
5567<p>Format a <a href="#Braced_Initializer_List">braced initializer list</a>
5568exactly like you would format a function call in its place.</p>
5569</div>
5570
5571<div class="stylebody">
5572
5573<p>If the braced list follows a name (e.g. a type or
5574variable name), format as if the <code>{}</code> were the
5575parentheses of a function call with that name. If there
5576is no name, assume a zero-length name.</p>
5577
5578<pre>// Examples of braced init list on a single line.
5579return {foo, bar};
5580functioncall({foo, bar});
5581std::pair&lt;int, int&gt; p{foo, bar};
5582
5583// When you have to wrap.
5584SomeFunction(
5585 {"assume a zero-length name before {"},
5586 some_other_function_parameter);
5587SomeType variable{
5588 some, other, values,
5589 {"assume a zero-length name before {"},
5590 SomeOtherType{
5591 "Very long string requiring the surrounding breaks.",
5592 some, other values},
5593 SomeOtherType{"Slightly shorter string",
5594 some, other, values}};
5595SomeType variable{
5596 "This is too long to fit all in one line"};
5597MyType m = { // Here, you could also break before {.
5598 superlongvariablename1,
5599 superlongvariablename2,
5600 {short, interior, list},
5601 {interiorwrappinglist,
5602 interiorwrappinglist2}};
5603</pre>
5604
5605</div>
5606
5607<h3 id="Conditionals">Conditionals</h3>
5608
5609<div class="summary">
5610<p>Prefer no spaces inside parentheses. The <code>if</code>
5611and <code>else</code> keywords belong on separate lines.</p>
5612</div>
5613
5614<div class="stylebody">
5615
5616<p>There are two acceptable formats for a basic
5617conditional statement. One includes spaces between the
5618parentheses and the condition, and one does not.</p>
5619
5620<p>The most common form is without spaces. Either is
5621fine, but <em>be consistent</em>. If you are modifying a
5622file, use the format that is already present. If you are
5623writing new code, use the format that the other files in
5624that directory or project use. If in doubt and you have
5625no personal preference, do not add the spaces.</p>
5626
5627<pre>if (condition) { // no spaces inside parentheses
5628 ... // 2 space indent.
5629} else if (...) { // The else goes on the same line as the closing brace.
5630 ...
5631} else {
5632 ...
5633}
5634</pre>
5635
5636<p>If you prefer you may add spaces inside the
5637parentheses:</p>
5638
5639<pre>if ( condition ) { // spaces inside parentheses - rare
5640 ... // 2 space indent.
5641} else { // The else goes on the same line as the closing brace.
5642 ...
5643}
5644</pre>
5645
5646<p>Note that in all cases you must have a space between
5647the <code>if</code> and the open parenthesis. You must
5648also have a space between the close parenthesis and the
5649curly brace, if you're using one.</p>
5650
5651<pre class="badcode">if(condition) { // Bad - space missing after IF.
5652if (condition){ // Bad - space missing before {.
5653if(condition){ // Doubly bad.
5654</pre>
5655
5656<pre>if (condition) { // Good - proper space after IF and before {.
5657</pre>
5658
5659<p>Short conditional statements may be written on one
5660line if this enhances readability. You may use this only
5661when the line is brief and the statement does not use the
5662<code>else</code> clause.</p>
5663
5664<pre>if (x == kFoo) return new Foo();
5665if (x == kBar) return new Bar();
5666</pre>
5667
5668<p>This is not allowed when the if statement has an
5669<code>else</code>:</p>
5670
5671<pre class="badcode">// Not allowed - IF statement on one line when there is an ELSE clause
5672if (x) DoThis();
5673else DoThat();
5674</pre>
5675
5676<p>In general, curly braces are not required for
5677single-line statements, but they are allowed if you like
5678them; conditional or loop statements with complex
5679conditions or statements may be more readable with curly
5680braces. Some
5681projects require that an
Victor Costan6dfd9d92018-02-05 18:30:35 -08005682<code>if</code> must always have an accompanying
Ted Osborne505ba682018-01-30 12:36:50 -05005683brace.</p>
5684
5685<pre>if (condition)
5686 DoSomething(); // 2 space indent.
5687
5688if (condition) {
5689 DoSomething(); // 2 space indent.
5690}
5691</pre>
5692
5693<p>However, if one part of an
5694<code>if</code>-<code>else</code> statement uses curly
5695braces, the other part must too:</p>
5696
5697<pre class="badcode">// Not allowed - curly on IF but not ELSE
5698if (condition) {
5699 foo;
5700} else
5701 bar;
5702
5703// Not allowed - curly on ELSE but not IF
5704if (condition)
5705 foo;
5706else {
5707 bar;
5708}
5709</pre>
5710
5711<pre>// Curly braces around both IF and ELSE required because
5712// one of the clauses used braces.
5713if (condition) {
5714 foo;
5715} else {
5716 bar;
5717}
5718</pre>
5719
5720</div>
5721
5722<h3 id="Loops_and_Switch_Statements">Loops and Switch Statements</h3>
5723
5724<div class="summary">
5725<p>Switch statements may use braces for blocks. Annotate
5726non-trivial fall-through between cases.
5727Braces are optional for single-statement loops.
Victor Costan6dfd9d92018-02-05 18:30:35 -08005728Empty loop bodies should use either empty braces or <code>continue</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005729</div>
5730
5731<div class="stylebody">
5732
5733<p><code>case</code> blocks in <code>switch</code>
5734statements can have curly braces or not, depending on
5735your preference. If you do include curly braces they
5736should be placed as shown below.</p>
5737
5738<p>If not conditional on an enumerated value, switch
5739statements should always have a <code>default</code> case
5740(in the case of an enumerated value, the compiler will
5741warn you if any values are not handled). If the default
Victor Costan6dfd9d92018-02-05 18:30:35 -08005742case should never execute, treat this as an error. For example:
Ted Osborne505ba682018-01-30 12:36:50 -05005743
Victor Costan6dfd9d92018-02-05 18:30:35 -08005744</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005745
5746<div>
5747<pre>switch (var) {
5748 case 0: { // 2 space indent
5749 ... // 4 space indent
5750 break;
5751 }
5752 case 1: {
5753 ...
5754 break;
5755 }
5756 default: {
5757 assert(false);
5758 }
5759}
5760</pre>
5761</div>
5762
5763
5764
5765
5766
5767<p> Braces are optional for single-statement loops.</p>
5768
5769<pre>for (int i = 0; i &lt; kSomeNumber; ++i)
5770 printf("I love you\n");
5771
5772for (int i = 0; i &lt; kSomeNumber; ++i) {
5773 printf("I take it back\n");
5774}
5775</pre>
5776
5777
Victor Costan6dfd9d92018-02-05 18:30:35 -08005778<p>Empty loop bodies should use either an empty pair of braces or
5779<code>continue</code> with no braces, rather than a single semicolon.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005780
5781<pre>while (condition) {
5782 // Repeat test until it returns false.
5783}
5784for (int i = 0; i &lt; kSomeNumber; ++i) {} // Good - one newline is also OK.
5785while (condition) continue; // Good - continue indicates no logic.
5786</pre>
5787
5788<pre class="badcode">while (condition); // Bad - looks like part of do/while loop.
5789</pre>
5790
5791</div>
5792
5793<h3 id="Pointer_and_Reference_Expressions">Pointer and Reference Expressions</h3>
5794
5795<div class="summary">
5796<p>No spaces around period or arrow. Pointer operators do not
5797have trailing spaces.</p>
5798</div>
5799
5800<div class="stylebody">
5801
5802<p>The following are examples of correctly-formatted
5803pointer and reference expressions:</p>
5804
5805<pre>x = *p;
5806p = &amp;x;
5807x = r.y;
5808x = r-&gt;y;
5809</pre>
5810
5811<p>Note that:</p>
5812
5813<ul>
5814 <li>There are no spaces around the period or arrow when
5815 accessing a member.</li>
5816
5817 <li>Pointer operators have no space after the
5818 <code>*</code> or <code>&amp;</code>.</li>
5819</ul>
5820
5821<p>When declaring a pointer variable or argument, you may
5822place the asterisk adjacent to either the type or to the
5823variable name:</p>
5824
5825<pre>// These are fine, space preceding.
5826char *c;
5827const string &amp;str;
5828
5829// These are fine, space following.
5830char* c;
5831const string&amp; str;
5832</pre>
5833
Victor Costan6dfd9d92018-02-05 18:30:35 -08005834<p>You should do this consistently within a single
5835file,
5836so, when modifying an existing file, use the style in
5837that file.</p>
5838
Ted Osborne505ba682018-01-30 12:36:50 -05005839It is allowed (if unusual) to declare multiple variables in the same
5840declaration, but it is disallowed if any of those have pointer or
5841reference decorations. Such declarations are easily misread.
5842<pre>// Fine if helpful for readability.
5843int x, y;
5844</pre>
5845<pre class="badcode">int x, *y; // Disallowed - no &amp; or * in multiple declaration
5846char * c; // Bad - spaces on both sides of *
5847const string &amp; str; // Bad - spaces on both sides of &amp;
5848</pre>
5849
Ted Osborne505ba682018-01-30 12:36:50 -05005850</div>
5851
5852<h3 id="Boolean_Expressions">Boolean Expressions</h3>
5853
5854<div class="summary">
5855<p>When you have a boolean expression that is longer than the
5856<a href="#Line_Length">standard line length</a>, be
5857consistent in how you break up the lines.</p>
5858</div>
5859
5860<div class="stylebody">
5861
5862<p>In this example, the logical AND operator is always at
5863the end of the lines:</p>
5864
5865<pre>if (this_one_thing &gt; this_other_thing &amp;&amp;
5866 a_third_thing == a_fourth_thing &amp;&amp;
5867 yet_another &amp;&amp; last_one) {
5868 ...
5869}
5870</pre>
5871
5872<p>Note that when the code wraps in this example, both of
5873the <code>&amp;&amp;</code> logical AND operators are at
5874the end of the line. This is more common in Google code,
5875though wrapping all operators at the beginning of the
5876line is also allowed. Feel free to insert extra
5877parentheses judiciously because they can be very helpful
5878in increasing readability when used
5879appropriately. Also note that you should always use
5880the punctuation operators, such as
5881<code>&amp;&amp;</code> and <code>~</code>, rather than
5882the word operators, such as <code>and</code> and
5883<code>compl</code>.</p>
5884
5885</div>
5886
5887<h3 id="Return_Values">Return Values</h3>
5888
5889<div class="summary">
5890<p>Do not needlessly surround the <code>return</code>
5891expression with parentheses.</p>
5892</div>
5893
5894<div class="stylebody">
5895
5896<p>Use parentheses in <code>return expr;</code> only
5897where you would use them in <code>x = expr;</code>.</p>
5898
5899<pre>return result; // No parentheses in the simple case.
5900// Parentheses OK to make a complex expression more readable.
5901return (some_long_condition &amp;&amp;
5902 another_condition);
5903</pre>
5904
5905<pre class="badcode">return (value); // You wouldn't write var = (value);
5906return(result); // return is not a function!
5907</pre>
5908
5909</div>
5910
5911
5912
5913<h3 id="Variable_and_Array_Initialization">Variable and Array Initialization</h3>
5914
5915<div class="summary">
5916<p>Your choice of <code>=</code>, <code>()</code>, or
5917<code>{}</code>.</p>
5918</div>
5919
5920<div class="stylebody">
5921
5922<p>You may choose between <code>=</code>,
5923<code>()</code>, and <code>{}</code>; the following are
5924all correct:</p>
5925
5926<pre>int x = 3;
5927int x(3);
5928int x{3};
5929string name = "Some Name";
5930string name("Some Name");
5931string name{"Some Name"};
5932</pre>
5933
5934<p>Be careful when using a braced initialization list <code>{...}</code>
5935on a type with an <code>std::initializer_list</code> constructor.
5936A nonempty <i>braced-init-list</i> prefers the
5937<code>std::initializer_list</code> constructor whenever
5938possible. Note that empty braces <code>{}</code> are special, and
5939will call a default constructor if available. To force the
5940non-<code>std::initializer_list</code> constructor, use parentheses
5941instead of braces.</p>
5942
Victor Costan6dfd9d92018-02-05 18:30:35 -08005943<pre>std::vector&lt;int&gt; v(100, 1); // A vector containing 100 items: All 1s.
5944std::vector&lt;int&gt; v{100, 1}; // A vector containing 2 items: 100 and 1.
Ted Osborne505ba682018-01-30 12:36:50 -05005945</pre>
5946
5947<p>Also, the brace form prevents narrowing of integral
5948types. This can prevent some types of programming
5949errors.</p>
5950
5951<pre>int pi(3.14); // OK -- pi == 3.
5952int pi{3.14}; // Compile error: narrowing conversion.
5953</pre>
5954
5955</div>
5956
5957<h3 id="Preprocessor_Directives">Preprocessor Directives</h3>
5958
5959<div class="summary">
5960<p>The hash mark that starts a preprocessor directive should
5961always be at the beginning of the line.</p>
5962</div>
5963
5964<div class="stylebody">
5965
5966<p>Even when preprocessor directives are within the body
5967of indented code, the directives should start at the
5968beginning of the line.</p>
5969
5970<pre>// Good - directives at beginning of line
5971 if (lopsided_score) {
5972#if DISASTER_PENDING // Correct -- Starts at beginning of line
5973 DropEverything();
5974# if NOTIFY // OK but not required -- Spaces after #
5975 NotifyClient();
5976# endif
5977#endif
5978 BackToNormal();
5979 }
5980</pre>
5981
5982<pre class="badcode">// Bad - indented directives
5983 if (lopsided_score) {
5984 #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line
5985 DropEverything();
5986 #endif // Wrong! Do not indent "#endif"
5987 BackToNormal();
5988 }
5989</pre>
5990
5991</div>
5992
5993<h3 id="Class_Format">Class Format</h3>
5994
5995<div class="summary">
5996<p>Sections in <code>public</code>, <code>protected</code> and
5997<code>private</code> order, each indented one space.</p>
5998</div>
5999
6000<div class="stylebody">
6001
6002<p>The basic format for a class definition (lacking the
6003comments, see <a href="#Class_Comments">Class
6004Comments</a> for a discussion of what comments are
6005needed) is:</p>
6006
6007<pre>class MyClass : public OtherClass {
6008 public: // Note the 1 space indent!
6009 MyClass(); // Regular 2 space indent.
6010 explicit MyClass(int var);
6011 ~MyClass() {}
6012
6013 void SomeFunction();
6014 void SomeFunctionThatDoesNothing() {
6015 }
6016
6017 void set_some_var(int var) { some_var_ = var; }
6018 int some_var() const { return some_var_; }
6019
6020 private:
6021 bool SomeInternalFunction();
6022
6023 int some_var_;
6024 int some_other_var_;
6025};
6026</pre>
6027
6028<p>Things to note:</p>
6029
6030<ul>
6031 <li>Any base class name should be on the same line as
6032 the subclass name, subject to the 80-column limit.</li>
6033
6034 <li>The <code>public:</code>, <code>protected:</code>,
6035 and <code>private:</code> keywords should be indented
6036 one space.</li>
6037
6038 <li>Except for the first instance, these keywords
6039 should be preceded by a blank line. This rule is
6040 optional in small classes.</li>
6041
6042 <li>Do not leave a blank line after these
6043 keywords.</li>
6044
6045 <li>The <code>public</code> section should be first,
6046 followed by the <code>protected</code> and finally the
6047 <code>private</code> section.</li>
6048
6049 <li>See <a href="#Declaration_Order">Declaration
6050 Order</a> for rules on ordering declarations within
6051 each of these sections.</li>
6052</ul>
6053
6054</div>
6055
6056<h3 id="Constructor_Initializer_Lists">Constructor Initializer Lists</h3>
6057
6058<div class="summary">
6059<p>Constructor initializer lists can be all on one line or
6060with subsequent lines indented four spaces.</p>
6061</div>
6062
6063<div class="stylebody">
6064
6065<p>The acceptable formats for initializer lists are:</p>
6066
6067<pre>// When everything fits on one line:
6068MyClass::MyClass(int var) : some_var_(var) {
6069 DoSomething();
6070}
6071
6072// If the signature and initializer list are not all on one line,
6073// you must wrap before the colon and indent 4 spaces:
6074MyClass::MyClass(int var)
6075 : some_var_(var), some_other_var_(var + 1) {
6076 DoSomething();
6077}
6078
6079// When the list spans multiple lines, put each member on its own line
6080// and align them:
6081MyClass::MyClass(int var)
6082 : some_var_(var), // 4 space indent
6083 some_other_var_(var + 1) { // lined up
6084 DoSomething();
6085}
6086
6087// As with any other code block, the close curly can be on the same
6088// line as the open curly, if it fits.
6089MyClass::MyClass(int var)
6090 : some_var_(var) {}
6091</pre>
6092
6093</div>
6094
6095<h3 id="Namespace_Formatting">Namespace Formatting</h3>
6096
6097<div class="summary">
6098<p>The contents of namespaces are not indented.</p>
6099</div>
6100
6101<div class="stylebody">
6102
6103<p><a href="#Namespaces">Namespaces</a> do not add an
6104extra level of indentation. For example, use:</p>
6105
6106<pre>namespace {
6107
6108void foo() { // Correct. No extra indentation within namespace.
6109 ...
6110}
6111
6112} // namespace
6113</pre>
6114
6115<p>Do not indent within a namespace:</p>
6116
6117<pre class="badcode">namespace {
6118
Victor Costan6dfd9d92018-02-05 18:30:35 -08006119 // Wrong! Indented when it should not be.
Ted Osborne505ba682018-01-30 12:36:50 -05006120 void foo() {
6121 ...
6122 }
6123
6124} // namespace
6125</pre>
6126
6127<p>When declaring nested namespaces, put each namespace
6128on its own line.</p>
6129
6130<pre>namespace foo {
6131namespace bar {
6132</pre>
6133
6134</div>
6135
6136<h3 id="Horizontal_Whitespace">Horizontal Whitespace</h3>
6137
6138<div class="summary">
6139<p>Use of horizontal whitespace depends on location. Never put
6140trailing whitespace at the end of a line.</p>
6141</div>
6142
6143<div class="stylebody">
6144
6145<h4 class="stylepoint_subsection">General</h4>
6146
6147<pre>void f(bool b) { // Open braces should always have a space before them.
6148 ...
6149int i = 0; // Semicolons usually have no space before them.
6150// Spaces inside braces for braced-init-list are optional. If you use them,
6151// put them on both sides!
6152int x[] = { 0 };
6153int x[] = {0};
6154
6155// Spaces around the colon in inheritance and initializer lists.
6156class Foo : public Bar {
6157 public:
6158 // For inline function implementations, put spaces between the braces
6159 // and the implementation itself.
6160 Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces.
6161 void Reset() { baz_ = 0; } // Spaces separating braces from implementation.
6162 ...
6163</pre>
6164
6165<p>Adding trailing whitespace can cause extra work for
6166others editing the same file, when they merge, as can
6167removing existing trailing whitespace. So: Don't
6168introduce trailing whitespace. Remove it if you're
6169already changing that line, or do it in a separate
6170clean-up
6171operation (preferably when no-one
6172else is working on the file).</p>
6173
6174<h4 class="stylepoint_subsection">Loops and Conditionals</h4>
6175
6176<pre>if (b) { // Space after the keyword in conditions and loops.
6177} else { // Spaces around else.
6178}
6179while (test) {} // There is usually no space inside parentheses.
6180switch (i) {
6181for (int i = 0; i &lt; 5; ++i) {
6182// Loops and conditions may have spaces inside parentheses, but this
6183// is rare. Be consistent.
6184switch ( i ) {
6185if ( test ) {
6186for ( int i = 0; i &lt; 5; ++i ) {
6187// For loops always have a space after the semicolon. They may have a space
6188// before the semicolon, but this is rare.
6189for ( ; i &lt; 5 ; ++i) {
6190 ...
6191
6192// Range-based for loops always have a space before and after the colon.
6193for (auto x : counts) {
6194 ...
6195}
6196switch (i) {
6197 case 1: // No space before colon in a switch case.
6198 ...
6199 case 2: break; // Use a space after a colon if there's code after it.
6200</pre>
6201
6202<h4 class="stylepoint_subsection">Operators</h4>
6203
6204<pre>// Assignment operators always have spaces around them.
6205x = 0;
6206
6207// Other binary operators usually have spaces around them, but it's
6208// OK to remove spaces around factors. Parentheses should have no
6209// internal padding.
6210v = w * x + y / z;
6211v = w*x + y/z;
6212v = w * (x + z);
6213
6214// No spaces separating unary operators and their arguments.
6215x = -5;
6216++x;
6217if (x &amp;&amp; !y)
6218 ...
6219</pre>
6220
6221<h4 class="stylepoint_subsection">Templates and Casts</h4>
6222
6223<pre>// No spaces inside the angle brackets (&lt; and &gt;), before
6224// &lt;, or between &gt;( in a cast
6225std::vector&lt;string&gt; x;
6226y = static_cast&lt;char*&gt;(x);
6227
6228// Spaces between type and pointer are OK, but be consistent.
6229std::vector&lt;char *&gt; x;
6230</pre>
6231
6232</div>
6233
6234<h3 id="Vertical_Whitespace">Vertical Whitespace</h3>
6235
6236<div class="summary">
6237<p>Minimize use of vertical whitespace.</p>
6238</div>
6239
6240<div class="stylebody">
6241
6242<p>This is more a principle than a rule: don't use blank
6243lines when you don't have to. In particular, don't put
6244more than one or two blank lines between functions,
6245resist starting functions with a blank line, don't end
6246functions with a blank line, and be discriminating with
6247your use of blank lines inside functions.</p>
6248
6249<p>The basic principle is: The more code that fits on one
6250screen, the easier it is to follow and understand the
6251control flow of the program. Of course, readability can
6252suffer from code being too dense as well as too spread
6253out, so use your judgement. But in general, minimize use
6254of vertical whitespace.</p>
6255
6256<p>Some rules of thumb to help when blank lines may be
6257useful:</p>
6258
6259<ul>
6260 <li>Blank lines at the beginning or end of a function
6261 very rarely help readability.</li>
6262
6263 <li>Blank lines inside a chain of if-else blocks may
6264 well help readability.</li>
6265</ul>
6266
6267</div>
6268
6269<h2 id="Exceptions_to_the_Rules">Exceptions to the Rules</h2>
6270
6271<p>The coding conventions described above are mandatory.
6272However, like all good rules, these sometimes have exceptions,
6273which we discuss here.</p>
6274
6275
6276
6277<div>
6278<h3 id="Existing_Non-conformant_Code">Existing Non-conformant Code</h3>
6279
6280<div class="summary">
6281<p>You may diverge from the rules when dealing with code that
6282does not conform to this style guide.</p>
6283</div>
6284
6285<div class="stylebody">
6286
6287<p>If you find yourself modifying code that was written
6288to specifications other than those presented by this
6289guide, you may have to diverge from these rules in order
6290to stay consistent with the local conventions in that
6291code. If you are in doubt about how to do this, ask the
6292original author or the person currently responsible for
6293the code. Remember that <em>consistency</em> includes
6294local consistency, too.</p>
6295
6296</div>
6297</div>
6298
6299
6300
6301<h3 id="Windows_Code">Windows Code</h3>
6302
6303<div class="summary">
6304<p> Windows
6305programmers have developed their own set of coding
6306conventions, mainly derived from the conventions in Windows
6307headers and other Microsoft code. We want to make it easy
6308for anyone to understand your code, so we have a single set
6309of guidelines for everyone writing C++ on any platform.</p>
6310</div>
6311
6312<div class="stylebody">
6313<p>It is worth reiterating a few of the guidelines that
6314you might forget if you are used to the prevalent Windows
6315style:</p>
6316
6317<ul>
6318 <li>Do not use Hungarian notation (for example, naming
6319 an integer <code>iNum</code>). Use the Google naming
6320 conventions, including the <code>.cc</code> extension
6321 for source files.</li>
6322
6323 <li>Windows defines many of its own synonyms for
6324 primitive types, such as <code>DWORD</code>,
6325 <code>HANDLE</code>, etc. It is perfectly acceptable,
6326 and encouraged, that you use these types when calling
6327 Windows API functions. Even so, keep as close as you
6328 can to the underlying C++ types. For example, use
6329 <code>const TCHAR *</code> instead of
6330 <code>LPCTSTR</code>.</li>
6331
6332 <li>When compiling with Microsoft Visual C++, set the
6333 compiler to warning level 3 or higher, and treat all
6334 warnings as errors.</li>
6335
6336 <li>Do not use <code>#pragma once</code>; instead use
6337 the standard Google include guards. The path in the
6338 include guards should be relative to the top of your
6339 project tree.</li>
6340
6341 <li>In fact, do not use any nonstandard extensions,
6342 like <code>#pragma</code> and <code>__declspec</code>,
6343 unless you absolutely must. Using
6344 <code>__declspec(dllimport)</code> and
6345 <code>__declspec(dllexport)</code> is allowed; however,
6346 you must use them through macros such as
6347 <code>DLLIMPORT</code> and <code>DLLEXPORT</code>, so
6348 that someone can easily disable the extensions if they
6349 share the code.</li>
6350</ul>
6351
6352<p>However, there are just a few rules that we
6353occasionally need to break on Windows:</p>
6354
6355<ul>
6356 <li>Normally we <a href="#Multiple_Inheritance">forbid
6357 the use of multiple implementation inheritance</a>;
6358 however, it is required when using COM and some ATL/WTL
6359 classes. You may use multiple implementation
6360 inheritance to implement COM or ATL/WTL classes and
6361 interfaces.</li>
6362
6363 <li>Although you should not use exceptions in your own
6364 code, they are used extensively in the ATL and some
6365 STLs, including the one that comes with Visual C++.
6366 When using the ATL, you should define
6367 <code>_ATL_NO_EXCEPTIONS</code> to disable exceptions.
6368 You should investigate whether you can also disable
6369 exceptions in your STL, but if not, it is OK to turn on
6370 exceptions in the compiler. (Note that this is only to
6371 get the STL to compile. You should still not write
6372 exception handling code yourself.)</li>
6373
6374 <li>The usual way of working with precompiled headers
6375 is to include a header file at the top of each source
6376 file, typically with a name like <code>StdAfx.h</code>
6377 or <code>precompile.h</code>. To make your code easier
6378 to share with other projects, avoid including this file
6379 explicitly (except in <code>precompile.cc</code>), and
6380 use the <code>/FI</code> compiler option to include the
6381 file automatically.</li>
6382
6383 <li>Resource headers, which are usually named
6384 <code>resource.h</code> and contain only macros, do not
6385 need to conform to these style guidelines.</li>
6386</ul>
6387
6388</div>
6389
Victor Costan6dfd9d92018-02-05 18:30:35 -08006390<h2 id="Parting_Words">Parting Words</h2>
Ted Osborne505ba682018-01-30 12:36:50 -05006391
6392<p>Use common sense and <em>BE CONSISTENT</em>.</p>
6393
6394<p>If you are editing code, take a few minutes to look at the
6395code around you and determine its style. If they use spaces
6396around their <code>if</code> clauses, you should, too. If their
6397comments have little boxes of stars around them, make your
6398comments have little boxes of stars around them too.</p>
6399
6400<p>The point of having style guidelines is to have a common
6401vocabulary of coding so people can concentrate on what you are
6402saying, rather than on how you are saying it. We present global
6403style rules here so people know the vocabulary. But local style
6404is also important. If code you add to a file looks drastically
6405different from the existing code around it, the discontinuity
6406throws readers out of their rhythm when they go to read it. Try
6407to avoid this.</p>
6408
6409
6410
6411<p>OK, enough writing about writing code; the code itself is much
6412more interesting. Have fun!</p>
6413
6414<hr>
6415
6416</div>
6417</div>
6418</body>
6419</html>