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