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