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