blob: bbf1f64d7f54325904056934d92169d660cfce41 [file] [log] [blame]
Ted Osborne505ba682018-01-30 12:36:50 -05001<!DOCTYPE html>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002<html lang="en">
Ted Osborne505ba682018-01-30 12:36:50 -05003<head>
Victor Costan6dfd9d92018-02-05 18:30:35 -08004<meta charset="utf-8">
Ted Osborne505ba682018-01-30 12:36:50 -05005<title>Google C++ Style Guide</title>
Victor Costan6dfd9d92018-02-05 18:30:35 -08006<link rel="stylesheet" href="include/styleguide.css">
7<script src="include/styleguide.js"></script>
8<link rel="shortcut icon" href="https://www.google.com/favicon.ico">
Ted Osborne505ba682018-01-30 12:36:50 -05009</head>
10<body onload="initStyleGuide();">
11<div id="content">
12<h1>Google C++ Style Guide</h1>
Tom Manshreck63107a12018-08-14 16:12:59 -040013<div class="horizontal_toc" id="tocDiv"></div>
Ted Osborne505ba682018-01-30 12:36:50 -050014<div class="main_body">
15
Victor Costanf0314ea2019-09-01 20:42:44 -070016<h2 id="Background" class="ignoreLink">Background</h2>
Ted Osborne505ba682018-01-30 12:36:50 -050017
18<p>C++ is one of the main development languages used by
19many of Google's open-source projects. As every C++
20programmer knows, the language has many powerful features, but
21this power brings with it complexity, which in turn can make
22code more bug-prone and harder to read and maintain.</p>
23
24<p>The goal of this guide is to manage this complexity by
Victor Costanf0314ea2019-09-01 20:42:44 -070025describing in detail the dos and don'ts of writing C++ code
26. These rules exist to
Ted Osborne505ba682018-01-30 12:36:50 -050027keep the code base manageable while still allowing
28coders to use C++ language features productively.</p>
29
30<p><em>Style</em>, also known as readability, is what we call
31the conventions that govern our C++ code. The term Style is a
32bit of a misnomer, since these conventions cover far more than
33just source file formatting.</p>
34
35<p>
36Most open-source projects developed by
37Google conform to the requirements in this guide.
38</p>
39
40
41
Ted Osborne505ba682018-01-30 12:36:50 -050042<p>Note that this guide is not a C++ tutorial: we assume that
43the reader is familiar with the language. </p>
44
45<h3 id="Goals">Goals of the Style Guide</h3>
Victor Costanf0314ea2019-09-01 20:42:44 -070046
Ted Osborne505ba682018-01-30 12:36:50 -050047<p>Why do we have this document?</p>
48
49<p>There are a few core goals that we believe this guide should
50serve. These are the fundamental <b>why</b>s that
51underlie all of the individual rules. By bringing these ideas to
52the fore, we hope to ground discussions and make it clearer to our
53broader community why the rules are in place and why particular
54decisions have been made. If you understand what goals each rule is
55serving, it should be clearer to everyone when a rule may be waived
56(some can be), and what sort of argument or alternative would be
57necessary to change a rule in the guide.</p>
58
59<p>The goals of the style guide as we currently see them are as follows:</p>
60<dl>
61<dt>Style rules should pull their weight</dt>
62<dd>The benefit of a style rule
63must be large enough to justify asking all of our engineers to
64remember it. The benefit is measured relative to the codebase we would
65get without the rule, so a rule against a very harmful practice may
66still have a small benefit if people are unlikely to do it
67anyway. This principle mostly explains the rules we don&#8217;t have, rather
68than the rules we do: for example, <code>goto</code> contravenes many
69of the following principles, but is already vanishingly rare, so the Style
70Guide doesn&#8217;t discuss it.</dd>
71
72<dt>Optimize for the reader, not the writer</dt>
73<dd>Our codebase (and most individual components submitted to it) is
74expected to continue for quite some time. As a result, more time will
75be spent reading most of our code than writing it. We explicitly
76choose to optimize for the experience of our average software engineer
77reading, maintaining, and debugging code in our codebase rather than
78ease when writing said code. "Leave a trace for the reader" is a
79particularly common sub-point of this principle: When something
80surprising or unusual is happening in a snippet of code (for example,
81transfer of pointer ownership), leaving textual hints for the reader
82at the point of use is valuable (<code>std::unique_ptr</code>
83demonstrates the ownership transfer unambiguously at the call
84site). </dd>
85
86<dt>Be consistent with existing code</dt>
87<dd>Using one style consistently through our codebase lets us focus on
88other (more important) issues. Consistency also allows for
89automation: tools that format your code or adjust
90your <code>#include</code>s only work properly when your code is
91consistent with the expectations of the tooling. In many cases, rules
92that are attributed to "Be Consistent" boil down to "Just pick one and
93stop worrying about it"; the potential value of allowing flexibility
94on these points is outweighed by the cost of having people argue over
95them. </dd>
96
97<dt>Be consistent with the broader C++ community when appropriate</dt>
98<dd>Consistency with the way other organizations use C++ has value for
99the same reasons as consistency within our code base. If a feature in
100the C++ standard solves a problem, or if some idiom is widely known
101and accepted, that's an argument for using it. However, sometimes
102standard features and idioms are flawed, or were just designed without
103our codebase's needs in mind. In those cases (as described below) it's
104appropriate to constrain or ban standard features. In some cases we
105prefer a homegrown or third-party library over a library defined in
106the C++ Standard, either out of perceived superiority or insufficient
107value to transition the codebase to the standard interface.</dd>
108
109<dt>Avoid surprising or dangerous constructs</dt>
110<dd>C++ has features that are more surprising or dangerous than one
111might think at a glance. Some style guide restrictions are in place to
112prevent falling into these pitfalls. There is a high bar for style
113guide waivers on such restrictions, because waiving such rules often
114directly risks compromising program correctness.
115</dd>
116
117<dt>Avoid constructs that our average C++ programmer would find tricky
118or hard to maintain</dt>
119<dd>C++ has features that may not be generally appropriate because of
120the complexity they introduce to the code. In widely used
121code, it may be more acceptable to use
122trickier language constructs, because any benefits of more complex
123implementation are multiplied widely by usage, and the cost in understanding
124the complexity does not need to be paid again when working with new
125portions of the codebase. When in doubt, waivers to rules of this type
Victor Costanf0314ea2019-09-01 20:42:44 -0700126can be sought by asking
Ted Osborne505ba682018-01-30 12:36:50 -0500127your project leads. This is specifically
128important for our codebase because code ownership and team membership
129changes over time: even if everyone that works with some piece of code
130currently understands it, such understanding is not guaranteed to hold a
131few years from now.</dd>
132
133<dt>Be mindful of our scale</dt>
134<dd>With a codebase of 100+ million lines and thousands of engineers,
135some mistakes and simplifications for one engineer can become costly
136for many. For instance it's particularly important to
137avoid polluting the global namespace: name collisions across a
138codebase of hundreds of millions of lines are difficult to work with
139and hard to avoid if everyone puts things into the global
140namespace.</dd>
141
142<dt>Concede to optimization when necessary</dt>
143<dd>Performance optimizations can sometimes be necessary and
144appropriate, even when they conflict with the other principles of this
145document.</dd>
146</dl>
147
148<p>The intent of this document is to provide maximal guidance with
149reasonable restriction. As always, common sense and good taste should
150prevail. By this we specifically refer to the established conventions
151of the entire Google C++ community, not just your personal preferences
152or those of your team. Be skeptical about and reluctant to use
153clever or unusual constructs: the absence of a prohibition is not the
154same as a license to proceed. Use your judgment, and if you are
155unsure, please don't hesitate to ask your project leads to get additional
156input.</p>
157
Ted Osborne505ba682018-01-30 12:36:50 -0500158
Ted Osborne505ba682018-01-30 12:36:50 -0500159
Victor Costanb89a7752018-07-31 10:17:48 -0700160<h2 id="C++_Version">C++ Version</h2>
161
Victor Costan967e1572019-09-05 05:09:38 -0700162<p>Currently, code should target C++17, i.e., should not use C++2x
163 features. The C++ version targeted by this guide will advance
164 (aggressively) over time.</p>
Victor Costanb89a7752018-07-31 10:17:48 -0700165
166
167
Victor Costan967e1572019-09-05 05:09:38 -0700168<p>Do not use
169 <a href="#Nonstandard_Extensions">non-standard extensions</a>.</p>
170
171 <div>Consider portability to other environments
172before using features from C++14 and C++17 in your project.
173</div>
174
Ted Osborne505ba682018-01-30 12:36:50 -0500175<h2 id="Header_Files">Header Files</h2>
176
177<p>In general, every <code>.cc</code> file should have an
178associated <code>.h</code> file. There are some common
179exceptions, such as unittests and
180small <code>.cc</code> files containing just a
181<code>main()</code> function.</p>
182
183<p>Correct use of header files can make a huge difference to
184the readability, size and performance of your code.</p>
185
186<p>The following rules will guide you through the various
187pitfalls of using header files.</p>
188
189<a id="The_-inl.h_Files"></a>
190<h3 id="Self_contained_Headers">Self-contained Headers</h3>
191
Ted Osborne505ba682018-01-30 12:36:50 -0500192<p>Header files should be self-contained (compile on their own) and
193end in <code>.h</code>. Non-header files that are meant for inclusion
194should end in <code>.inc</code> and be used sparingly.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500195
Ted Osborne505ba682018-01-30 12:36:50 -0500196<p>All header files should be self-contained. Users and refactoring
197tools should not have to adhere to special conditions to include the
198header. Specifically, a header should
199have <a href="#The__define_Guard">header guards</a> and include all
200other headers it needs.</p>
201
202<p>Prefer placing the definitions for template and inline functions in
203the same file as their declarations. The definitions of these
204constructs must be included into every <code>.cc</code> file that uses
205them, or the program may fail to link in some build configurations. If
206declarations and definitions are in different files, including the
207former should transitively include the latter. Do not move these
208definitions to separately included header files (<code>-inl.h</code>);
209this practice was common in the past, but is no longer allowed.</p>
210
211<p>As an exception, a template that is explicitly instantiated for
212all relevant sets of template arguments, or that is a private
213implementation detail of a class, is allowed to be defined in the one
214and only <code>.cc</code> file that instantiates the template.</p>
215
216<p>There are rare cases where a file designed to be included is not
217self-contained. These are typically intended to be included at unusual
218locations, such as the middle of another file. They might not
219use <a href="#The__define_Guard">header guards</a>, and might not include
220their prerequisites. Name such files with the <code>.inc</code>
221extension. Use sparingly, and prefer self-contained headers when
222possible.</p>
223
Ted Osborne505ba682018-01-30 12:36:50 -0500224<h3 id="The__define_Guard">The #define Guard</h3>
225
Ted Osborne505ba682018-01-30 12:36:50 -0500226<p>All header files should have <code>#define</code> guards to
227prevent multiple inclusion. The format of the symbol name
228should be
Victor Costanf0314ea2019-09-01 20:42:44 -0700229
Ted Osborne505ba682018-01-30 12:36:50 -0500230<code><i>&lt;PROJECT&gt;</i>_<i>&lt;PATH&gt;</i>_<i>&lt;FILE&gt;</i>_H_</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500231
232
233
Victor Costanf0314ea2019-09-01 20:42:44 -0700234<div>
Ted Osborne505ba682018-01-30 12:36:50 -0500235<p>To guarantee uniqueness, they should
236be based on the full path in a project's source tree. For
237example, the file <code>foo/src/bar/baz.h</code> in
238project <code>foo</code> should have the following
239guard:</p>
Victor Costanf0314ea2019-09-01 20:42:44 -0700240</div>
Ted Osborne505ba682018-01-30 12:36:50 -0500241
242<pre>#ifndef FOO_BAR_BAZ_H_
243#define FOO_BAR_BAZ_H_
244
245...
246
247#endif // FOO_BAR_BAZ_H_
248</pre>
249
250
251
Ted Osborne505ba682018-01-30 12:36:50 -0500252<h3 id="Forward_Declarations">Forward Declarations</h3>
253
Victor Costanf0314ea2019-09-01 20:42:44 -0700254<p>Avoid using forward declarations where possible.
255Instead, <code>#include</code> the headers you need.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500256
Victor Costanf0314ea2019-09-01 20:42:44 -0700257<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500258<p>A "forward declaration" is a declaration of a class,
259function, or template without an associated definition.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500260
Victor Costanf0314ea2019-09-01 20:42:44 -0700261<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500262<ul>
263 <li>Forward declarations can save compile time, as
264 <code>#include</code>s force the compiler to open
265 more files and process more input.</li>
266
267 <li>Forward declarations can save on unnecessary
268 recompilation. <code>#include</code>s can force
269 your code to be recompiled more often, due to unrelated
270 changes in the header.</li>
271</ul>
Ted Osborne505ba682018-01-30 12:36:50 -0500272
Victor Costanf0314ea2019-09-01 20:42:44 -0700273<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500274<ul>
275 <li>Forward declarations can hide a dependency, allowing
276 user code to skip necessary recompilation when headers
277 change.</li>
278
279 <li>A forward declaration may be broken by subsequent
280 changes to the library. Forward declarations of functions
281 and templates can prevent the header owners from making
282 otherwise-compatible changes to their APIs, such as
283 widening a parameter type, adding a template parameter
284 with a default value, or migrating to a new namespace.</li>
285
286 <li>Forward declaring symbols from namespace
287 <code>std::</code> yields undefined behavior.</li>
288
289 <li>It can be difficult to determine whether a forward
290 declaration or a full <code>#include</code> is needed.
291 Replacing an <code>#include</code> with a forward
292 declaration can silently change the meaning of
293 code:
294 <pre> // b.h:
295 struct B {};
296 struct D : B {};
297
298 // good_user.cc:
299 #include "b.h"
300 void f(B*);
301 void f(void*);
302 void test(D* x) { f(x); } // calls f(B*)
303 </pre>
304 If the <code>#include</code> was replaced with forward
305 decls for <code>B</code> and <code>D</code>,
306 <code>test()</code> would call <code>f(void*)</code>.
307 </li>
308
309 <li>Forward declaring multiple symbols from a header
310 can be more verbose than simply
311 <code>#include</code>ing the header.</li>
312
313 <li>Structuring code to enable forward declarations
314 (e.g. using pointer members instead of object members)
315 can make the code slower and more complex.</li>
316
Ted Osborne505ba682018-01-30 12:36:50 -0500317
Victor Costanf0314ea2019-09-01 20:42:44 -0700318</ul>
319
320<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500321<ul>
322 <li>Try to avoid forward declarations of entities
323 defined in another project.</li>
324
325 <li>When using a function declared in a header file,
326 always <code>#include</code> that header.</li>
327
328 <li>When using a class template, prefer to
329 <code>#include</code> its header file.</li>
330</ul>
331
332<p>Please see <a href="#Names_and_Order_of_Includes">Names and Order
333of Includes</a> for rules about when to #include a header.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500334
335<h3 id="Inline_Functions">Inline Functions</h3>
336
Ted Osborne505ba682018-01-30 12:36:50 -0500337<p>Define functions inline only when they are small, say, 10
338lines or fewer.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500339
Victor Costanf0314ea2019-09-01 20:42:44 -0700340<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500341<p>You can declare functions in a way that allows the compiler to expand
342them inline rather than calling them through the usual
343function call mechanism.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500344
Victor Costanf0314ea2019-09-01 20:42:44 -0700345<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500346<p>Inlining a function can generate more efficient object
347code, as long as the inlined function is small. Feel free
348to inline accessors and mutators, and other short,
349performance-critical functions.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500350
Victor Costanf0314ea2019-09-01 20:42:44 -0700351<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500352<p>Overuse of inlining can actually make programs slower.
353Depending on a function's size, inlining it can cause the
354code size to increase or decrease. Inlining a very small
355accessor function will usually decrease code size while
356inlining a very large function can dramatically increase
357code size. On modern processors smaller code usually runs
358faster due to better use of the instruction cache.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500359
Victor Costanf0314ea2019-09-01 20:42:44 -0700360<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500361<p>A decent rule of thumb is to not inline a function if
362it is more than 10 lines long. Beware of destructors,
363which are often longer than they appear because of
364implicit member- and base-destructor calls!</p>
365
366<p>Another useful rule of thumb: it's typically not cost
367effective to inline functions with loops or switch
368statements (unless, in the common case, the loop or
369switch statement is never executed).</p>
370
371<p>It is important to know that functions are not always
372inlined even if they are declared as such; for example,
373virtual and recursive functions are not normally inlined.
374Usually recursive functions should not be inline. The
375main reason for making a virtual function inline is to
376place its definition in the class, either for convenience
377or to document its behavior, e.g., for accessors and
378mutators.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500379
380<h3 id="Names_and_Order_of_Includes">Names and Order of Includes</h3>
381
Victor Costanf0314ea2019-09-01 20:42:44 -0700382<p>Include headers in the following order: Related header, C system headers,
383C++ standard library headers,
384other libraries' headers, your project's
385headers.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500386
Ted Osborne505ba682018-01-30 12:36:50 -0500387<p>
388All of a project's header files should be
389listed as descendants of the project's source
Victor Costanf0314ea2019-09-01 20:42:44 -0700390directory without use of UNIX directory aliases
Ted Osborne505ba682018-01-30 12:36:50 -0500391<code>.</code> (the current directory) or <code>..</code>
392(the parent directory). For example,
393
394<code>google-awesome-project/src/base/logging.h</code>
395should be included as:</p>
396
397<pre>#include "base/logging.h"
398</pre>
399
400<p>In <code><var>dir/foo</var>.cc</code> or
401<code><var>dir/foo_test</var>.cc</code>, whose main
402purpose is to implement or test the stuff in
403<code><var>dir2/foo2</var>.h</code>, order your includes
404as follows:</p>
405
406<ol>
407 <li><code><var>dir2/foo2</var>.h</code>.</li>
408
Victor Costan6dfd9d92018-02-05 18:30:35 -0800409 <li>A blank line</li>
410
Victor Costanf0314ea2019-09-01 20:42:44 -0700411 <li>C system headers (more precisely: headers in angle brackets with the
412 <code>.h</code> extension), e.g. <code>&lt;unistd.h&gt;</code>,
413 <code>&lt;stdlib.h&gt;</code>.</li>
Ted Osborne505ba682018-01-30 12:36:50 -0500414
Victor Costan6dfd9d92018-02-05 18:30:35 -0800415 <li>A blank line</li>
416
Victor Costanf0314ea2019-09-01 20:42:44 -0700417 <li>C++ standard library headers (without file extension), e.g.
418 <code>&lt;algorithm&gt;</code>, <code>&lt;cstddef&gt;</code>.</li>
419
420 <li>A blank line</li>
421
422 <div>
423 <li>Other libraries' <code>.h</code> files.</li>
424 </div>
Ted Osborne505ba682018-01-30 12:36:50 -0500425
426 <li>
427 Your project's <code>.h</code>
428 files.</li>
429</ol>
430
Victor Costanf0314ea2019-09-01 20:42:44 -0700431<p>Separate each non-empty group with one blank line.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800432
Victor Costanf0314ea2019-09-01 20:42:44 -0700433<p>With the preferred ordering, if the related header
Ted Osborne505ba682018-01-30 12:36:50 -0500434<code><var>dir2/foo2</var>.h</code> omits any necessary
435includes, the build of <code><var>dir/foo</var>.cc</code>
436or <code><var>dir/foo</var>_test.cc</code> will break.
437Thus, this rule ensures that build breaks show up first
438for the people working on these files, not for innocent
439people in other packages.</p>
440
441<p><code><var>dir/foo</var>.cc</code> and
442<code><var>dir2/foo2</var>.h</code> are usually in the same
443directory (e.g. <code>base/basictypes_test.cc</code> and
444<code>base/basictypes.h</code>), but may sometimes be in different
445directories too.</p>
446
447
448
Victor Costanf0314ea2019-09-01 20:42:44 -0700449<p>Note that the C headers such as <code>stddef.h</code>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800450are essentially interchangeable with their C++ counterparts
Victor Costanf0314ea2019-09-01 20:42:44 -0700451(<code>cstddef</code>).
Victor Costan6dfd9d92018-02-05 18:30:35 -0800452Either style is acceptable, but prefer consistency with existing code.</p>
453
Ted Osborne505ba682018-01-30 12:36:50 -0500454<p>Within each section the includes should be ordered
455alphabetically. Note that older code might not conform to
456this rule and should be fixed when convenient.</p>
457
458<p>You should include all the headers that define the symbols you rely
459upon, except in the unusual case of <a href="#Forward_Declarations">forward
460declaration</a>. If you rely on symbols from <code>bar.h</code>,
461don't count on the fact that you included <code>foo.h</code> which
462(currently) includes <code>bar.h</code>: include <code>bar.h</code>
463yourself, unless <code>foo.h</code> explicitly demonstrates its intent
Victor Costanf0314ea2019-09-01 20:42:44 -0700464to provide you the symbols of <code>bar.h</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500465
466<p>For example, the includes in
467
468<code>google-awesome-project/src/foo/internal/fooserver.cc</code>
469might look like this:</p>
470
Ted Osborne505ba682018-01-30 12:36:50 -0500471<pre>#include "foo/server/fooserver.h"
472
473#include &lt;sys/types.h&gt;
474#include &lt;unistd.h&gt;
Victor Costanf0314ea2019-09-01 20:42:44 -0700475
476#include &lt;string&gt;
Ted Osborne505ba682018-01-30 12:36:50 -0500477#include &lt;vector&gt;
478
479#include "base/basictypes.h"
480#include "base/commandlineflags.h"
481#include "foo/server/bar.h"
482</pre>
483
Victor Costanf0314ea2019-09-01 20:42:44 -0700484<p><b>Exception:</b></p>
485
486<p>Sometimes, system-specific code needs
Ted Osborne505ba682018-01-30 12:36:50 -0500487conditional includes. Such code can put conditional
488includes after other includes. Of course, keep your
489system-specific code small and localized. Example:</p>
490
491<pre>#include "foo/public/fooserver.h"
492
493#include "base/port.h" // For LANG_CXX11.
494
495#ifdef LANG_CXX11
496#include &lt;initializer_list&gt;
497#endif // LANG_CXX11
498</pre>
499
Ted Osborne505ba682018-01-30 12:36:50 -0500500<h2 id="Scoping">Scoping</h2>
501
502<h3 id="Namespaces">Namespaces</h3>
503
Ted Osborne505ba682018-01-30 12:36:50 -0500504<p>With few exceptions, place code in a namespace. Namespaces
505should have unique names based on the project name, and possibly
506its path. Do not use <i>using-directives</i> (e.g.
507<code>using namespace foo</code>). Do not use
508inline namespaces. For unnamed namespaces, see
509<a href="#Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and
510Static Variables</a>.
Ted Osborne505ba682018-01-30 12:36:50 -0500511
Victor Costanf0314ea2019-09-01 20:42:44 -0700512</p><p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500513<p>Namespaces subdivide the global scope
514into distinct, named scopes, and so are useful for preventing
515name collisions in the global scope.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500516
Victor Costanf0314ea2019-09-01 20:42:44 -0700517<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500518
519<p>Namespaces provide a method for preventing name conflicts
520in large programs while allowing most code to use reasonably
521short names.</p>
522
523<p>For example, if two different projects have a class
524<code>Foo</code> in the global scope, these symbols may
525collide at compile time or at runtime. If each project
526places their code in a namespace, <code>project1::Foo</code>
527and <code>project2::Foo</code> are now distinct symbols that
528do not collide, and code within each project's namespace
529can continue to refer to <code>Foo</code> without the prefix.</p>
530
531<p>Inline namespaces automatically place their names in
532the enclosing scope. Consider the following snippet, for
533example:</p>
534
Victor Costanf0314ea2019-09-01 20:42:44 -0700535<pre class="neutralcode">namespace outer {
Victor Costan6dfd9d92018-02-05 18:30:35 -0800536inline namespace inner {
Ted Osborne505ba682018-01-30 12:36:50 -0500537 void foo();
Victor Costan6dfd9d92018-02-05 18:30:35 -0800538} // namespace inner
539} // namespace outer
Ted Osborne505ba682018-01-30 12:36:50 -0500540</pre>
541
Victor Costan6dfd9d92018-02-05 18:30:35 -0800542<p>The expressions <code>outer::inner::foo()</code> and
543<code>outer::foo()</code> are interchangeable. Inline
Ted Osborne505ba682018-01-30 12:36:50 -0500544namespaces are primarily intended for ABI compatibility
545across versions.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500546
Victor Costanf0314ea2019-09-01 20:42:44 -0700547<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500548
549<p>Namespaces can be confusing, because they complicate
550the mechanics of figuring out what definition a name refers
551to.</p>
552
553<p>Inline namespaces, in particular, can be confusing
554because names aren't actually restricted to the namespace
555where they are declared. They are only useful as part of
556some larger versioning policy.</p>
557
558<p>In some contexts, it's necessary to repeatedly refer to
559symbols by their fully-qualified names. For deeply-nested
560namespaces, this can add a lot of clutter.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500561
Victor Costanf0314ea2019-09-01 20:42:44 -0700562<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500563
564<p>Namespaces should be used as follows:</p>
565
566<ul>
567 <li>Follow the rules on <a href="#Namespace_Names">Namespace Names</a>.
568 </li><li>Terminate namespaces with comments as shown in the given examples.
569 </li><li>
570
571 <p>Namespaces wrap the entire source file after
Victor Costanf0314ea2019-09-01 20:42:44 -0700572 includes,
Ted Osborne505ba682018-01-30 12:36:50 -0500573 <a href="https://gflags.github.io/gflags/">
574 gflags</a> definitions/declarations
575 and forward declarations of classes from other namespaces.</p>
576
577<pre>// In the .h file
578namespace mynamespace {
579
580// All declarations are within the namespace scope.
581// Notice the lack of indentation.
582class MyClass {
583 public:
584 ...
585 void Foo();
586};
587
588} // namespace mynamespace
589</pre>
590
591<pre>// In the .cc file
592namespace mynamespace {
593
594// Definition of functions is within scope of the namespace.
595void MyClass::Foo() {
596 ...
597}
598
599} // namespace mynamespace
600</pre>
601
602 <p>More complex <code>.cc</code> files might have additional details,
603 like flags or using-declarations.</p>
604
605<pre>#include "a.h"
606
Victor Costanf0314ea2019-09-01 20:42:44 -0700607ABSL_FLAG(bool, someflag, false, "dummy flag");
Ted Osborne505ba682018-01-30 12:36:50 -0500608
Victor Costan6dfd9d92018-02-05 18:30:35 -0800609namespace mynamespace {
Ted Osborne505ba682018-01-30 12:36:50 -0500610
Victor Costanf0314ea2019-09-01 20:42:44 -0700611using ::foo::Bar;
Ted Osborne505ba682018-01-30 12:36:50 -0500612
Victor Costan6dfd9d92018-02-05 18:30:35 -0800613...code for mynamespace... // Code goes against the left margin.
Ted Osborne505ba682018-01-30 12:36:50 -0500614
Victor Costan6dfd9d92018-02-05 18:30:35 -0800615} // namespace mynamespace
Ted Osborne505ba682018-01-30 12:36:50 -0500616</pre>
617 </li>
618
Victor Costan4b9c0c02018-02-20 14:58:48 -0800619 <li>To place generated protocol
620 message code in a namespace, use the
621 <code>package</code> specifier in the
622 <code>.proto</code> file. See
Victor Costanf0314ea2019-09-01 20:42:44 -0700623
624
Victor Costan4b9c0c02018-02-20 14:58:48 -0800625 <a href="https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#package">
626 Protocol Buffer Packages</a>
627 for details.</li>
Ted Osborne505ba682018-01-30 12:36:50 -0500628
629 <li>Do not declare anything in namespace
630 <code>std</code>, including forward declarations of
631 standard library classes. Declaring entities in
632 namespace <code>std</code> is undefined behavior, i.e.,
633 not portable. To declare entities from the standard
634 library, include the appropriate header file.</li>
635
636 <li><p>You may not use a <i>using-directive</i>
637 to make all names from a namespace available.</p>
638
639<pre class="badcode">// Forbidden -- This pollutes the namespace.
640using namespace foo;
641</pre>
642 </li>
643
644 <li><p>Do not use <i>Namespace aliases</i> at namespace scope
645 in header files except in explicitly marked
646 internal-only namespaces, because anything imported into a namespace
647 in a header file becomes part of the public
648 API exported by that file.</p>
649
650<pre>// Shorten access to some commonly used names in .cc files.
651namespace baz = ::foo::bar::baz;
652</pre>
653
654<pre>// Shorten access to some commonly used names (in a .h file).
655namespace librarian {
656namespace impl { // Internal, not part of the API.
657namespace sidetable = ::pipeline_diagnostics::sidetable;
658} // namespace impl
659
660inline void my_inline_function() {
661 // namespace alias local to a function (or method).
662 namespace baz = ::foo::bar::baz;
663 ...
664}
665} // namespace librarian
666</pre>
667
668 </li><li>Do not use inline namespaces.</li>
669</ul>
Ted Osborne505ba682018-01-30 12:36:50 -0500670
671<h3 id="Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and Static
672Variables</h3>
673
Ted Osborne505ba682018-01-30 12:36:50 -0500674<p>When definitions in a <code>.cc</code> file do not need to be
675referenced outside that file, place them in an unnamed
676namespace or declare them <code>static</code>. Do not use either
677of these constructs in <code>.h</code> files.
Ted Osborne505ba682018-01-30 12:36:50 -0500678
Victor Costanf0314ea2019-09-01 20:42:44 -0700679</p><p class="definition"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800680<p>All declarations can be given internal linkage by placing them in unnamed
681namespaces. Functions and variables can also be given internal linkage by
Ted Osborne505ba682018-01-30 12:36:50 -0500682declaring them <code>static</code>. This means that anything you're declaring
Victor Costan6dfd9d92018-02-05 18:30:35 -0800683can't be accessed from another file. If a different file declares something with
684the same name, then the two entities are completely independent.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500685
Victor Costanf0314ea2019-09-01 20:42:44 -0700686<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500687
688<p>Use of internal linkage in <code>.cc</code> files is encouraged
689for all code that does not need to be referenced elsewhere.
690Do not use internal linkage in <code>.h</code> files.</p>
691
692<p>Format unnamed namespaces like named namespaces. In the
693 terminating comment, leave the namespace name empty:</p>
694
695<pre>namespace {
696...
697} // namespace
698</pre>
Ted Osborne505ba682018-01-30 12:36:50 -0500699
700<h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3>
701
Ted Osborne505ba682018-01-30 12:36:50 -0500702<p>Prefer placing nonmember functions in a namespace; use completely global
Victor Costan6dfd9d92018-02-05 18:30:35 -0800703functions rarely. Do not use a class simply to group static functions. Static
704methods of a class should generally be closely related to instances of the
705class or the class's static data.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500706
Ted Osborne505ba682018-01-30 12:36:50 -0500707
Victor Costanf0314ea2019-09-01 20:42:44 -0700708<p class="pros"></p>
709<p>Nonmember and static member functions can be useful in
710some situations. Putting nonmember functions in a
711namespace avoids polluting the global namespace.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500712
Victor Costanf0314ea2019-09-01 20:42:44 -0700713<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500714<p>Nonmember and static member functions may make more sense
715as members of a new class, especially if they access
716external resources or have significant dependencies.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500717
Victor Costanf0314ea2019-09-01 20:42:44 -0700718<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -0500719<p>Sometimes it is useful to define a
720function not bound to a class instance. Such a function
721can be either a static member or a nonmember function.
722Nonmember functions should not depend on external
723variables, and should nearly always exist in a namespace.
Victor Costan6dfd9d92018-02-05 18:30:35 -0800724Do not create classes only to group static member functions;
725this is no different than just giving the function names a
726common prefix, and such grouping is usually unnecessary anyway.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500727
728<p>If you define a nonmember function and it is only
729needed in its <code>.cc</code> file, use
730<a href="#Unnamed_Namespaces_and_Static_Variables">internal linkage</a> to limit
731its scope.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500732
733<h3 id="Local_Variables">Local Variables</h3>
734
Ted Osborne505ba682018-01-30 12:36:50 -0500735<p>Place a function's variables in the narrowest scope
736possible, and initialize variables in the declaration.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500737
738<p>C++ allows you to declare variables anywhere in a
739function. We encourage you to declare them in as local a
740scope as possible, and as close to the first use as
741possible. This makes it easier for the reader to find the
742declaration and see what type the variable is and what it
743was initialized to. In particular, initialization should
744be used instead of declaration and assignment, e.g.:</p>
745
746<pre class="badcode">int i;
747i = f(); // Bad -- initialization separate from declaration.
748</pre>
749
750<pre>int j = g(); // Good -- declaration has initialization.
751</pre>
752
753<pre class="badcode">std::vector&lt;int&gt; v;
754v.push_back(1); // Prefer initializing using brace initialization.
755v.push_back(2);
756</pre>
757
758<pre>std::vector&lt;int&gt; v = {1, 2}; // Good -- v starts initialized.
759</pre>
760
761<p>Variables needed for <code>if</code>, <code>while</code>
762and <code>for</code> statements should normally be declared
763within those statements, so that such variables are confined
764to those scopes. E.g.:</p>
765
766<pre>while (const char* p = strchr(str, '/')) str = p + 1;
767</pre>
768
769<p>There is one caveat: if the variable is an object, its
770constructor is invoked every time it enters scope and is
771created, and its destructor is invoked every time it goes
772out of scope.</p>
773
774<pre class="badcode">// Inefficient implementation:
775for (int i = 0; i &lt; 1000000; ++i) {
776 Foo f; // My ctor and dtor get called 1000000 times each.
777 f.DoSomething(i);
778}
779</pre>
780
781<p>It may be more efficient to declare such a variable
782used in a loop outside that loop:</p>
783
784<pre>Foo f; // My ctor and dtor get called once each.
785for (int i = 0; i &lt; 1000000; ++i) {
786 f.DoSomething(i);
787}
788</pre>
789
Ted Osborne505ba682018-01-30 12:36:50 -0500790<h3 id="Static_and_Global_Variables">Static and Global Variables</h3>
791
Victor Costan6dfd9d92018-02-05 18:30:35 -0800792<p>Objects with
793<a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration">
794static storage duration</a> are forbidden unless they are
795<a href="http://en.cppreference.com/w/cpp/types/is_destructible">trivially
796destructible</a>. Informally this means that the destructor does not do
797anything, even taking member and base destructors into account. More formally it
798means that the type has no user-defined or virtual destructor and that all bases
799and non-static members are trivially destructible.
800Static function-local variables may use dynamic initialization.
801Use of dynamic initialization for static class member variables or variables at
802namespace scope is discouraged, but allowed in limited circumstances; see below
803for details.</p>
804
805<p>As a rule of thumb: a global variable satisfies these requirements if its
806declaration, considered in isolation, could be <code>constexpr</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500807
Victor Costanf0314ea2019-09-01 20:42:44 -0700808<p class="definition"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800809<p>Every object has a <dfn>storage duration</dfn>, which correlates with its
810lifetime. Objects with static storage duration live from the point of their
811initialization until the end of the program. Such objects appear as variables at
812namespace scope ("global variables"), as static data members of classes, or as
813function-local variables that are declared with the <code>static</code>
814specifier. Function-local static variables are initialized when control first
815passes through their declaration; all other objects with static storage duration
816are initialized as part of program start-up. All objects with static storage
817duration are destroyed at program exit (which happens before unjoined threads
818are terminated).</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500819
Victor Costan6dfd9d92018-02-05 18:30:35 -0800820<p>Initialization may be <dfn>dynamic</dfn>, which means that something
821non-trivial happens during initialization. (For example, consider a constructor
822that allocates memory, or a variable that is initialized with the current
823process ID.) The other kind of initialization is <dfn>static</dfn>
824initialization. The two aren't quite opposites, though: static
825initialization <em>always</em> happens to objects with static storage duration
826(initializing the object either to a given constant or to a representation
827consisting of all bytes set to zero), whereas dynamic initialization happens
828after that, if required.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500829
Victor Costanf0314ea2019-09-01 20:42:44 -0700830<p class="pros"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800831<p>Global and static variables are very useful for a large number of
832applications: named constants, auxiliary data structures internal to some
833translation unit, command-line flags, logging, registration mechanisms,
834background infrastructure, etc.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500835
Victor Costanf0314ea2019-09-01 20:42:44 -0700836<p class="cons"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800837<p>Global and static variables that use dynamic initialization or have
838non-trivial destructors create complexity that can easily lead to hard-to-find
839bugs. Dynamic initialization is not ordered across translation units, and
840neither is destruction (except that destruction
841happens in reverse order of initialization). When one initialization refers to
842another variable with static storage duration, it is possible that this causes
843an object to be accessed before its lifetime has begun (or after its lifetime
844has ended). Moreover, when a program starts threads that are not joined at exit,
845those threads may attempt to access objects after their lifetime has ended if
846their destructor has already run.</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500847
Victor Costanf0314ea2019-09-01 20:42:44 -0700848<p class="decision"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800849<h4>Decision on destruction</h4>
850
851<p>When destructors are trivial, their execution is not subject to ordering at
852all (they are effectively not "run"); otherwise we are exposed to the risk of
853accessing objects after the end of their lifetime. Therefore, we only allow
854objects with static storage duration if they are trivially destructible.
855Fundamental types (like pointers and <code>int</code>) are trivially
856destructible, as are arrays of trivially destructible types. Note that
857variables marked with <code>constexpr</code> are trivially destructible.</p>
858<pre>const int kNum = 10; // allowed
859
860struct X { int n; };
861const X kX[] = {{1}, {2}, {3}}; // allowed
862
863void foo() {
864 static const char* const kMessages[] = {"hello", "world"}; // allowed
865}
866
867// allowed: constexpr guarantees trivial destructor
868constexpr std::array&lt;int, 3&gt; kArray = {{1, 2, 3}};</pre>
869<pre class="badcode">// bad: non-trivial destructor
Victor Costanf0314ea2019-09-01 20:42:44 -0700870const std::string kFoo = "foo";
Victor Costan6dfd9d92018-02-05 18:30:35 -0800871
872// bad for the same reason, even though kBar is a reference (the
873// rule also applies to lifetime-extended temporary objects)
Victor Costanf0314ea2019-09-01 20:42:44 -0700874const std::string&amp; kBar = StrCat("a", "b", "c");
Victor Costan6dfd9d92018-02-05 18:30:35 -0800875
876void bar() {
877 // bad: non-trivial destructor
878 static std::map&lt;int, int&gt; kData = {{1, 0}, {2, 0}, {3, 0}};
879}</pre>
880
881<p>Note that references are not objects, and thus they are not subject to the
882constraints on destructibility. The constraint on dynamic initialization still
883applies, though. In particular, a function-local static reference of the form
884<code>static T&amp; t = *new T;</code> is allowed.</p>
885
886<h4>Decision on initialization</h4>
887
888<p>Initialization is a more complex topic. This is because we must not only
889consider whether class constructors execute, but we must also consider the
890evaluation of the initializer:</p>
891<pre class="neutralcode">int n = 5; // fine
892int m = f(); // ? (depends on f)
893Foo x; // ? (depends on Foo::Foo)
Victor Costanf0314ea2019-09-01 20:42:44 -0700894Bar y = g(); // ? (depends on g and on Bar::Bar)
895</pre>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800896
897<p>All but the first statement expose us to indeterminate initialization
898ordering.</p>
899
900<p>The concept we are looking for is called <em>constant initialization</em> in
901the formal language of the C++ standard. It means that the initializing
902expression is a constant expression, and if the object is initialized by a
903constructor call, then the constructor must be specified as
904<code>constexpr</code>, too:</p>
905<pre>struct Foo { constexpr Foo(int) {} };
906
907int n = 5; // fine, 5 is a constant expression
908Foo x(2); // fine, 2 is a constant expression and the chosen constructor is constexpr
909Foo a[] = { Foo(1), Foo(2), Foo(3) }; // fine</pre>
910
911<p>Constant initialization is always allowed. Constant initialization of
912static storage duration variables should be marked with <code>constexpr</code>
Victor Costan4b9c0c02018-02-20 14:58:48 -0800913or where possible the
914
Victor Costanf0314ea2019-09-01 20:42:44 -0700915
Victor Costan4b9c0c02018-02-20 14:58:48 -0800916<a href="https://github.com/abseil/abseil-cpp/blob/03c1513538584f4a04d666be5eb469e3979febba/absl/base/attributes.h#L540">
917<code>ABSL_CONST_INIT</code></a>
918attribute. Any non-local static storage
Victor Costan6dfd9d92018-02-05 18:30:35 -0800919duration variable that is not so marked should be presumed to have
920dynamic initialization, and reviewed very carefully.</p>
921
922<p>By contrast, the following initializations are problematic:</p>
923
Victor Costanb89a7752018-07-31 10:17:48 -0700924<pre class="badcode">// Some declarations used below.
925time_t time(time_t*); // not constexpr!
Victor Costan6dfd9d92018-02-05 18:30:35 -0800926int f(); // not constexpr!
927struct Bar { Bar() {} };
928
Victor Costanb89a7752018-07-31 10:17:48 -0700929// Problematic initializations.
Victor Costan6dfd9d92018-02-05 18:30:35 -0800930time_t m = time(nullptr); // initializing expression not a constant expression
931Foo y(f()); // ditto
932Bar b; // chosen constructor Bar::Bar() not constexpr</pre>
933
934<p>Dynamic initialization of nonlocal variables is discouraged, and in general
935it is forbidden. However, we do permit it if no aspect of the program depends
936on the sequencing of this initialization with respect to all other
937initializations. Under those restrictions, the ordering of the initialization
938does not make an observable difference. For example:</p>
939<pre>int p = getpid(); // allowed, as long as no other static variable
940 // uses p in its own initialization</pre>
941
942<p>Dynamic initialization of static local variables is allowed (and common).</p>
Ted Osborne505ba682018-01-30 12:36:50 -0500943
944
945
Victor Costan6dfd9d92018-02-05 18:30:35 -0800946<h4>Common patterns</h4>
Ted Osborne505ba682018-01-30 12:36:50 -0500947
Victor Costan6dfd9d92018-02-05 18:30:35 -0800948<ul>
949 <li>Global strings: if you require a global or static string constant,
950 consider using a simple character array, or a char pointer to the first
951 element of a string literal. String literals have static storage duration
952 already and are usually sufficient.</li>
953 <li>Maps, sets, and other dynamic containers: if you require a static, fixed
954 collection, such as a set to search against or a lookup table, you cannot
955 use the dynamic containers from the standard library as a static variable,
956 since they have non-trivial destructors. Instead, consider a simple array of
957 trivial types, e.g. an array of arrays of ints (for a "map from int to
958 int"), or an array of pairs (e.g. pairs of <code>int</code> and <code>const
959 char*</code>). For small collections, linear search is entirely sufficient
Victor Costanf0314ea2019-09-01 20:42:44 -0700960 (and efficient, due to memory locality); consider using the facilities from
961
962 <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/algorithm/container.h">absl/algorithm/container.h</a>
963
964
965 for the standard operations. If necessary, keep the collection in sorted
966 order and use a binary search algorithm. If you do really prefer a dynamic
967 container from the standard library, consider using a function-local static
968 pointer, as described below.</li>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800969 <li>Smart pointers (<code>unique_ptr</code>, <code>shared_ptr</code>): smart
970 pointers execute cleanup during destruction and are therefore forbidden.
971 Consider whether your use case fits into one of the other patterns described
972 in this section. One simple solution is to use a plain pointer to a
973 dynamically allocated object and never delete it (see last item).</li>
974 <li>Static variables of custom types: if you require static, constant data of
975 a type that you need to define yourself, give the type a trivial destructor
976 and a <code>constexpr</code> constructor.</li>
977 <li>If all else fails, you can create an object dynamically and never delete
Victor Costanf0314ea2019-09-01 20:42:44 -0700978 it by using a function-local static pointer or reference (e.g. <code>static
979 const auto&amp; impl = *new T(args...);</code>).</li>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800980</ul>
Ted Osborne505ba682018-01-30 12:36:50 -0500981
Victor Costan6dfd9d92018-02-05 18:30:35 -0800982<h3 id="thread_local">thread_local Variables</h3>
983
Victor Costan6dfd9d92018-02-05 18:30:35 -0800984<p><code>thread_local</code> variables that aren't declared inside a function
Victor Costan4b9c0c02018-02-20 14:58:48 -0800985must be initialized with a true compile-time constant,
986and this must be enforced by using the
987
Victor Costanf0314ea2019-09-01 20:42:44 -0700988
Victor Costan4b9c0c02018-02-20 14:58:48 -0800989<a href="https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h">
990<code>ABSL_CONST_INIT</code></a>
991attribute. Prefer
Victor Costan6dfd9d92018-02-05 18:30:35 -0800992<code>thread_local</code> over other ways of defining thread-local data.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800993
Victor Costanf0314ea2019-09-01 20:42:44 -0700994<p class="definition"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -0800995<p>Starting with C++11, variables can be declared with the
996<code>thread_local</code> specifier:</p>
997<pre>thread_local Foo foo = ...;
998</pre>
999<p>Such a variable is actually a collection of objects, so that when different
1000threads access it, they are actually accessing different objects.
1001<code>thread_local</code> variables are much like
1002<a href="#Static_and_Global_Variables">static storage duration variables</a>
1003in many respects. For instance, they can be declared at namespace scope,
1004inside functions, or as static class members, but not as ordinary class
1005members.</p>
1006
1007<p><code>thread_local</code> variable instances are initialized much like
1008static variables, except that they must be initialized separately for each
1009thread, rather than once at program startup. This means that
1010<code>thread_local</code> variables declared within a function are safe, but
1011other <code>thread_local</code> variables are subject to the same
1012initialization-order issues as static variables (and more besides).</p>
1013
1014<p><code>thread_local</code> variable instances are destroyed when their thread
1015terminates, so they do not have the destruction-order issues of static
1016variables.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001017
Victor Costanf0314ea2019-09-01 20:42:44 -07001018<p class="pros"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001019<ul>
1020 <li>Thread-local data is inherently safe from races (because only one thread
1021 can ordinarily access it), which makes <code>thread_local</code> useful for
1022 concurrent programming.</li>
1023 <li><code>thread_local</code> is the only standard-supported way of creating
1024 thread-local data.</li>
1025</ul>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001026
Victor Costanf0314ea2019-09-01 20:42:44 -07001027<p class="cons"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001028<ul>
1029 <li>Accessing a <code>thread_local</code> variable may trigger execution of
1030 an unpredictable and uncontrollable amount of other code.</li>
1031 <li><code>thread_local</code> variables are effectively global variables,
1032 and have all the drawbacks of global variables other than lack of
1033 thread-safety.</li>
1034 <li>The memory consumed by a <code>thread_local</code> variable scales with
1035 the number of running threads (in the worst case), which can be quite large
1036 in a program.</li>
1037 <li>An ordinary class member cannot be <code>thread_local</code>.</li>
1038 <li><code>thread_local</code> may not be as efficient as certain compiler
1039 intrinsics.</li>
1040</ul>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001041
Victor Costanf0314ea2019-09-01 20:42:44 -07001042<p class="decision"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001043 <p><code>thread_local</code> variables inside a function have no safety
1044 concerns, so they can be used without restriction. Note that you can use
1045 a function-scope <code>thread_local</code> to simulate a class- or
1046 namespace-scope <code>thread_local</code> by defining a function or
1047 static method that exposes it:</p>
1048
1049<pre>Foo&amp; MyThreadLocalFoo() {
1050 thread_local Foo result = ComplicatedInitialization();
1051 return result;
1052}
1053</pre>
1054
Victor Costanf0314ea2019-09-01 20:42:44 -07001055<p><code>thread_local</code> variables at class or namespace scope must be
1056initialized with a true compile-time constant (i.e. they must have no
1057dynamic initialization). To enforce this, <code>thread_local</code> variables
1058at class or namespace scope must be annotated with
1059
1060
1061<a href="https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h">
1062<code>ABSL_CONST_INIT</code></a>
1063(or <code>constexpr</code>, but that should be rare):</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001064
Victor Costan4b9c0c02018-02-20 14:58:48 -08001065<pre>ABSL_CONST_INIT thread_local Foo foo = ...;
1066</pre>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001067
Victor Costanf0314ea2019-09-01 20:42:44 -07001068<p><code>thread_local</code> should be preferred over other mechanisms for
1069defining thread-local data.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001070
Ted Osborne505ba682018-01-30 12:36:50 -05001071<h2 id="Classes">Classes</h2>
1072
1073<p>Classes are the fundamental unit of code in C++. Naturally,
1074we use them extensively. This section lists the main dos and
1075don'ts you should follow when writing a class.</p>
1076
1077<h3 id="Doing_Work_in_Constructors">Doing Work in Constructors</h3>
1078
Ted Osborne505ba682018-01-30 12:36:50 -05001079<p>Avoid virtual method calls in constructors, and avoid
1080initialization that can fail if you can't signal an error.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001081
Victor Costanf0314ea2019-09-01 20:42:44 -07001082<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001083<p>It is possible to perform arbitrary initialization in the body
1084of the constructor.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001085
Victor Costanf0314ea2019-09-01 20:42:44 -07001086<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001087<ul>
1088 <li>No need to worry about whether the class has been initialized or
1089 not.</li>
1090
1091 <li>Objects that are fully initialized by constructor call can
1092 be <code>const</code> and may also be easier to use with standard containers
1093 or algorithms.</li>
1094</ul>
1095
Victor Costanf0314ea2019-09-01 20:42:44 -07001096<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001097<ul>
1098 <li>If the work calls virtual functions, these calls
1099 will not get dispatched to the subclass
1100 implementations. Future modification to your class can
1101 quietly introduce this problem even if your class is
1102 not currently subclassed, causing much confusion.</li>
1103
1104 <li>There is no easy way for constructors to signal errors, short of
1105 crashing the program (not always appropriate) or using exceptions
1106 (which are <a href="#Exceptions">forbidden</a>).</li>
1107
1108 <li>If the work fails, we now have an object whose initialization
1109 code failed, so it may be an unusual state requiring a <code>bool
1110 IsValid()</code> state checking mechanism (or similar) which is easy
1111 to forget to call.</li>
1112
1113 <li>You cannot take the address of a constructor, so whatever work
1114 is done in the constructor cannot easily be handed off to, for
1115 example, another thread.</li>
1116</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05001117
Victor Costanf0314ea2019-09-01 20:42:44 -07001118<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001119<p>Constructors should never call virtual functions. If appropriate
Victor Costanf0314ea2019-09-01 20:42:44 -07001120for your code ,
Ted Osborne505ba682018-01-30 12:36:50 -05001121terminating the program may be an appropriate error handling
1122response. Otherwise, consider a factory function
Victor Costan4b9c0c02018-02-20 14:58:48 -08001123or <code>Init()</code> method as described in
Victor Costan4b9c0c02018-02-20 14:58:48 -08001124<a href="https://abseil.io/tips/42">TotW #42</a>
1125.
1126Avoid <code>Init()</code> methods on objects with
Ted Osborne505ba682018-01-30 12:36:50 -05001127no other states that affect which public methods may be called
1128(semi-constructed objects of this form are particularly hard to work
1129with correctly).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001130
1131<a id="Explicit_Constructors"></a>
1132<h3 id="Implicit_Conversions">Implicit Conversions</h3>
1133
Ted Osborne505ba682018-01-30 12:36:50 -05001134<p>Do not define implicit conversions. Use the <code>explicit</code>
1135keyword for conversion operators and single-argument
1136constructors.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001137
Victor Costanf0314ea2019-09-01 20:42:44 -07001138<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001139<p>Implicit conversions allow an
1140object of one type (called the <dfn>source type</dfn>) to
1141be used where a different type (called the <dfn>destination
1142type</dfn>) is expected, such as when passing an
1143<code>int</code> argument to a function that takes a
1144<code>double</code> parameter.</p>
1145
1146<p>In addition to the implicit conversions defined by the language,
1147users can define their own, by adding appropriate members to the
1148class definition of the source or destination type. An implicit
1149conversion in the source type is defined by a type conversion operator
1150named after the destination type (e.g. <code>operator
1151bool()</code>). An implicit conversion in the destination
1152type is defined by a constructor that can take the source type as
1153its only argument (or only argument with no default value).</p>
1154
1155<p>The <code>explicit</code> keyword can be applied to a constructor
1156or (since C++11) a conversion operator, to ensure that it can only be
1157used when the destination type is explicit at the point of use,
1158e.g. with a cast. This applies not only to implicit conversions, but to
1159C++11's list initialization syntax:</p>
1160<pre>class Foo {
1161 explicit Foo(int x, double y);
1162 ...
1163};
1164
1165void Func(Foo f);
1166</pre>
1167<pre class="badcode">Func({42, 3.14}); // Error
1168</pre>
1169This kind of code isn't technically an implicit conversion, but the
1170language treats it as one as far as <code>explicit</code> is concerned.
Ted Osborne505ba682018-01-30 12:36:50 -05001171
Victor Costanf0314ea2019-09-01 20:42:44 -07001172<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001173<ul>
1174<li>Implicit conversions can make a type more usable and
1175 expressive by eliminating the need to explicitly name a type
1176 when it's obvious.</li>
1177<li>Implicit conversions can be a simpler alternative to
Victor Costan4b9c0c02018-02-20 14:58:48 -08001178 overloading, such as when a single
1179 function with a <code>string_view</code> parameter takes the
Victor Costanf0314ea2019-09-01 20:42:44 -07001180 place of separate overloads for <code>std::string</code> and
Victor Costan4b9c0c02018-02-20 14:58:48 -08001181 <code>const char*</code>.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05001182<li>List initialization syntax is a concise and expressive
1183 way of initializing objects.</li>
1184</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05001185
Victor Costanf0314ea2019-09-01 20:42:44 -07001186<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001187<ul>
1188<li>Implicit conversions can hide type-mismatch bugs, where the
1189 destination type does not match the user's expectation, or
1190 the user is unaware that any conversion will take place.</li>
1191
1192<li>Implicit conversions can make code harder to read, particularly
1193 in the presence of overloading, by making it less obvious what
1194 code is actually getting called.</li>
1195
1196<li>Constructors that take a single argument may accidentally
1197 be usable as implicit type conversions, even if they are not
1198 intended to do so.</li>
1199
1200<li>When a single-argument constructor is not marked
1201 <code>explicit</code>, there's no reliable way to tell whether
1202 it's intended to define an implicit conversion, or the author
1203 simply forgot to mark it.</li>
1204
1205<li>It's not always clear which type should provide the conversion,
1206 and if they both do, the code becomes ambiguous.</li>
1207
1208<li>List initialization can suffer from the same problems if
1209 the destination type is implicit, particularly if the
1210 list has only a single element.</li>
1211</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05001212
Victor Costanf0314ea2019-09-01 20:42:44 -07001213<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001214<p>Type conversion operators, and constructors that are
1215callable with a single argument, must be marked
1216<code>explicit</code> in the class definition. As an
1217exception, copy and move constructors should not be
1218<code>explicit</code>, since they do not perform type
1219conversion. Implicit conversions can sometimes be necessary and
1220appropriate for types that are designed to transparently wrap other
Victor Costanf0314ea2019-09-01 20:42:44 -07001221types. In that case, contact
Ted Osborne505ba682018-01-30 12:36:50 -05001222your project leads to request
1223a waiver of this rule.</p>
1224
1225<p>Constructors that cannot be called with a single argument
Victor Costan6dfd9d92018-02-05 18:30:35 -08001226may omit <code>explicit</code>. Constructors that
Ted Osborne505ba682018-01-30 12:36:50 -05001227take a single <code>std::initializer_list</code> parameter should
1228also omit <code>explicit</code>, in order to support copy-initialization
1229(e.g. <code>MyType m = {1, 2};</code>).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001230
1231<h3 id="Copyable_Movable_Types">Copyable and Movable Types</h3>
1232<a id="Copy_Constructors"></a>
Victor Costanf0314ea2019-09-01 20:42:44 -07001233
1234<p>A class's public API must make clear whether the class is copyable,
Victor Costan6dfd9d92018-02-05 18:30:35 -08001235move-only, or neither copyable nor movable. Support copying and/or
1236moving if these operations are clear and meaningful for your type.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001237
Victor Costanf0314ea2019-09-01 20:42:44 -07001238<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001239<p>A movable type is one that can be initialized and assigned
Victor Costan6dfd9d92018-02-05 18:30:35 -08001240from temporaries.</p>
1241
1242<p>A copyable type is one that can be initialized or assigned from
1243any other object of the same type (so is also movable by definition), with the
1244stipulation that the value of the source does not change.
Ted Osborne505ba682018-01-30 12:36:50 -05001245<code>std::unique_ptr&lt;int&gt;</code> is an example of a movable but not
Victor Costan6dfd9d92018-02-05 18:30:35 -08001246copyable type (since the value of the source
1247<code>std::unique_ptr&lt;int&gt;</code> must be modified during assignment to
Victor Costanf0314ea2019-09-01 20:42:44 -07001248the destination). <code>int</code> and <code>std::string</code> are examples of
Victor Costan6dfd9d92018-02-05 18:30:35 -08001249movable types that are also copyable. (For <code>int</code>, the move and copy
Victor Costanf0314ea2019-09-01 20:42:44 -07001250operations are the same; for <code>std::string</code>, there exists a move operation
Victor Costan6dfd9d92018-02-05 18:30:35 -08001251that is less expensive than a copy.)</p>
1252
1253<p>For user-defined types, the copy behavior is defined by the copy
1254constructor and the copy-assignment operator. Move behavior is defined by the
1255move constructor and the move-assignment operator, if they exist, or by the
1256copy constructor and the copy-assignment operator otherwise.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001257
1258<p>The copy/move constructors can be implicitly invoked by the compiler
1259in some situations, e.g. when passing objects by value.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001260
Victor Costanf0314ea2019-09-01 20:42:44 -07001261<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001262<p>Objects of copyable and movable types can be passed and returned by value,
1263which makes APIs simpler, safer, and more general. Unlike when passing objects
1264by pointer or reference, there's no risk of confusion over ownership,
1265lifetime, mutability, and similar issues, and no need to specify them in the
1266contract. It also prevents non-local interactions between the client and the
1267implementation, which makes them easier to understand, maintain, and optimize by
1268the compiler. Further, such objects can be used with generic APIs that
1269require pass-by-value, such as most containers, and they allow for additional
1270flexibility in e.g., type composition.</p>
1271
1272<p>Copy/move constructors and assignment operators are usually
1273easier to define correctly than alternatives
1274like <code>Clone()</code>, <code>CopyFrom()</code> or <code>Swap()</code>,
1275because they can be generated by the compiler, either implicitly or
1276with <code>= default</code>. They are concise, and ensure
1277that all data members are copied. Copy and move
1278constructors are also generally more efficient, because they don't
1279require heap allocation or separate initialization and assignment
1280steps, and they're eligible for optimizations such as
1281
1282<a href="http://en.cppreference.com/w/cpp/language/copy_elision">
1283copy elision</a>.</p>
1284
1285<p>Move operations allow the implicit and efficient transfer of
1286resources out of rvalue objects. This allows a plainer coding style
1287in some cases.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001288
Victor Costanf0314ea2019-09-01 20:42:44 -07001289<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001290<p>Some types do not need to be copyable, and providing copy
1291operations for such types can be confusing, nonsensical, or outright
1292incorrect. Types representing singleton objects (<code>Registerer</code>),
1293objects tied to a specific scope (<code>Cleanup</code>), or closely coupled to
1294object identity (<code>Mutex</code>) cannot be copied meaningfully.
1295Copy operations for base class types that are to be used
1296polymorphically are hazardous, because use of them can lead to
1297<a href="https://en.wikipedia.org/wiki/Object_slicing">object slicing</a>.
1298Defaulted or carelessly-implemented copy operations can be incorrect, and the
1299resulting bugs can be confusing and difficult to diagnose.</p>
1300
1301<p>Copy constructors are invoked implicitly, which makes the
1302invocation easy to miss. This may cause confusion for programmers used to
1303languages where pass-by-reference is conventional or mandatory. It may also
1304encourage excessive copying, which can cause performance problems.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001305
Victor Costanf0314ea2019-09-01 20:42:44 -07001306<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001307
Victor Costanf0314ea2019-09-01 20:42:44 -07001308<p>Every class's public interface must make clear which copy and move
Victor Costan6dfd9d92018-02-05 18:30:35 -08001309operations the class supports. This should usually take the form of explicitly
1310declaring and/or deleting the appropriate operations in the <code>public</code>
1311section of the declaration.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001312
Victor Costan6dfd9d92018-02-05 18:30:35 -08001313<p>Specifically, a copyable class should explicitly declare the copy
1314operations, a move-only class should explicitly declare the move operations,
1315and a non-copyable/movable class should explicitly delete the copy operations.
1316Explicitly declaring or deleting all four copy/move operations is permitted,
1317but not required. If you provide a copy or move assignment operator, you
1318must also provide the corresponding constructor.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001319
Victor Costan6dfd9d92018-02-05 18:30:35 -08001320<pre>class Copyable {
Ted Osborne505ba682018-01-30 12:36:50 -05001321 public:
Victor Costanf0314ea2019-09-01 20:42:44 -07001322 Copyable(const Copyable&amp; other) = default;
1323 Copyable&amp; operator=(const Copyable&amp; other) = default;
Ted Osborne505ba682018-01-30 12:36:50 -05001324
Victor Costan6dfd9d92018-02-05 18:30:35 -08001325 // The implicit move operations are suppressed by the declarations above.
1326};
1327
1328class MoveOnly {
1329 public:
Victor Costanf0314ea2019-09-01 20:42:44 -07001330 MoveOnly(MoveOnly&amp;&amp; other);
1331 MoveOnly&amp; operator=(MoveOnly&amp;&amp; other);
Victor Costan6dfd9d92018-02-05 18:30:35 -08001332
1333 // The copy operations are implicitly deleted, but you can
1334 // spell that out explicitly if you want:
1335 MoveOnly(const MoveOnly&amp;) = delete;
1336 MoveOnly&amp; operator=(const MoveOnly&amp;) = delete;
1337};
1338
1339class NotCopyableOrMovable {
1340 public:
1341 // Not copyable or movable
1342 NotCopyableOrMovable(const NotCopyableOrMovable&amp;) = delete;
1343 NotCopyableOrMovable&amp; operator=(const NotCopyableOrMovable&amp;)
1344 = delete;
1345
1346 // The move operations are implicitly disabled, but you can
1347 // spell that out explicitly if you want:
1348 NotCopyableOrMovable(NotCopyableOrMovable&amp;&amp;) = delete;
1349 NotCopyableOrMovable&amp; operator=(NotCopyableOrMovable&amp;&amp;)
1350 = delete;
Ted Osborne505ba682018-01-30 12:36:50 -05001351};
1352</pre>
1353
Victor Costanf0314ea2019-09-01 20:42:44 -07001354<p>These declarations/deletions can be omitted only if they are obvious:
1355</p><ul>
1356<li>If the class has no <code>private</code> section, like a
1357 <a href="#Structs_vs._Classes">struct</a> or an interface-only base class,
1358 then the copyability/movability can be determined by the
1359 copyability/movability of any public data members.
1360</li><li>If a base class clearly isn't copyable or movable, derived classes
1361 naturally won't be either. An interface-only base class that leaves these
1362 operations implicit is not sufficient to make concrete subclasses clear.
1363</li><li>Note that if you explicitly declare or delete either the constructor or
1364 assignment operation for copy, the other copy operation is not obvious and
1365 must be declared or deleted. Likewise for move operations.
1366</li></ul>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001367
1368<p>A type should not be copyable/movable if the meaning of
1369copying/moving is unclear to a casual user, or if it incurs unexpected
1370costs. Move operations for copyable types are strictly a performance
1371optimization and are a potential source of bugs and complexity, so
1372avoid defining them unless they are significantly more efficient than
1373the corresponding copy operations. If your type provides copy operations, it is
1374recommended that you design your class so that the default implementation of
1375those operations is correct. Remember to review the correctness of any
1376defaulted operations as you would any other code.</p>
1377
1378<p>Due to the risk of slicing, prefer to avoid providing a public assignment
1379operator or copy/move constructor for a class that's
1380intended to be derived from (and prefer to avoid deriving from a class
Ted Osborne505ba682018-01-30 12:36:50 -05001381with such members). If your base class needs to be
1382copyable, provide a public virtual <code>Clone()</code>
1383method, and a protected copy constructor that derived classes
1384can use to implement it.</p>
1385
Ted Osborne505ba682018-01-30 12:36:50 -05001386
Ted Osborne505ba682018-01-30 12:36:50 -05001387
Ted Osborne505ba682018-01-30 12:36:50 -05001388<h3 id="Structs_vs._Classes">Structs vs. Classes</h3>
1389
Ted Osborne505ba682018-01-30 12:36:50 -05001390<p>Use a <code>struct</code> only for passive objects that
1391 carry data; everything else is a <code>class</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001392
1393<p>The <code>struct</code> and <code>class</code>
1394keywords behave almost identically in C++. We add our own
1395semantic meanings to each keyword, so you should use the
1396appropriate keyword for the data-type you're
1397defining.</p>
1398
Victor Costanf0314ea2019-09-01 20:42:44 -07001399<p><code>structs</code> should be used for passive objects that carry
1400data, and may have associated constants, but lack any functionality
1401other than access/setting the data members. All fields must be public,
1402and accessed directly rather than through getter/setter methods. The
1403struct must not have invariants that imply relationships between
1404different fields, since direct user access to those fields may break
1405those invariants. Methods should not provide behavior but should only
1406be used to set up the data members, e.g., constructor, destructor,
1407<code>Initialize()</code>, <code>Reset()</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001408
Victor Costanf0314ea2019-09-01 20:42:44 -07001409<p>If more functionality or invariants are required, a
Ted Osborne505ba682018-01-30 12:36:50 -05001410<code>class</code> is more appropriate. If in doubt, make
1411it a <code>class</code>.</p>
1412
1413<p>For consistency with STL, you can use
1414<code>struct</code> instead of <code>class</code> for
Victor Costanf0314ea2019-09-01 20:42:44 -07001415stateless types, such as traits,
1416<a href="#Template_metaprogramming">template metafunctions</a>,
1417and some functors.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001418
1419<p>Note that member variables in structs and classes have
1420<a href="#Variable_Names">different naming rules</a>.</p>
1421
Victor Costanf0314ea2019-09-01 20:42:44 -07001422<h3 id="Structs_vs._Tuples">Structs vs. Pairs and Tuples</h3>
1423
1424<p>Prefer to use a <code>struct</code> instead of a pair or a
1425tuple whenever the elements can have meaningful names.</p>
1426
1427<p>
1428 While using pairs and tuples can avoid the need to define a custom type,
1429 potentially saving work when <em>writing</em> code, a meaningful field
1430 name will almost always be much clearer when <em>reading</em> code than
1431 <code>.first</code>, <code>.second</code>, or <code>std::get&lt;X&gt;</code>.
1432 While C++14's introduction of <code>std::get&lt;Type&gt;</code> to access a
1433 tuple element by type rather than index (when the type is unique) can
1434 sometimes partially mitigate this, a field name is usually substantially
1435 clearer and more informative than a type.
1436</p>
1437
1438<p>
1439 Pairs and tuples may be appropriate in generic code where there are not
1440 specific meanings for the elements of the pair or tuple. Their use may
1441 also be required in order to interoperate with existing code or APIs.
1442</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001443
Victor Costanb89a7752018-07-31 10:17:48 -07001444<a id="Multiple_Inheritance"></a>
Ted Osborne505ba682018-01-30 12:36:50 -05001445<h3 id="Inheritance">Inheritance</h3>
1446
Ted Osborne505ba682018-01-30 12:36:50 -05001447<p>Composition is often more appropriate than inheritance.
1448When using inheritance, make it <code>public</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001449
Victor Costanf0314ea2019-09-01 20:42:44 -07001450<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001451<p> When a sub-class
1452inherits from a base class, it includes the definitions
Victor Costanb89a7752018-07-31 10:17:48 -07001453of all the data and operations that the base class
1454defines. "Interface inheritance" is inheritance from a
1455pure abstract base class (one with no state or defined
1456methods); all other inheritance is "implementation
1457inheritance".</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001458
Victor Costanf0314ea2019-09-01 20:42:44 -07001459<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001460<p>Implementation inheritance reduces code size by re-using
1461the base class code as it specializes an existing type.
1462Because inheritance is a compile-time declaration, you
1463and the compiler can understand the operation and detect
1464errors. Interface inheritance can be used to
1465programmatically enforce that a class expose a particular
1466API. Again, the compiler can detect errors, in this case,
1467when a class does not define a necessary method of the
1468API.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001469
Victor Costanf0314ea2019-09-01 20:42:44 -07001470<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001471<p>For implementation inheritance, because the code
1472implementing a sub-class is spread between the base and
1473the sub-class, it can be more difficult to understand an
1474implementation. The sub-class cannot override functions
1475that are not virtual, so the sub-class cannot change
Victor Costan6dfd9d92018-02-05 18:30:35 -08001476implementation.</p>
Victor Costanb89a7752018-07-31 10:17:48 -07001477
1478<p>Multiple inheritance is especially problematic, because
1479it often imposes a higher performance overhead (in fact,
1480the performance drop from single inheritance to multiple
1481inheritance can often be greater than the performance
1482drop from ordinary to virtual dispatch), and because
1483it risks leading to "diamond" inheritance patterns,
1484which are prone to ambiguity, confusion, and outright bugs.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001485
Victor Costanf0314ea2019-09-01 20:42:44 -07001486<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001487
1488<p>All inheritance should be <code>public</code>. If you
1489want to do private inheritance, you should be including
1490an instance of the base class as a member instead.</p>
1491
1492<p>Do not overuse implementation inheritance. Composition
1493is often more appropriate. Try to restrict use of
1494inheritance to the "is-a" case: <code>Bar</code>
1495subclasses <code>Foo</code> if it can reasonably be said
1496that <code>Bar</code> "is a kind of"
1497<code>Foo</code>.</p>
1498
Ted Osborne505ba682018-01-30 12:36:50 -05001499<p>Limit the use of <code>protected</code> to those
1500member functions that might need to be accessed from
1501subclasses. Note that <a href="#Access_Control">data
1502members should be private</a>.</p>
1503
Victor Costan6dfd9d92018-02-05 18:30:35 -08001504<p>Explicitly annotate overrides of virtual functions or virtual
1505destructors with exactly one of an <code>override</code> or (less
1506frequently) <code>final</code> specifier. Do not
1507use <code>virtual</code> when declaring an override.
Ted Osborne505ba682018-01-30 12:36:50 -05001508Rationale: A function or destructor marked
1509<code>override</code> or <code>final</code> that is
1510not an override of a base class virtual function will
1511not compile, and this helps catch common errors. The
1512specifiers serve as documentation; if no specifier is
1513present, the reader has to check all ancestors of the
1514class in question to determine if the function or
1515destructor is virtual or not.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001516
Victor Costanf0314ea2019-09-01 20:42:44 -07001517<p>Multiple inheritance is permitted, but multiple <em>implementation</em>
Victor Costanb89a7752018-07-31 10:17:48 -07001518inheritance is strongly discouraged.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001519
1520<h3 id="Operator_Overloading">Operator Overloading</h3>
1521
Victor Costanf0314ea2019-09-01 20:42:44 -07001522<p>Overload operators judiciously. Do not use user-defined literals.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001523
Victor Costanf0314ea2019-09-01 20:42:44 -07001524<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001525<p>C++ permits user code to
1526<a href="http://en.cppreference.com/w/cpp/language/operators">declare
1527overloaded versions of the built-in operators</a> using the
1528<code>operator</code> keyword, so long as one of the parameters
1529is a user-defined type. The <code>operator</code> keyword also
1530permits user code to define new kinds of literals using
1531<code>operator""</code>, and to define type-conversion functions
1532such as <code>operator bool()</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001533
Victor Costanf0314ea2019-09-01 20:42:44 -07001534<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001535<p>Operator overloading can make code more concise and
1536intuitive by enabling user-defined types to behave the same
1537as built-in types. Overloaded operators are the idiomatic names
1538for certain operations (e.g. <code>==</code>, <code>&lt;</code>,
1539<code>=</code>, and <code>&lt;&lt;</code>), and adhering to
1540those conventions can make user-defined types more readable
1541and enable them to interoperate with libraries that expect
1542those names.</p>
1543
1544<p>User-defined literals are a very concise notation for
1545creating objects of user-defined types.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001546
Victor Costanf0314ea2019-09-01 20:42:44 -07001547<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001548<ul>
1549 <li>Providing a correct, consistent, and unsurprising
1550 set of operator overloads requires some care, and failure
1551 to do so can lead to confusion and bugs.</li>
1552
1553 <li>Overuse of operators can lead to obfuscated code,
1554 particularly if the overloaded operator's semantics
1555 don't follow convention.</li>
1556
1557 <li>The hazards of function overloading apply just as
1558 much to operator overloading, if not more so.</li>
1559
1560 <li>Operator overloads can fool our intuition into
1561 thinking that expensive operations are cheap, built-in
1562 operations.</li>
1563
1564 <li>Finding the call sites for overloaded operators may
1565 require a search tool that's aware of C++ syntax, rather
1566 than e.g. grep.</li>
1567
1568 <li>If you get the argument type of an overloaded operator
1569 wrong, you may get a different overload rather than a
1570 compiler error. For example, <code>foo &lt; bar</code>
1571 may do one thing, while <code>&amp;foo &lt; &amp;bar</code>
1572 does something totally different.</li>
1573
1574 <li>Certain operator overloads are inherently hazardous.
1575 Overloading unary <code>&amp;</code> can cause the same
1576 code to have different meanings depending on whether
1577 the overload declaration is visible. Overloads of
1578 <code>&amp;&amp;</code>, <code>||</code>, and <code>,</code>
1579 (comma) cannot match the evaluation-order semantics of the
1580 built-in operators.</li>
1581
1582 <li>Operators are often defined outside the class,
1583 so there's a risk of different files introducing
1584 different definitions of the same operator. If both
1585 definitions are linked into the same binary, this results
1586 in undefined behavior, which can manifest as subtle
1587 run-time bugs.</li>
1588
Victor Costanf0314ea2019-09-01 20:42:44 -07001589 <li>User-defined literals (UDLs) allow the creation of new
Ted Osborne505ba682018-01-30 12:36:50 -05001590 syntactic forms that are unfamiliar even to experienced C++
Victor Costanf0314ea2019-09-01 20:42:44 -07001591 programmers, such as <code>"Hello World"sv</code> as a
1592 shorthand for <code>std::string_view("Hello World")</code>.
1593 Existing notations are clearer, though less terse.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05001594
Victor Costanf0314ea2019-09-01 20:42:44 -07001595 <li>Because they can't be namespace-qualified, uses of UDLs also require
1596 use of either using-directives (which <a href="#Namespaces">we ban</a>) or
1597 using-declarations (which <a href="#Aliases">we ban in header files</a> except
1598 when the imported names are part of the interface exposed by the header
1599 file in question). Given that header files would have to avoid UDL
1600 suffixes, we prefer to avoid having conventions for literals differ
1601 between header files and source files.
1602 </li>
1603</ul>
1604
1605<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001606<p>Define overloaded operators only if their meaning is
1607obvious, unsurprising, and consistent with the corresponding
1608built-in operators. For example, use <code>|</code> as a
1609bitwise- or logical-or, not as a shell-style pipe.</p>
1610
1611<p>Define operators only on your own types. More precisely,
1612define them in the same headers, .cc files, and namespaces
1613as the types they operate on. That way, the operators are available
1614wherever the type is, minimizing the risk of multiple
1615definitions. If possible, avoid defining operators as templates,
1616because they must satisfy this rule for any possible template
1617arguments. If you define an operator, also define
1618any related operators that make sense, and make sure they
1619are defined consistently. For example, if you overload
1620<code>&lt;</code>, overload all the comparison operators,
1621and make sure <code>&lt;</code> and <code>&gt;</code> never
1622return true for the same arguments.</p>
1623
1624<p>Prefer to define non-modifying binary operators as
1625non-member functions. If a binary operator is defined as a
1626class member, implicit conversions will apply to the
1627right-hand argument, but not the left-hand one. It will
1628confuse your users if <code>a &lt; b</code> compiles but
1629<code>b &lt; a</code> doesn't.</p>
1630
1631<p>Don't go out of your way to avoid defining operator
1632overloads. For example, prefer to define <code>==</code>,
1633<code>=</code>, and <code>&lt;&lt;</code>, rather than
1634<code>Equals()</code>, <code>CopyFrom()</code>, and
1635<code>PrintTo()</code>. Conversely, don't define
1636operator overloads just because other libraries expect
1637them. For example, if your type doesn't have a natural
1638ordering, but you want to store it in a <code>std::set</code>,
1639use a custom comparator rather than overloading
1640<code>&lt;</code>.</p>
1641
1642<p>Do not overload <code>&amp;&amp;</code>, <code>||</code>,
1643<code>,</code> (comma), or unary <code>&amp;</code>. Do not overload
1644<code>operator""</code>, i.e. do not introduce user-defined
Victor Costanf0314ea2019-09-01 20:42:44 -07001645literals. Do not use any such literals provided by others
1646(including the standard library).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001647
1648<p>Type conversion operators are covered in the section on
1649<a href="#Implicit_Conversions">implicit conversions</a>.
1650The <code>=</code> operator is covered in the section on
1651<a href="#Copy_Constructors">copy constructors</a>. Overloading
1652<code>&lt;&lt;</code> for use with streams is covered in the
1653section on <a href="#Streams">streams</a>. See also the rules on
1654<a href="#Function_Overloading">function overloading</a>, which
1655apply to operator overloading as well.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001656
1657<h3 id="Access_Control">Access Control</h3>
1658
Victor Costanb89a7752018-07-31 10:17:48 -07001659<p>Make classes' data members <code>private</code>, unless they are
Victor Costanf0314ea2019-09-01 20:42:44 -07001660<a href="#Constant_Names">constants</a>. This simplifies reasoning about invariants, at the cost
1661of some easy boilerplate in the form of accessors (usually <code>const</code>) if necessary.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001662
1663<p>For technical
Victor Costanb89a7752018-07-31 10:17:48 -07001664reasons, we allow data members of a test fixture class in a .cc file to
Ted Osborne505ba682018-01-30 12:36:50 -05001665be <code>protected</code> when using
1666
1667
1668<a href="https://github.com/google/googletest">Google
1669Test</a>).</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001670
Ted Osborne505ba682018-01-30 12:36:50 -05001671<h3 id="Declaration_Order">Declaration Order</h3>
1672
Ted Osborne505ba682018-01-30 12:36:50 -05001673<p>Group similar declarations together, placing public parts
1674earlier.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001675
1676<p>A class definition should usually start with a
1677<code>public:</code> section, followed by
1678<code>protected:</code>, then <code>private:</code>. Omit
1679sections that would be empty.</p>
1680
1681<p>Within each section, generally prefer grouping similar
1682kinds of declarations together, and generally prefer the
1683following order: types (including <code>typedef</code>,
1684<code>using</code>, and nested structs and classes),
1685constants, factory functions, constructors, assignment
1686operators, destructor, all other methods, data members.</p>
1687
1688<p>Do not put large method definitions inline in the
1689class definition. Usually, only trivial or
1690performance-critical, and very short, methods may be
1691defined inline. See <a href="#Inline_Functions">Inline
1692Functions</a> for more details.</p>
1693
Ted Osborne505ba682018-01-30 12:36:50 -05001694<h2 id="Functions">Functions</h2>
1695
Victor Costan6dfd9d92018-02-05 18:30:35 -08001696<a id="Function_Parameter_Ordering"></a>
1697<h3 id="Output_Parameters">Output Parameters</h3>
Ted Osborne505ba682018-01-30 12:36:50 -05001698
Victor Costan6dfd9d92018-02-05 18:30:35 -08001699<p>The output of a C++ function is naturally provided via
1700a return value and sometimes via output parameters.</p>
1701
Victor Costanf0314ea2019-09-01 20:42:44 -07001702<p>Prefer using return values over output parameters: they
1703improve readability, and often provide the same or better
1704performance. If output-only parameters are used,
1705they should appear after input parameters.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001706
1707<p>Parameters are either input to the function, output from the
1708function, or both. Input parameters are usually values or
1709<code>const</code> references, while output and input/output
1710parameters will be pointers to non-<code>const</code>.</p>
1711
1712<p>When ordering function parameters, put all input-only
1713parameters before any output parameters. In particular,
1714do not add new parameters to the end of the function just
1715because they are new; place new input-only parameters before
1716the output parameters.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001717
1718<p>This is not a hard-and-fast rule. Parameters that are
1719both input and output (often classes/structs) muddy the
1720waters, and, as always, consistency with related
1721functions may require you to bend the rule.</p>
1722
Ted Osborne505ba682018-01-30 12:36:50 -05001723<h3 id="Write_Short_Functions">Write Short Functions</h3>
1724
Ted Osborne505ba682018-01-30 12:36:50 -05001725<p>Prefer small and focused functions.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001726
Ted Osborne505ba682018-01-30 12:36:50 -05001727<p>We recognize that long functions are sometimes
1728appropriate, so no hard limit is placed on functions
1729length. If a function exceeds about 40 lines, think about
1730whether it can be broken up without harming the structure
1731of the program.</p>
1732
1733<p>Even if your long function works perfectly now,
1734someone modifying it in a few months may add new
1735behavior. This could result in bugs that are hard to
1736find. Keeping your functions short and simple makes it
Victor Costanf0314ea2019-09-01 20:42:44 -07001737easier for other people to read and modify your code.
1738Small functions are also easier to test.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001739
1740<p>You could find long and complicated functions when
Victor Costanf0314ea2019-09-01 20:42:44 -07001741working with
Ted Osborne505ba682018-01-30 12:36:50 -05001742some code. Do not be
1743intimidated by modifying existing code: if working with
1744such a function proves to be difficult, you find that
1745errors are hard to debug, or you want to use a piece of
1746it in several different contexts, consider breaking up
1747the function into smaller and more manageable pieces.</p>
1748
Ted Osborne505ba682018-01-30 12:36:50 -05001749<h3 id="Reference_Arguments">Reference Arguments</h3>
1750
Victor Costanb89a7752018-07-31 10:17:48 -07001751<p>All parameters passed by lvalue reference must be labeled
Ted Osborne505ba682018-01-30 12:36:50 -05001752<code>const</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001753
Victor Costanf0314ea2019-09-01 20:42:44 -07001754<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001755<p>In C, if a
1756function needs to modify a variable, the parameter must
1757use a pointer, eg <code>int foo(int *pval)</code>. In
1758C++, the function can alternatively declare a reference
1759parameter: <code>int foo(int &amp;val)</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001760
Victor Costanf0314ea2019-09-01 20:42:44 -07001761<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001762<p>Defining a parameter as reference avoids ugly code like
1763<code>(*pval)++</code>. Necessary for some applications
1764like copy constructors. Makes it clear, unlike with
1765pointers, that a null pointer is not a possible
1766value.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001767
Victor Costanf0314ea2019-09-01 20:42:44 -07001768<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001769<p>References can be confusing, as they have value syntax
1770but pointer semantics.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001771
Victor Costanf0314ea2019-09-01 20:42:44 -07001772<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001773<p>Within function parameter lists all references must be
1774<code>const</code>:</p>
1775
Victor Costanf0314ea2019-09-01 20:42:44 -07001776<pre>void Foo(const std::string &amp;in, std::string *out);
Ted Osborne505ba682018-01-30 12:36:50 -05001777</pre>
1778
1779<p>In fact it is a very strong convention in Google code
1780that input arguments are values or <code>const</code>
1781references while output arguments are pointers. Input
1782parameters may be <code>const</code> pointers, but we
1783never allow non-<code>const</code> reference parameters
1784except when required by convention, e.g.,
1785<code>swap()</code>.</p>
1786
1787<p>However, there are some instances where using
1788<code>const T*</code> is preferable to <code>const
1789T&amp;</code> for input parameters. For example:</p>
1790
1791<ul>
1792 <li>You want to pass in a null pointer.</li>
1793
1794 <li>The function saves a pointer or reference to the
1795 input.</li>
1796</ul>
1797
1798<p> Remember that most of the time input
1799parameters are going to be specified as <code>const
1800T&amp;</code>. Using <code>const T*</code> instead
1801communicates to the reader that the input is somehow
1802treated differently. So if you choose <code>const
1803T*</code> rather than <code>const T&amp;</code>, do so
1804for a concrete reason; otherwise it will likely confuse
1805readers by making them look for an explanation that
1806doesn't exist.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001807
1808<h3 id="Function_Overloading">Function Overloading</h3>
1809
Ted Osborne505ba682018-01-30 12:36:50 -05001810<p>Use overloaded functions (including constructors) only if a
1811reader looking at a call site can get a good idea of what
1812is happening without having to first figure out exactly
1813which overload is being called.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001814
Victor Costanf0314ea2019-09-01 20:42:44 -07001815<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001816<p>You may write a function that takes a <code>const
Victor Costanf0314ea2019-09-01 20:42:44 -07001817std::string&amp;</code> and overload it with another that
Victor Costan6dfd9d92018-02-05 18:30:35 -08001818takes <code>const char*</code>. However, in this case consider
1819std::string_view
1820 instead.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001821
1822<pre>class MyClass {
1823 public:
Victor Costanf0314ea2019-09-01 20:42:44 -07001824 void Analyze(const std::string &amp;text);
Ted Osborne505ba682018-01-30 12:36:50 -05001825 void Analyze(const char *text, size_t textlen);
1826};
1827</pre>
Ted Osborne505ba682018-01-30 12:36:50 -05001828
Victor Costanf0314ea2019-09-01 20:42:44 -07001829<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001830<p>Overloading can make code more intuitive by allowing an
1831identically-named function to take different arguments.
1832It may be necessary for templatized code, and it can be
1833convenient for Visitors.</p>
Victor Costanb89a7752018-07-31 10:17:48 -07001834<p>Overloading based on const or ref qualification may make utility
1835 code more usable, more efficient, or both.
Victor Costanb89a7752018-07-31 10:17:48 -07001836 (See <a href="http://abseil.io/tips/148">TotW 148</a> for more.)
1837</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001838
Victor Costanf0314ea2019-09-01 20:42:44 -07001839<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001840<p>If a function is overloaded by the argument types alone,
1841a reader may have to understand C++'s complex matching
1842rules in order to tell what's going on. Also many people
1843are confused by the semantics of inheritance if a derived
1844class overrides only some of the variants of a
1845function.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001846
Victor Costanf0314ea2019-09-01 20:42:44 -07001847<p class="decision"></p>
Victor Costanb89a7752018-07-31 10:17:48 -07001848<p>You may overload a function when there are no semantic differences
1849between variants. These overloads may vary in types, qualifiers, or
1850argument count. However, a reader of such a call must not need to know
1851which member of the overload set is chosen, only that <b>something</b>
1852from the set is being called. If you can document all entries in the
1853overload set with a single comment in the header, that is a good sign
1854that it is a well-designed overload set.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001855
1856<h3 id="Default_Arguments">Default Arguments</h3>
1857
Ted Osborne505ba682018-01-30 12:36:50 -05001858<p>Default arguments are allowed on non-virtual functions
1859when the default is guaranteed to always have the same
1860value. Follow the same restrictions as for <a href="#Function_Overloading">function overloading</a>, and
1861prefer overloaded functions if the readability gained with
1862default arguments doesn't outweigh the downsides below.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001863
Victor Costanf0314ea2019-09-01 20:42:44 -07001864<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001865<p>Often you have a function that uses default values, but
1866occasionally you want to override the defaults. Default
1867parameters allow an easy way to do this without having to
1868define many functions for the rare exceptions. Compared
1869to overloading the function, default arguments have a
1870cleaner syntax, with less boilerplate and a clearer
1871distinction between 'required' and 'optional'
1872arguments.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001873
Victor Costanf0314ea2019-09-01 20:42:44 -07001874<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001875<p>Defaulted arguments are another way to achieve the
1876semantics of overloaded functions, so all the <a href="#Function_Overloading">reasons not to overload
1877functions</a> apply.</p>
1878
1879<p>The defaults for arguments in a virtual function call are
1880determined by the static type of the target object, and
1881there's no guarantee that all overrides of a given function
1882declare the same defaults.</p>
1883
1884<p>Default parameters are re-evaluated at each call site,
1885which can bloat the generated code. Readers may also expect
1886the default's value to be fixed at the declaration instead
1887of varying at each call.</p>
1888
1889<p>Function pointers are confusing in the presence of
1890default arguments, since the function signature often
1891doesn't match the call signature. Adding
1892function overloads avoids these problems.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001893
Victor Costanf0314ea2019-09-01 20:42:44 -07001894<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001895<p>Default arguments are banned on virtual functions, where
1896they don't work properly, and in cases where the specified
1897default might not evaluate to the same value depending on
1898when it was evaluated. (For example, don't write <code>void
1899f(int n = counter++);</code>.)</p>
1900
1901<p>In some other cases, default arguments can improve the
1902readability of their function declarations enough to
1903overcome the downsides above, so they are allowed. When in
1904doubt, use overloads.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001905
1906<h3 id="trailing_return">Trailing Return Type Syntax</h3>
Victor Costanf0314ea2019-09-01 20:42:44 -07001907
Ted Osborne505ba682018-01-30 12:36:50 -05001908<p>Use trailing return types only where using the ordinary syntax (leading
1909 return types) is impractical or much less readable.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001910
Victor Costanf0314ea2019-09-01 20:42:44 -07001911<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001912<p>C++ allows two different forms of function declarations. In the older
1913 form, the return type appears before the function name. For example:</p>
1914<pre>int foo(int x);
1915</pre>
Victor Costan967e1572019-09-05 05:09:38 -07001916<p>The newer form, introduced in C++11, uses the <code>auto</code>
Ted Osborne505ba682018-01-30 12:36:50 -05001917 keyword before the function name and a trailing return type after
1918 the argument list. For example, the declaration above could
1919 equivalently be written:</p>
1920<pre>auto foo(int x) -&gt; int;
1921</pre>
1922<p>The trailing return type is in the function's scope. This doesn't
1923 make a difference for a simple case like <code>int</code> but it matters
1924 for more complicated cases, like types declared in class scope or
1925 types written in terms of the function parameters.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001926
Victor Costanf0314ea2019-09-01 20:42:44 -07001927<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001928<p>Trailing return types are the only way to explicitly specify the
1929 return type of a <a href="#Lambda_expressions">lambda expression</a>.
1930 In some cases the compiler is able to deduce a lambda's return type,
1931 but not in all cases. Even when the compiler can deduce it automatically,
1932 sometimes specifying it explicitly would be clearer for readers.
1933</p>
1934<p>Sometimes it's easier and more readable to specify a return type
1935 after the function's parameter list has already appeared. This is
1936 particularly true when the return type depends on template parameters.
1937 For example:</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08001938 <pre> template &lt;typename T, typename U&gt;
1939 auto add(T t, U u) -&gt; decltype(t + u);
1940 </pre>
Ted Osborne505ba682018-01-30 12:36:50 -05001941 versus
Victor Costan6dfd9d92018-02-05 18:30:35 -08001942 <pre> template &lt;typename T, typename U&gt;
1943 decltype(declval&lt;T&amp;&gt;() + declval&lt;U&amp;&gt;()) add(T t, U u);
1944 </pre>
Ted Osborne505ba682018-01-30 12:36:50 -05001945
Victor Costanf0314ea2019-09-01 20:42:44 -07001946<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001947<p>Trailing return type syntax is relatively new and it has no
Victor Costanb89a7752018-07-31 10:17:48 -07001948 analogue in C++-like languages such as C and Java, so some readers may
Ted Osborne505ba682018-01-30 12:36:50 -05001949 find it unfamiliar.</p>
1950<p>Existing code bases have an enormous number of function
1951 declarations that aren't going to get changed to use the new syntax,
1952 so the realistic choices are using the old syntax only or using a mixture
1953 of the two. Using a single version is better for uniformity of style.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001954
Victor Costanf0314ea2019-09-01 20:42:44 -07001955<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001956<p>In most cases, continue to use the older style of function
1957 declaration where the return type goes before the function name.
1958 Use the new trailing-return-type form only in cases where it's
1959 required (such as lambdas) or where, by putting the type after the
1960 function's parameter list, it allows you to write the type in a much
1961 more readable way. The latter case should be rare; it's mostly an
1962 issue in fairly complicated template code, which is
1963 <a href="#Template_metaprogramming">discouraged in most cases</a>.</p>
1964
Ted Osborne505ba682018-01-30 12:36:50 -05001965
1966<h2 id="Google-Specific_Magic">Google-Specific Magic</h2>
1967
1968
1969
Victor Costanf0314ea2019-09-01 20:42:44 -07001970<div>
Ted Osborne505ba682018-01-30 12:36:50 -05001971<p>There are various tricks and utilities that
1972we use to make C++ code more robust, and various ways we use
1973C++ that may differ from what you see elsewhere.</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07001974</div>
Ted Osborne505ba682018-01-30 12:36:50 -05001975
Victor Costanf0314ea2019-09-01 20:42:44 -07001976
Ted Osborne505ba682018-01-30 12:36:50 -05001977
1978<h3 id="Ownership_and_Smart_Pointers">Ownership and Smart Pointers</h3>
1979
Ted Osborne505ba682018-01-30 12:36:50 -05001980<p>Prefer to have single, fixed owners for dynamically
1981allocated objects. Prefer to transfer ownership with smart
1982pointers.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05001983
Victor Costanf0314ea2019-09-01 20:42:44 -07001984<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05001985<p>"Ownership" is a bookkeeping technique for managing
1986dynamically allocated memory (and other resources). The
1987owner of a dynamically allocated object is an object or
1988function that is responsible for ensuring that it is
1989deleted when no longer needed. Ownership can sometimes be
1990shared, in which case the last owner is typically
1991responsible for deleting it. Even when ownership is not
1992shared, it can be transferred from one piece of code to
1993another.</p>
1994
1995<p>"Smart" pointers are classes that act like pointers,
1996e.g. by overloading the <code>*</code> and
1997<code>-&gt;</code> operators. Some smart pointer types
1998can be used to automate ownership bookkeeping, to ensure
1999these responsibilities are met.
2000<a href="http://en.cppreference.com/w/cpp/memory/unique_ptr">
2001<code>std::unique_ptr</code></a> is a smart pointer type
2002introduced in C++11, which expresses exclusive ownership
2003of a dynamically allocated object; the object is deleted
2004when the <code>std::unique_ptr</code> goes out of scope.
2005It cannot be copied, but can be <em>moved</em> to
2006represent ownership transfer.
2007<a href="http://en.cppreference.com/w/cpp/memory/shared_ptr">
2008<code>std::shared_ptr</code></a> is a smart pointer type
2009that expresses shared ownership of
2010a dynamically allocated object. <code>std::shared_ptr</code>s
2011can be copied; ownership of the object is shared among
2012all copies, and the object is deleted when the last
2013<code>std::shared_ptr</code> is destroyed. </p>
Ted Osborne505ba682018-01-30 12:36:50 -05002014
Victor Costanf0314ea2019-09-01 20:42:44 -07002015<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002016<ul>
2017 <li>It's virtually impossible to manage dynamically
2018 allocated memory without some sort of ownership
2019 logic.</li>
2020
2021 <li>Transferring ownership of an object can be cheaper
2022 than copying it (if copying it is even possible).</li>
2023
2024 <li>Transferring ownership can be simpler than
2025 'borrowing' a pointer or reference, because it reduces
2026 the need to coordinate the lifetime of the object
2027 between the two users.</li>
2028
2029 <li>Smart pointers can improve readability by making
2030 ownership logic explicit, self-documenting, and
2031 unambiguous.</li>
2032
2033 <li>Smart pointers can eliminate manual ownership
2034 bookkeeping, simplifying the code and ruling out large
2035 classes of errors.</li>
2036
2037 <li>For const objects, shared ownership can be a simple
2038 and efficient alternative to deep copying.</li>
2039</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05002040
Victor Costanf0314ea2019-09-01 20:42:44 -07002041<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002042<ul>
2043 <li>Ownership must be represented and transferred via
2044 pointers (whether smart or plain). Pointer semantics
2045 are more complicated than value semantics, especially
2046 in APIs: you have to worry not just about ownership,
2047 but also aliasing, lifetime, and mutability, among
2048 other issues.</li>
2049
2050 <li>The performance costs of value semantics are often
2051 overestimated, so the performance benefits of ownership
2052 transfer might not justify the readability and
2053 complexity costs.</li>
2054
2055 <li>APIs that transfer ownership force their clients
2056 into a single memory management model.</li>
2057
2058 <li>Code using smart pointers is less explicit about
2059 where the resource releases take place.</li>
2060
2061 <li><code>std::unique_ptr</code> expresses ownership
2062 transfer using C++11's move semantics, which are
2063 relatively new and may confuse some programmers.</li>
2064
2065 <li>Shared ownership can be a tempting alternative to
2066 careful ownership design, obfuscating the design of a
2067 system.</li>
2068
2069 <li>Shared ownership requires explicit bookkeeping at
2070 run-time, which can be costly.</li>
2071
2072 <li>In some cases (e.g. cyclic references), objects
2073 with shared ownership may never be deleted.</li>
2074
2075 <li>Smart pointers are not perfect substitutes for
2076 plain pointers.</li>
2077</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05002078
Victor Costanf0314ea2019-09-01 20:42:44 -07002079<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002080<p>If dynamic allocation is necessary, prefer to keep
2081ownership with the code that allocated it. If other code
2082needs access to the object, consider passing it a copy,
2083or passing a pointer or reference without transferring
2084ownership. Prefer to use <code>std::unique_ptr</code> to
2085make ownership transfer explicit. For example:</p>
2086
2087<pre>std::unique_ptr&lt;Foo&gt; FooFactory();
2088void FooConsumer(std::unique_ptr&lt;Foo&gt; ptr);
2089</pre>
2090
2091
2092
2093<p>Do not design your code to use shared ownership
2094without a very good reason. One such reason is to avoid
2095expensive copy operations, but you should only do this if
2096the performance benefits are significant, and the
2097underlying object is immutable (i.e.
2098<code>std::shared_ptr&lt;const Foo&gt;</code>). If you
2099do use shared ownership, prefer to use
2100<code>std::shared_ptr</code>.</p>
2101
2102<p>Never use <code>std::auto_ptr</code>. Instead, use
2103<code>std::unique_ptr</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002104
2105<h3 id="cpplint">cpplint</h3>
2106
Victor Costan6dfd9d92018-02-05 18:30:35 -08002107<p>Use <code>cpplint.py</code> to detect style errors.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002108
2109<p><code>cpplint.py</code>
2110is a tool that reads a source file and identifies many
2111style errors. It is not perfect, and has both false
2112positives and false negatives, but it is still a valuable
2113tool. False positives can be ignored by putting <code>//
2114NOLINT</code> at the end of the line or
2115<code>// NOLINTNEXTLINE</code> in the previous line.</p>
2116
2117
2118
Victor Costanf0314ea2019-09-01 20:42:44 -07002119<div>
Ted Osborne505ba682018-01-30 12:36:50 -05002120<p>Some projects have instructions on
2121how to run <code>cpplint.py</code> from their project
2122tools. If the project you are contributing to does not,
2123you can download
2124<a href="https://raw.githubusercontent.com/google/styleguide/gh-pages/cpplint/cpplint.py">
2125<code>cpplint.py</code></a> separately.</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07002126</div>
Ted Osborne505ba682018-01-30 12:36:50 -05002127
Ted Osborne505ba682018-01-30 12:36:50 -05002128
Ted Osborne505ba682018-01-30 12:36:50 -05002129
2130<h2 id="Other_C++_Features">Other C++ Features</h2>
2131
2132<h3 id="Rvalue_references">Rvalue References</h3>
2133
Victor Costanb89a7752018-07-31 10:17:48 -07002134<p>Use rvalue references to:</p>
2135<ul>
2136 <li>Define move constructors and move assignment operators.</li>
2137
2138 <li>Define <a href="#Function_Overloading">overload sets</a> with
2139 const&amp; and &amp;&amp; variants if you have evidence that this
2140 provides meaningfully better performance than passing by value,
2141 or if you're writing low-overhead generic code that needs to support
2142 arbitrary types. Beware combinatorial overload sets, that is, seldom
2143 overload more than one parameter.</li>
2144
2145 <li>Support 'perfect forwarding' in generic code.</li>
2146</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05002147
Victor Costanf0314ea2019-09-01 20:42:44 -07002148<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002149<p> Rvalue references
2150are a type of reference that can only bind to temporary
2151objects. The syntax is similar to traditional reference
Victor Costanf0314ea2019-09-01 20:42:44 -07002152syntax. For example, <code>void f(std::string&amp;&amp;
Ted Osborne505ba682018-01-30 12:36:50 -05002153s);</code> declares a function whose argument is an
Victor Costanf0314ea2019-09-01 20:42:44 -07002154rvalue reference to a std::string.</p>
Victor Costanb89a7752018-07-31 10:17:48 -07002155
2156<p id="Forwarding_references"> When the token '&amp;&amp;' is applied to
2157an unqualified template argument in a function
2158parameter, special template argument deduction
2159rules apply. Such a reference is called forwarding reference.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002160
Victor Costanf0314ea2019-09-01 20:42:44 -07002161<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002162<ul>
2163 <li>Defining a move constructor (a constructor taking
2164 an rvalue reference to the class type) makes it
2165 possible to move a value instead of copying it. If
Victor Costanf0314ea2019-09-01 20:42:44 -07002166 <code>v1</code> is a <code>std::vector&lt;std::string&gt;</code>,
Ted Osborne505ba682018-01-30 12:36:50 -05002167 for example, then <code>auto v2(std::move(v1))</code>
2168 will probably just result in some simple pointer
2169 manipulation instead of copying a large amount of data.
Victor Costanb89a7752018-07-31 10:17:48 -07002170 In many cases this can result in a major performance
Ted Osborne505ba682018-01-30 12:36:50 -05002171 improvement.</li>
2172
Ted Osborne505ba682018-01-30 12:36:50 -05002173 <li>Rvalue references make it possible to implement
2174 types that are movable but not copyable, which can be
2175 useful for types that have no sensible definition of
2176 copying but where you might still want to pass them as
2177 function arguments, put them in containers, etc.</li>
2178
2179 <li><code>std::move</code> is necessary to make
2180 effective use of some standard-library types, such as
2181 <code>std::unique_ptr</code>.</li>
Victor Costanb89a7752018-07-31 10:17:48 -07002182
2183 <li><a href="#Forwarding_references">Forwarding references</a> which
2184 use the rvalue reference token, make it possible to write a
2185 generic function wrapper that forwards its arguments to
2186 another function, and works whether or not its
2187 arguments are temporary objects and/or const.
2188 This is called 'perfect forwarding'.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05002189</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05002190
Victor Costanf0314ea2019-09-01 20:42:44 -07002191<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002192<ul>
Victor Costanf0314ea2019-09-01 20:42:44 -07002193 <li>Rvalue references are not yet widely understood. Rules like reference
2194 collapsing and the special deduction rule for forwarding references
2195 are somewhat obscure.</li>
Victor Costanb89a7752018-07-31 10:17:48 -07002196
2197 <li>Rvalue references are often misused. Using rvalue
2198 references is counter-intuitive in signatures where the argument is expected
2199 to have a valid specified state after the function call, or where no move
2200 operation is performed.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05002201</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05002202
Victor Costanf0314ea2019-09-01 20:42:44 -07002203<p class="decision"></p>
2204<p>You may use rvalue references to define move constructors and move
2205assignment operators (as described in
2206<a href="#Copyable_Movable_Types">Copyable and Movable Types</a>). See the
2207<a href="primer#copying_moving">C++ Primer</a> for more information about
2208move semantics and <code>std::move</code>.</p>
Victor Costanb89a7752018-07-31 10:17:48 -07002209
Victor Costanf0314ea2019-09-01 20:42:44 -07002210<p>You may use rvalue references to define pairs of overloads, one taking
2211<code>Foo&amp;&amp;</code> and the other taking <code>const Foo&amp;</code>.
2212Usually the preferred solution is just to pass by value, but an overloaded pair
2213of functions sometimes yields better performance and is sometimes necessary in
2214generic code that needs to support a wide variety of types. As always: if
2215you're writing more complicated code for the sake of performance, make sure you
2216have evidence that it actually helps.</p>
Victor Costanb89a7752018-07-31 10:17:48 -07002217
Victor Costanf0314ea2019-09-01 20:42:44 -07002218<p>You may use forwarding references in conjunction with <code>
2219<a href="http://en.cppreference.com/w/cpp/utility/forward">std::forward</a></code>,
2220to support perfect forwarding.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002221
2222<h3 id="Friends">Friends</h3>
2223
Ted Osborne505ba682018-01-30 12:36:50 -05002224<p>We allow use of <code>friend</code> classes and functions,
2225within reason.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002226
2227<p>Friends should usually be defined in the same file so
2228that the reader does not have to look in another file to
2229find uses of the private members of a class. A common use
2230of <code>friend</code> is to have a
2231<code>FooBuilder</code> class be a friend of
2232<code>Foo</code> so that it can construct the inner state
2233of <code>Foo</code> correctly, without exposing this
2234state to the world. In some cases it may be useful to
2235make a unittest class a friend of the class it tests.</p>
2236
2237<p>Friends extend, but do not break, the encapsulation
2238boundary of a class. In some cases this is better than
2239making a member public when you want to give only one
2240other class access to it. However, most classes should
2241interact with other classes solely through their public
2242members.</p>
2243
Ted Osborne505ba682018-01-30 12:36:50 -05002244<h3 id="Exceptions">Exceptions</h3>
2245
Ted Osborne505ba682018-01-30 12:36:50 -05002246<p>We do not use C++ exceptions.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002247
Victor Costanf0314ea2019-09-01 20:42:44 -07002248<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002249<ul>
2250 <li>Exceptions allow higher levels of an application to
2251 decide how to handle "can't happen" failures in deeply
2252 nested functions, without the obscuring and error-prone
2253 bookkeeping of error codes.</li>
2254
Ted Osborne505ba682018-01-30 12:36:50 -05002255
Victor Costanf0314ea2019-09-01 20:42:44 -07002256
2257 <div>
Ted Osborne505ba682018-01-30 12:36:50 -05002258 <li>Exceptions are used by most other
2259 modern languages. Using them in C++ would make it more
2260 consistent with Python, Java, and the C++ that others
2261 are familiar with.</li>
Victor Costanf0314ea2019-09-01 20:42:44 -07002262 </div>
Ted Osborne505ba682018-01-30 12:36:50 -05002263
2264 <li>Some third-party C++ libraries use exceptions, and
2265 turning them off internally makes it harder to
2266 integrate with those libraries.</li>
2267
2268 <li>Exceptions are the only way for a constructor to
2269 fail. We can simulate this with a factory function or
2270 an <code>Init()</code> method, but these require heap
2271 allocation or a new "invalid" state, respectively.</li>
2272
2273 <li>Exceptions are really handy in testing
2274 frameworks.</li>
2275</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05002276
Victor Costanf0314ea2019-09-01 20:42:44 -07002277<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002278<ul>
2279 <li>When you add a <code>throw</code> statement to an
2280 existing function, you must examine all of its
2281 transitive callers. Either they must make at least the
2282 basic exception safety guarantee, or they must never
2283 catch the exception and be happy with the program
2284 terminating as a result. For instance, if
2285 <code>f()</code> calls <code>g()</code> calls
2286 <code>h()</code>, and <code>h</code> throws an
2287 exception that <code>f</code> catches, <code>g</code>
2288 has to be careful or it may not clean up properly.</li>
2289
2290 <li>More generally, exceptions make the control flow of
2291 programs difficult to evaluate by looking at code:
2292 functions may return in places you don't expect. This
2293 causes maintainability and debugging difficulties. You
2294 can minimize this cost via some rules on how and where
2295 exceptions can be used, but at the cost of more that a
2296 developer needs to know and understand.</li>
2297
2298 <li>Exception safety requires both RAII and different
2299 coding practices. Lots of supporting machinery is
2300 needed to make writing correct exception-safe code
2301 easy. Further, to avoid requiring readers to understand
2302 the entire call graph, exception-safe code must isolate
2303 logic that writes to persistent state into a "commit"
2304 phase. This will have both benefits and costs (perhaps
2305 where you're forced to obfuscate code to isolate the
2306 commit). Allowing exceptions would force us to always
2307 pay those costs even when they're not worth it.</li>
2308
2309 <li>Turning on exceptions adds data to each binary
2310 produced, increasing compile time (probably slightly)
2311 and possibly increasing address space pressure.
2312 </li>
2313
2314 <li>The availability of exceptions may encourage
2315 developers to throw them when they are not appropriate
2316 or recover from them when it's not safe to do so. For
2317 example, invalid user input should not cause exceptions
2318 to be thrown. We would need to make the style guide
2319 even longer to document these restrictions!</li>
2320</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05002321
Victor Costanf0314ea2019-09-01 20:42:44 -07002322<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002323<p>On their face, the benefits of using exceptions
2324outweigh the costs, especially in new projects. However,
2325for existing code, the introduction of exceptions has
2326implications on all dependent code. If exceptions can be
2327propagated beyond a new project, it also becomes
2328problematic to integrate the new project into existing
2329exception-free code. Because most existing C++ code at
2330Google is not prepared to deal with exceptions, it is
2331comparatively difficult to adopt new code that generates
2332exceptions.</p>
2333
2334<p>Given that Google's existing code is not
2335exception-tolerant, the costs of using exceptions are
2336somewhat greater than the costs in a new project. The
2337conversion process would be slow and error-prone. We
2338don't believe that the available alternatives to
2339exceptions, such as error codes and assertions, introduce
2340a significant burden. </p>
2341
2342<p>Our advice against using exceptions is not predicated
2343on philosophical or moral grounds, but practical ones.
2344 Because we'd like to use our open-source
2345projects at Google and it's difficult to do so if those
2346projects use exceptions, we need to advise against
2347exceptions in Google open-source projects as well.
2348Things would probably be different if we had to do it all
2349over again from scratch.</p>
2350
Victor Costan6dfd9d92018-02-05 18:30:35 -08002351<p>This prohibition also applies to the exception handling related
2352features added in C++11, such as
2353<code>std::exception_ptr</code> and
Ted Osborne505ba682018-01-30 12:36:50 -05002354<code>std::nested_exception</code>.</p>
2355
2356<p>There is an <a href="#Windows_Code">exception</a> to
2357this rule (no pun intended) for Windows code.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002358
Victor Costan6dfd9d92018-02-05 18:30:35 -08002359<h3 id="noexcept"><code>noexcept</code></h3>
2360
Victor Costan6dfd9d92018-02-05 18:30:35 -08002361<p>Specify <code>noexcept</code> when it is useful and correct.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002362
Victor Costanf0314ea2019-09-01 20:42:44 -07002363<p class="definition"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002364<p>The <code>noexcept</code> specifier is used to specify whether
2365a function will throw exceptions or not. If an exception
2366escapes from a function marked <code>noexcept</code>, the program
2367crashes via <code>std::terminate</code>.</p>
2368
2369<p>The <code>noexcept</code> operator performs a compile-time
2370check that returns true if an expression is declared to not
2371throw any exceptions.</p>
2372
Victor Costanf0314ea2019-09-01 20:42:44 -07002373<p class="pros"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002374<ul>
2375 <li>Specifying move constructors as <code>noexcept</code>
2376 improves performance in some cases, e.g.
2377 <code>std::vector&lt;T&gt;::resize()</code> moves rather than
2378 copies the objects if T's move constructor is
2379 <code>noexcept</code>.</li>
2380
2381 <li>Specifying <code>noexcept</code> on a function can
2382 trigger compiler optimizations in environments where
2383 exceptions are enabled, e.g. compiler does not have to
2384 generate extra code for stack-unwinding, if it knows
2385 that no exceptions can be thrown due to a
2386 <code>noexcept</code> specifier.</li>
2387</ul>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002388
Victor Costanf0314ea2019-09-01 20:42:44 -07002389<p class="cons"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002390<ul>
2391 <li>
Victor Costanf0314ea2019-09-01 20:42:44 -07002392
Victor Costan6dfd9d92018-02-05 18:30:35 -08002393 In projects following this guide
2394 that have exceptions disabled it is hard
2395 to ensure that <code>noexcept</code>
2396 specifiers are correct, and hard to define what
2397 correctness even means.</li>
2398
2399 <li>It's hard, if not impossible, to undo <code>noexcept</code>
2400 because it eliminates a guarantee that callers may be relying
2401 on, in ways that are hard to detect.</li>
2402</ul>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002403
Victor Costanf0314ea2019-09-01 20:42:44 -07002404<p class="decision"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002405<p>You may use <code>noexcept</code> when it is useful for
2406performance if it accurately reflects the intended semantics
2407of your function, i.e. that if an exception is somehow thrown
2408from within the function body then it represents a fatal error.
2409You can assume that <code>noexcept</code> on move constructors
2410has a meaningful performance benefit. If you think
2411there is significant performance benefit from specifying
2412<code>noexcept</code> on some other function, please discuss it
Victor Costanf0314ea2019-09-01 20:42:44 -07002413with
Victor Costan6dfd9d92018-02-05 18:30:35 -08002414your project leads.</p>
2415
2416<p>Prefer unconditional <code>noexcept</code> if exceptions are
2417completely disabled (i.e. most Google C++ environments).
2418Otherwise, use conditional <code>noexcept</code> specifiers
2419with simple conditions, in ways that evaluate false only in
2420the few cases where the function could potentially throw.
2421The tests might include type traits check on whether the
2422involved operation might throw (e.g.
2423<code>std::is_nothrow_move_constructible</code> for
2424move-constructing objects), or on whether allocation can throw
2425(e.g. <code>absl::default_allocator_is_nothrow</code> for
2426standard default allocation). Note in many cases the only
2427possible cause for an exception is allocation failure (we
2428believe move constructors should not throw except due to
2429allocation failure), and there are many applications where it&#8217;s
2430appropriate to treat memory exhaustion as a fatal error rather
2431than an exceptional condition that your program should attempt
2432to recover from. Even for other
2433potential failures you should prioritize interface simplicity
2434over supporting all possible exception throwing scenarios:
2435instead of writing a complicated <code>noexcept</code> clause
2436that depends on whether a hash function can throw, for example,
2437simply document that your component doesn&#8217;t support hash
2438functions throwing and make it unconditionally
2439<code>noexcept</code>.</p>
2440
Ted Osborne505ba682018-01-30 12:36:50 -05002441<h3 id="Run-Time_Type_Information__RTTI_">Run-Time Type
2442Information (RTTI)</h3>
2443
Ted Osborne505ba682018-01-30 12:36:50 -05002444<p>Avoid using Run Time Type Information (RTTI).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002445
Victor Costanf0314ea2019-09-01 20:42:44 -07002446<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002447<p> RTTI allows a
2448programmer to query the C++ class of an object at run
2449time. This is done by use of <code>typeid</code> or
2450<code>dynamic_cast</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002451
Victor Costanf0314ea2019-09-01 20:42:44 -07002452<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002453<p>The standard alternatives to RTTI (described below)
2454require modification or redesign of the class hierarchy
2455in question. Sometimes such modifications are infeasible
2456or undesirable, particularly in widely-used or mature
2457code.</p>
2458
2459<p>RTTI can be useful in some unit tests. For example, it
2460is useful in tests of factory classes where the test has
2461to verify that a newly created object has the expected
2462dynamic type. It is also useful in managing the
2463relationship between objects and their mocks.</p>
2464
2465<p>RTTI is useful when considering multiple abstract
2466objects. Consider</p>
2467
2468<pre>bool Base::Equal(Base* other) = 0;
2469bool Derived::Equal(Base* other) {
2470 Derived* that = dynamic_cast&lt;Derived*&gt;(other);
Victor Costan6dfd9d92018-02-05 18:30:35 -08002471 if (that == nullptr)
Ted Osborne505ba682018-01-30 12:36:50 -05002472 return false;
2473 ...
2474}
2475</pre>
Ted Osborne505ba682018-01-30 12:36:50 -05002476
Victor Costanf0314ea2019-09-01 20:42:44 -07002477<p class="cons"></p>
2478<p>Querying the type of an object at run-time frequently
2479means a design problem. Needing to know the type of an
2480object at runtime is often an indication that the design
2481of your class hierarchy is flawed.</p>
2482
2483<p>Undisciplined use of RTTI makes code hard to maintain.
2484It can lead to type-based decision trees or switch
2485statements scattered throughout the code, all of which
2486must be examined when making further changes.</p>
2487
2488<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002489<p>RTTI has legitimate uses but is prone to abuse, so you
2490must be careful when using it. You may use it freely in
2491unittests, but avoid it when possible in other code. In
2492particular, think twice before using RTTI in new code. If
2493you find yourself needing to write code that behaves
2494differently based on the class of an object, consider one
2495of the following alternatives to querying the type:</p>
2496
2497<ul>
2498 <li>Virtual methods are the preferred way of executing
2499 different code paths depending on a specific subclass
2500 type. This puts the work within the object itself.</li>
2501
2502 <li>If the work belongs outside the object and instead
2503 in some processing code, consider a double-dispatch
2504 solution, such as the Visitor design pattern. This
2505 allows a facility outside the object itself to
2506 determine the type of class using the built-in type
2507 system.</li>
2508</ul>
2509
2510<p>When the logic of a program guarantees that a given
2511instance of a base class is in fact an instance of a
2512particular derived class, then a
2513<code>dynamic_cast</code> may be used freely on the
2514object. Usually one
2515can use a <code>static_cast</code> as an alternative in
2516such situations.</p>
2517
2518<p>Decision trees based on type are a strong indication
2519that your code is on the wrong track.</p>
2520
2521<pre class="badcode">if (typeid(*data) == typeid(D1)) {
2522 ...
2523} else if (typeid(*data) == typeid(D2)) {
2524 ...
2525} else if (typeid(*data) == typeid(D3)) {
2526...
2527</pre>
2528
2529<p>Code such as this usually breaks when additional
2530subclasses are added to the class hierarchy. Moreover,
2531when properties of a subclass change, it is difficult to
2532find and modify all the affected code segments.</p>
2533
2534<p>Do not hand-implement an RTTI-like workaround. The
2535arguments against RTTI apply just as much to workarounds
2536like class hierarchies with type tags. Moreover,
2537workarounds disguise your true intent.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002538
2539<h3 id="Casting">Casting</h3>
2540
Ted Osborne505ba682018-01-30 12:36:50 -05002541<p>Use C++-style casts
2542like <code>static_cast&lt;float&gt;(double_value)</code>, or brace
2543initialization for conversion of arithmetic types like
2544<code>int64 y = int64{1} &lt;&lt; 42</code>. Do not use
2545cast formats like
2546<code>int y = (int)x</code> or <code>int y = int(x)</code> (but the latter
2547is okay when invoking a constructor of a class type).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002548
Victor Costanf0314ea2019-09-01 20:42:44 -07002549<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002550<p> C++ introduced a
2551different cast system from C that distinguishes the types
2552of cast operations.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002553
Victor Costanf0314ea2019-09-01 20:42:44 -07002554<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002555<p>The problem with C casts is the ambiguity of the operation;
2556sometimes you are doing a <em>conversion</em>
2557(e.g., <code>(int)3.5</code>) and sometimes you are doing
2558a <em>cast</em> (e.g., <code>(int)"hello"</code>). Brace
2559initialization and C++ casts can often help avoid this
2560ambiguity. Additionally, C++ casts are more visible when searching for
2561them.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002562
Victor Costanf0314ea2019-09-01 20:42:44 -07002563<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002564<p>The C++-style cast syntax is verbose and cumbersome.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002565
Victor Costanf0314ea2019-09-01 20:42:44 -07002566<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002567<p>Do not use C-style casts. Instead, use these C++-style casts when
2568explicit type conversion is necessary. </p>
2569
2570<ul>
2571 <li>Use brace initialization to convert arithmetic types
2572 (e.g. <code>int64{x}</code>). This is the safest approach because code
2573 will not compile if conversion can result in information loss. The
2574 syntax is also concise.</li>
2575
Victor Costanf0314ea2019-09-01 20:42:44 -07002576
Ted Osborne505ba682018-01-30 12:36:50 -05002577
2578 <li>Use <code>static_cast</code> as the equivalent of a C-style cast
2579 that does value conversion, when you need to
2580 explicitly up-cast a pointer from a class to its superclass, or when
2581 you need to explicitly cast a pointer from a superclass to a
2582 subclass. In this last case, you must be sure your object is
2583 actually an instance of the subclass.</li>
2584
Victor Costanf0314ea2019-09-01 20:42:44 -07002585
Ted Osborne505ba682018-01-30 12:36:50 -05002586
2587 <li>Use <code>const_cast</code> to remove the
2588 <code>const</code> qualifier (see <a href="#Use_of_const">const</a>).</li>
2589
Victor Costanf0314ea2019-09-01 20:42:44 -07002590 <li>Use <code>reinterpret_cast</code> to do unsafe conversions of
2591 pointer types to and from integer and other pointer
2592 types. Use this
2593 only if you know what you are doing and you understand the aliasing
2594 issues. Also, consider the alternative
2595 <code>absl::bit_cast</code>.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05002596
Victor Costanf0314ea2019-09-01 20:42:44 -07002597 <li>Use <code>absl::bit_cast</code> to interpret the raw bits of a
2598 value using a different type of the same size (a type pun), such as
2599 interpreting the bits of a <code>double</code> as
2600 <code>int64</code>.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05002601</ul>
2602
2603<p>See the <a href="#Run-Time_Type_Information__RTTI_">
2604RTTI section</a> for guidance on the use of
2605<code>dynamic_cast</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002606
2607<h3 id="Streams">Streams</h3>
2608
Ted Osborne505ba682018-01-30 12:36:50 -05002609<p>Use streams where appropriate, and stick to "simple"
Victor Costan6dfd9d92018-02-05 18:30:35 -08002610usages. Overload <code>&lt;&lt;</code> for streaming only for types
2611representing values, and write only the user-visible value, not any
2612implementation details.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002613
Victor Costanf0314ea2019-09-01 20:42:44 -07002614<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002615<p>Streams are the standard I/O abstraction in C++, as
2616exemplified by the standard header <code>&lt;iostream&gt;</code>.
Victor Costanf0314ea2019-09-01 20:42:44 -07002617They are widely used in Google code, mostly for debug logging
Ted Osborne505ba682018-01-30 12:36:50 -05002618and test diagnostics.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002619
Victor Costanf0314ea2019-09-01 20:42:44 -07002620<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002621<p>The <code>&lt;&lt;</code> and <code>&gt;&gt;</code>
2622stream operators provide an API for formatted I/O that
2623is easily learned, portable, reusable, and extensible.
2624<code>printf</code>, by contrast, doesn't even support
Victor Costanf0314ea2019-09-01 20:42:44 -07002625<code>std::string</code>, to say nothing of user-defined types,
Ted Osborne505ba682018-01-30 12:36:50 -05002626and is very difficult to use portably.
2627<code>printf</code> also obliges you to choose among the
2628numerous slightly different versions of that function,
2629and navigate the dozens of conversion specifiers.</p>
2630
2631<p>Streams provide first-class support for console I/O
2632via <code>std::cin</code>, <code>std::cout</code>,
2633<code>std::cerr</code>, and <code>std::clog</code>.
2634The C APIs do as well, but are hampered by the need to
2635manually buffer the input. </p>
Ted Osborne505ba682018-01-30 12:36:50 -05002636
Victor Costanf0314ea2019-09-01 20:42:44 -07002637<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002638<ul>
2639<li>Stream formatting can be configured by mutating the
2640state of the stream. Such mutations are persistent, so
2641the behavior of your code can be affected by the entire
2642previous history of the stream, unless you go out of your
2643way to restore it to a known state every time other code
2644might have touched it. User code can not only modify the
2645built-in state, it can add new state variables and behaviors
2646through a registration system.</li>
2647
2648<li>It is difficult to precisely control stream output, due
2649to the above issues, the way code and data are mixed in
2650streaming code, and the use of operator overloading (which
2651may select a different overload than you expect).</li>
2652
2653<li>The practice of building up output through chains
2654of <code>&lt;&lt;</code> operators interferes with
2655internationalization, because it bakes word order into the
2656code, 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">
2657flawed</a>.</li>
2658
2659
2660
2661
2662
2663<li>The streams API is subtle and complex, so programmers must
Victor Costan6dfd9d92018-02-05 18:30:35 -08002664develop experience with it in order to use it effectively.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05002665
2666<li>Resolving the many overloads of <code>&lt;&lt;</code> is
2667extremely costly for the compiler. When used pervasively in a
2668large code base, it can consume as much as 20% of the parsing
2669and semantic analysis time.</li>
2670</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05002671
Victor Costanf0314ea2019-09-01 20:42:44 -07002672<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002673<p>Use streams only when they are the best tool for the job.
2674This is typically the case when the I/O is ad-hoc, local,
2675human-readable, and targeted at other developers rather than
2676end-users. Be consistent with the code around you, and with the
2677codebase as a whole; if there's an established tool for
Victor Costan4b9c0c02018-02-20 14:58:48 -08002678your problem, use that tool instead.
2679In particular,
Victor Costanb89a7752018-07-31 10:17:48 -07002680
Victor Costan4b9c0c02018-02-20 14:58:48 -08002681logging libraries are usually a better
2682choice than <code>std::cerr</code> or <code>std::clog</code>
2683for diagnostic output, and the libraries in
2684
2685<code>absl/strings</code>
2686or the equivalent are usually a
2687better choice than <code>std::stringstream</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002688
2689<p>Avoid using streams for I/O that faces external users or
2690handles untrusted data. Instead, find and use the appropriate
2691templating libraries to handle issues like internationalization,
2692localization, and security hardening.</p>
2693
2694<p>If you do use streams, avoid the stateful parts of the
2695streams API (other than error state), such as <code>imbue()</code>,
2696<code>xalloc()</code>, and <code>register_callback()</code>.
Victor Costan4b9c0c02018-02-20 14:58:48 -08002697Use explicit formatting functions (see e.g.
2698
2699<code>absl/strings</code>)
2700rather than
Ted Osborne505ba682018-01-30 12:36:50 -05002701stream manipulators or formatting flags to control formatting
2702details such as number base, precision, or padding.</p>
2703
2704<p>Overload <code>&lt;&lt;</code> as a streaming operator
2705for your type only if your type represents a value, and
2706<code>&lt;&lt;</code> writes out a human-readable string
2707representation of that value. Avoid exposing implementation
2708details in the output of <code>&lt;&lt;</code>; if you need to print
2709object internals for debugging, use named functions instead
2710(a method named <code>DebugString()</code> is the most common
2711convention).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002712
2713<h3 id="Preincrement_and_Predecrement">Preincrement and Predecrement</h3>
2714
Ted Osborne505ba682018-01-30 12:36:50 -05002715<p>Use prefix form (<code>++i</code>) of the increment and
2716decrement operators with iterators and other template
2717objects.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002718
Victor Costanf0314ea2019-09-01 20:42:44 -07002719<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002720<p> When a variable
2721is incremented (<code>++i</code> or <code>i++</code>) or
2722decremented (<code>--i</code> or <code>i--</code>) and
2723the value of the expression is not used, one must decide
2724whether to preincrement (decrement) or postincrement
2725(decrement).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002726
Victor Costanf0314ea2019-09-01 20:42:44 -07002727<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002728<p>When the return value is ignored, the "pre" form
2729(<code>++i</code>) is never less efficient than the
2730"post" form (<code>i++</code>), and is often more
2731efficient. This is because post-increment (or decrement)
2732requires a copy of <code>i</code> to be made, which is
2733the value of the expression. If <code>i</code> is an
2734iterator or other non-scalar type, copying <code>i</code>
2735could be expensive. Since the two types of increment
2736behave the same when the value is ignored, why not just
2737always pre-increment?</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002738
Victor Costanf0314ea2019-09-01 20:42:44 -07002739<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002740<p>The tradition developed, in C, of using post-increment
2741when the expression value is not used, especially in
2742<code>for</code> loops. Some find post-increment easier
2743to read, since the "subject" (<code>i</code>) precedes
2744the "verb" (<code>++</code>), just like in English.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002745
Victor Costanf0314ea2019-09-01 20:42:44 -07002746<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002747<p> For simple scalar
2748(non-object) values there is no reason to prefer one form
2749and we allow either. For iterators and other template
2750types, use pre-increment.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002751
2752<h3 id="Use_of_const">Use of const</h3>
2753
Victor Costan967e1572019-09-05 05:09:38 -07002754<p>In APIs, use <code>const</code> whenever it makes sense.
Ted Osborne505ba682018-01-30 12:36:50 -05002755<code>constexpr</code> is a better choice for some uses of
2756const.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002757
Victor Costanf0314ea2019-09-01 20:42:44 -07002758<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002759<p> Declared variables and parameters can be preceded
2760by the keyword <code>const</code> to indicate the variables
2761are not changed (e.g., <code>const int foo</code>). Class
2762functions can have the <code>const</code> qualifier to
2763indicate the function does not change the state of the
2764class member variables (e.g., <code>class Foo { int
2765Bar(char c) const; };</code>).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002766
Victor Costanf0314ea2019-09-01 20:42:44 -07002767<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002768<p>Easier for people to understand how variables are being
2769used. Allows the compiler to do better type checking,
2770and, conceivably, generate better code. Helps people
2771convince themselves of program correctness because they
2772know the functions they call are limited in how they can
2773modify your variables. Helps people know what functions
2774are safe to use without locks in multi-threaded
2775programs.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002776
Victor Costanf0314ea2019-09-01 20:42:44 -07002777<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002778<p><code>const</code> is viral: if you pass a
2779<code>const</code> variable to a function, that function
2780must have <code>const</code> in its prototype (or the
2781variable will need a <code>const_cast</code>). This can
2782be a particular problem when calling library
2783functions.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002784
Victor Costanf0314ea2019-09-01 20:42:44 -07002785<p class="decision"></p>
2786<p>We strongly recommend using <code>const</code>
2787in APIs (i.e. on function parameters, methods, and
2788non-local variables) wherever it is meaningful and accurate. This
2789provides consistent, mostly compiler-verified documentation
2790of what objects an operation can mutate. Having
2791a consistent and reliable way to distinguish reads from writes
2792is critical to writing thread-safe code, and is useful in
2793many other contexts as well. In particular:</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002794
2795<ul>
2796 <li>If a function guarantees that it will not modify an argument
2797 passed by reference or by pointer, the corresponding function parameter
2798 should be a reference-to-const (<code>const T&amp;</code>) or
2799 pointer-to-const (<code>const T*</code>), respectively.</li>
2800
Victor Costanf0314ea2019-09-01 20:42:44 -07002801 <li>For a function parameter passed by value, <code>const</code> has
2802 no effect on the caller, thus is not recommended in function
2803 declarations. See
Ted Osborne505ba682018-01-30 12:36:50 -05002804
Victor Costanf0314ea2019-09-01 20:42:44 -07002805
2806 <a href="https://abseil.io/tips/109">TotW #109</a>.
2807
2808
2809 </li><li>Declare methods to be <code>const</code> unless they
2810 alter the logical state of the object (or enable the user to modify
2811 that state, e.g. by returning a non-const reference, but that's
2812 rare), or they can't safely be invoked concurrently.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05002813</ul>
2814
Victor Costanf0314ea2019-09-01 20:42:44 -07002815<p>Using <code>const</code> on local variables is neither encouraged
2816nor discouraged.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002817
Victor Costanf0314ea2019-09-01 20:42:44 -07002818<p>All of a class's <code>const</code> operations should be safe
2819to invoke concurrently with each other. If that's not feasible, the class must
2820be clearly documented as "thread-unsafe".</p>
2821
2822
Ted Osborne505ba682018-01-30 12:36:50 -05002823<h4>Where to put the const</h4>
2824
2825<p>Some people favor the form <code>int const *foo</code>
2826to <code>const int* foo</code>. They argue that this is
2827more readable because it's more consistent: it keeps the
2828rule that <code>const</code> always follows the object
2829it's describing. However, this consistency argument
2830doesn't apply in codebases with few deeply-nested pointer
2831expressions since most <code>const</code> expressions
2832have only one <code>const</code>, and it applies to the
2833underlying value. In such cases, there's no consistency
2834to maintain. Putting the <code>const</code> first is
2835arguably more readable, since it follows English in
2836putting the "adjective" (<code>const</code>) before the
2837"noun" (<code>int</code>).</p>
2838
2839<p>That said, while we encourage putting
2840<code>const</code> first, we do not require it. But be
2841consistent with the code around you!</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002842
2843<h3 id="Use_of_constexpr">Use of constexpr</h3>
2844
Victor Costan967e1572019-09-05 05:09:38 -07002845<p>Use <code>constexpr</code> to define true
Ted Osborne505ba682018-01-30 12:36:50 -05002846constants or to ensure constant initialization.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002847
Victor Costanf0314ea2019-09-01 20:42:44 -07002848<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002849<p> Some variables can be declared <code>constexpr</code>
2850to indicate the variables are true constants, i.e. fixed at
2851compilation/link time. Some functions and constructors
2852can be declared <code>constexpr</code> which enables them
2853to be used in defining a <code>constexpr</code>
2854variable.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002855
Victor Costanf0314ea2019-09-01 20:42:44 -07002856<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002857<p>Use of <code>constexpr</code> enables definition of
2858constants with floating-point expressions rather than
2859just literals; definition of constants of user-defined
2860types; and definition of constants with function
2861calls.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002862
Victor Costanf0314ea2019-09-01 20:42:44 -07002863<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002864<p>Prematurely marking something as constexpr may cause
2865migration problems if later on it has to be downgraded.
2866Current restrictions on what is allowed in constexpr
2867functions and constructors may invite obscure workarounds
2868in these definitions.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002869
Victor Costanf0314ea2019-09-01 20:42:44 -07002870<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002871<p><code>constexpr</code> definitions enable a more
2872robust specification of the constant parts of an
2873interface. Use <code>constexpr</code> to specify true
2874constants and the functions that support their
2875definitions. Avoid complexifying function definitions to
2876enable their use with <code>constexpr</code>. Do not use
2877<code>constexpr</code> to force inlining.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002878
2879<h3 id="Integer_Types">Integer Types</h3>
2880
Ted Osborne505ba682018-01-30 12:36:50 -05002881<p>Of the built-in C++ integer types, the only one used
2882 is
2883<code>int</code>. If a program needs a variable of a
Victor Costanf0314ea2019-09-01 20:42:44 -07002884different size, use
Ted Osborne505ba682018-01-30 12:36:50 -05002885a precise-width integer type from
2886<code>&lt;stdint.h&gt;</code>, such as
2887<code>int16_t</code>. If your variable represents a
2888value that could ever be greater than or equal to 2^31
2889(2GiB), use a 64-bit type such as
2890<code>int64_t</code>.
2891Keep in mind that even if your value won't ever be too large
2892for an <code>int</code>, it may be used in intermediate
2893calculations which may require a larger type. When in doubt,
2894choose a larger type.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002895
Victor Costanf0314ea2019-09-01 20:42:44 -07002896<p class="definition"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002897<p> C++ does not specify the sizes of integer types
2898like <code>int</code>. Typically people assume
2899that <code>short</code> is 16 bits,
Ted Osborne505ba682018-01-30 12:36:50 -05002900<code>int</code> is 32 bits, <code>long</code> is 32 bits
2901and <code>long long</code> is 64 bits.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002902
Victor Costanf0314ea2019-09-01 20:42:44 -07002903<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002904<p>Uniformity of declaration.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002905
Victor Costanf0314ea2019-09-01 20:42:44 -07002906<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002907<p>The sizes of integral types in C++ can vary based on
2908compiler and architecture.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002909
Victor Costanf0314ea2019-09-01 20:42:44 -07002910<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05002911
2912<p>
Victor Costanf0314ea2019-09-01 20:42:44 -07002913<code>&lt;cstdint&gt;</code> defines types
Ted Osborne505ba682018-01-30 12:36:50 -05002914like <code>int16_t</code>, <code>uint32_t</code>,
2915<code>int64_t</code>, etc. You should always use
2916those in preference to <code>short</code>, <code>unsigned
2917long long</code> and the like, when you need a guarantee
2918on the size of an integer. Of the C integer types, only
2919<code>int</code> should be used. When appropriate, you
2920are welcome to use standard types like
2921<code>size_t</code> and <code>ptrdiff_t</code>.</p>
2922
2923<p>We use <code>int</code> very often, for integers we
2924know are not going to be too big, e.g., loop counters.
2925Use plain old <code>int</code> for such things. You
2926should assume that an <code>int</code> is
2927
2928at least 32 bits, but don't
2929assume that it has more than 32 bits. If you need a 64-bit
2930integer type, use
2931<code>int64_t</code>
2932or
2933<code>uint64_t</code>.</p>
2934
2935<p>For integers we know can be "big",
2936 use
2937<code>int64_t</code>.
2938</p>
2939
2940<p>You should not use the unsigned integer types such as
Victor Costanf0314ea2019-09-01 20:42:44 -07002941
Ted Osborne505ba682018-01-30 12:36:50 -05002942<code>uint32_t</code>, unless there is a valid
2943reason such as representing a bit pattern rather than a
2944number, or you need defined overflow modulo 2^N. In
2945particular, do not use unsigned types to say a number
Victor Costanf0314ea2019-09-01 20:42:44 -07002946will never be negative. Instead, use
2947
Ted Osborne505ba682018-01-30 12:36:50 -05002948assertions for this.</p>
2949
2950
2951
2952<p>If your code is a container that returns a size, be
2953sure to use a type that will accommodate any possible
2954usage of your container. When in doubt, use a larger type
2955rather than a smaller type.</p>
2956
Victor Costan6dfd9d92018-02-05 18:30:35 -08002957<p>Use care when converting integer types. Integer conversions and
2958promotions can cause undefined behavior, leading to security bugs and
2959other problems.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002960
2961<h4>On Unsigned Integers</h4>
2962
Victor Costan6dfd9d92018-02-05 18:30:35 -08002963<p>Unsigned integers are good for representing bitfields and modular
2964arithmetic. Because of historical accident, the C++ standard also uses
2965unsigned integers to represent the size of containers - many members
2966of the standards body believe this to be a mistake, but it is
2967effectively impossible to fix at this point. The fact that unsigned
2968arithmetic doesn't model the behavior of a simple integer, but is
2969instead defined by the standard to model modular arithmetic (wrapping
2970around on overflow/underflow), means that a significant class of bugs
2971cannot be diagnosed by the compiler. In other cases, the defined
2972behavior impedes optimization.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002973
Victor Costan6dfd9d92018-02-05 18:30:35 -08002974<p>That said, mixing signedness of integer types is responsible for an
2975equally large class of problems. The best advice we can provide: try
2976to use iterators and containers rather than pointers and sizes, try
2977not to mix signedness, and try to avoid unsigned types (except for
2978representing bitfields or modular arithmetic). Do not use an unsigned
2979type merely to assert that a variable is non-negative.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002980
2981<h3 id="64-bit_Portability">64-bit Portability</h3>
2982
Ted Osborne505ba682018-01-30 12:36:50 -05002983<p>Code should be 64-bit and 32-bit friendly. Bear in mind
2984problems of printing, comparisons, and structure alignment.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05002985
2986<ul>
2987 <li>
Victor Costan6dfd9d92018-02-05 18:30:35 -08002988 <p>Correct portable <code>printf()</code> conversion specifiers for
2989 some integral typedefs rely on macro expansions that we find unpleasant to
2990 use and impractical to require (the <code>PRI</code> macros from
2991 <code>&lt;cinttypes&gt;</code>). Unless there is no reasonable alternative
2992 for your particular case, try to avoid or even upgrade APIs that rely on the
2993 <code>printf</code> family. Instead use a library supporting typesafe numeric
2994 formatting, such as
Victor Costanf0314ea2019-09-01 20:42:44 -07002995
2996
Victor Costan4b9c0c02018-02-20 14:58:48 -08002997 <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/strings/str_cat.h"><code>StrCat</code></a>
Victor Costanf0314ea2019-09-01 20:42:44 -07002998
Victor Costan4b9c0c02018-02-20 14:58:48 -08002999 or
Victor Costanf0314ea2019-09-01 20:42:44 -07003000
3001
Victor Costan4b9c0c02018-02-20 14:58:48 -08003002 <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/strings/substitute.h"><code>Substitute</code></a>
Victor Costanf0314ea2019-09-01 20:42:44 -07003003
Victor Costan4b9c0c02018-02-20 14:58:48 -08003004 for fast simple conversions,
Victor Costanf0314ea2019-09-01 20:42:44 -07003005
3006 or <a href="#Streams"><code>std::ostream</code></a>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003007
Victor Costan6dfd9d92018-02-05 18:30:35 -08003008 <p>Unfortunately, the <code>PRI</code> macros are the only portable way to
3009 specify a conversion for the standard bitwidth typedefs (e.g.
3010 <code>int64_t</code>, <code>uint64_t</code>, <code>int32_t</code>,
3011 <code>uint32_t</code>, etc).
Victor Costanf0314ea2019-09-01 20:42:44 -07003012
Victor Costan6dfd9d92018-02-05 18:30:35 -08003013 Where possible, avoid passing arguments of types specified by bitwidth
3014 typedefs to <code>printf</code>-based APIs. Note that it is acceptable
3015 to use typedefs for which printf has dedicated length modifiers, such as
3016 <code>size_t</code> (<code>z</code>),
3017 <code>ptrdiff_t</code> (<code>t</code>), and
3018 <code>maxint_t</code> (<code>j</code>).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003019 </li>
3020
3021 <li>Remember that <code>sizeof(void *)</code> !=
3022 <code>sizeof(int)</code>. Use <code>intptr_t</code> if
3023 you want a pointer-sized integer.</li>
3024
3025 <li>You may need to be careful with structure
3026 alignments, particularly for structures being stored on
Victor Costanf0314ea2019-09-01 20:42:44 -07003027 disk. Any class/structure with a
Ted Osborne505ba682018-01-30 12:36:50 -05003028 <code>int64_t</code>/<code>uint64_t</code>
3029 member will by default end up being 8-byte aligned on a
3030 64-bit system. If you have such structures being shared
3031 on disk between 32-bit and 64-bit code, you will need
3032 to ensure that they are packed the same on both
Victor Costanf0314ea2019-09-01 20:42:44 -07003033 architectures.
Ted Osborne505ba682018-01-30 12:36:50 -05003034 Most compilers offer a way to
3035 alter structure alignment. For gcc, you can use
3036 <code>__attribute__((packed))</code>. MSVC offers
3037 <code>#pragma pack()</code> and
3038 <code>__declspec(align())</code>.</li>
3039
3040 <li>
Victor Costan6dfd9d92018-02-05 18:30:35 -08003041 <p>Use <a href="#Casting">braced-initialization</a> as needed to create
3042 64-bit constants. For example:</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003043
3044
Victor Costanf0314ea2019-09-01 20:42:44 -07003045<div>
Victor Costan6dfd9d92018-02-05 18:30:35 -08003046<pre>int64_t my_value{0x123456789};
3047uint64_t my_mask{3ULL &lt;&lt; 48};
Ted Osborne505ba682018-01-30 12:36:50 -05003048</pre>
Victor Costanf0314ea2019-09-01 20:42:44 -07003049</div>
Ted Osborne505ba682018-01-30 12:36:50 -05003050 </li>
3051</ul>
3052
Ted Osborne505ba682018-01-30 12:36:50 -05003053<h3 id="Preprocessor_Macros">Preprocessor Macros</h3>
3054
Ted Osborne505ba682018-01-30 12:36:50 -05003055<p>Avoid defining macros, especially in headers; prefer
3056inline functions, enums, and <code>const</code> variables.
3057Name macros with a project-specific prefix. Do not use
3058macros to define pieces of a C++ API.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003059
3060<p>Macros mean that the code you see is not the same as
3061the code the compiler sees. This can introduce unexpected
3062behavior, especially since macros have global scope.</p>
3063
3064<p>The problems introduced by macros are especially severe
3065when they are used to define pieces of a C++ API,
3066and still more so for public APIs. Every error message from
3067the compiler when developers incorrectly use that interface
3068now must explain how the macros formed the interface.
3069Refactoring and analysis tools have a dramatically harder
3070time updating the interface. As a consequence, we
3071specifically disallow using macros in this way.
3072For example, avoid patterns like:</p>
3073
3074<pre class="badcode">class WOMBAT_TYPE(Foo) {
3075 // ...
3076
3077 public:
3078 EXPAND_PUBLIC_WOMBAT_API(Foo)
3079
3080 EXPAND_WOMBAT_COMPARISONS(Foo, ==, &lt;)
3081};
3082</pre>
3083
3084<p>Luckily, macros are not nearly as necessary in C++ as
3085they are in C. Instead of using a macro to inline
3086performance-critical code, use an inline function.
3087Instead of using a macro to store a constant, use a
3088<code>const</code> variable. Instead of using a macro to
3089"abbreviate" a long variable name, use a reference.
3090Instead of using a macro to conditionally compile code
3091... well, don't do that at all (except, of course, for
3092the <code>#define</code> guards to prevent double
3093inclusion of header files). It makes testing much more
3094difficult.</p>
3095
3096<p>Macros can do things these other techniques cannot,
3097and you do see them in the codebase, especially in the
3098lower-level libraries. And some of their special features
3099(like stringifying, concatenation, and so forth) are not
3100available through the language proper. But before using a
3101macro, consider carefully whether there's a non-macro way
3102to achieve the same result. If you need to use a macro to
Victor Costanf0314ea2019-09-01 20:42:44 -07003103define an interface, contact
Ted Osborne505ba682018-01-30 12:36:50 -05003104your project leads to request
3105a waiver of this rule.</p>
3106
3107<p>The following usage pattern will avoid many problems
3108with macros; if you use macros, follow it whenever
3109possible:</p>
3110
3111<ul>
3112 <li>Don't define macros in a <code>.h</code> file.</li>
3113
3114 <li><code>#define</code> macros right before you use
3115 them, and <code>#undef</code> them right after.</li>
3116
3117 <li>Do not just <code>#undef</code> an existing macro
3118 before replacing it with your own; instead, pick a name
3119 that's likely to be unique.</li>
3120
3121 <li>Try not to use macros that expand to unbalanced C++
3122 constructs, or at least document that behavior
3123 well.</li>
3124
3125 <li>Prefer not using <code>##</code> to generate
3126 function/class/variable names.</li>
3127</ul>
3128
3129<p>Exporting macros from headers (i.e. defining them in a header
3130without <code>#undef</code>ing them before the end of the header)
3131is extremely strongly discouraged. If you do export a macro from a
3132header, it must have a globally unique name. To achieve this, it
3133must be named with a prefix consisting of your project's namespace
3134name (but upper case). </p>
3135
Ted Osborne505ba682018-01-30 12:36:50 -05003136<h3 id="0_and_nullptr/NULL">0 and nullptr/NULL</h3>
3137
Victor Costanf0314ea2019-09-01 20:42:44 -07003138<p>Use <code>nullptr</code> for pointers, and <code>'\0'</code> for chars (and
3139not the <code>0</code> literal).</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003140
Victor Costanb89a7752018-07-31 10:17:48 -07003141<p>For pointers (address values), use <code>nullptr</code>, as this
3142provides type-safety.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003143
Victor Costan6dfd9d92018-02-05 18:30:35 -08003144<p>For C++03 projects, prefer <code>NULL</code> to <code>0</code>. While the
3145values are equivalent, <code>NULL</code> looks more like a pointer to the
3146reader, and some C++ compilers provide special definitions of <code>NULL</code>
Victor Costanf0314ea2019-09-01 20:42:44 -07003147which enable them to give useful warnings. Never use <code>NULL</code> for
3148numeric (integer or floating-point) values.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08003149
3150<p>Use <code>'\0'</code> for the null character. Using the correct type makes
3151the code more readable.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003152
Ted Osborne505ba682018-01-30 12:36:50 -05003153<h3 id="sizeof">sizeof</h3>
3154
Ted Osborne505ba682018-01-30 12:36:50 -05003155<p>Prefer <code>sizeof(<var>varname</var>)</code> to
3156<code>sizeof(<var>type</var>)</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003157
3158<p>Use <code>sizeof(<var>varname</var>)</code> when you
3159take the size of a particular variable.
3160<code>sizeof(<var>varname</var>)</code> will update
3161appropriately if someone changes the variable type either
3162now or later. You may use
3163<code>sizeof(<var>type</var>)</code> for code unrelated
3164to any particular variable, such as code that manages an
3165external or internal data format where a variable of an
3166appropriate C++ type is not convenient.</p>
3167
Victor Costan967e1572019-09-05 05:09:38 -07003168<pre>struct data;
Ted Osborne505ba682018-01-30 12:36:50 -05003169memset(&amp;data, 0, sizeof(data));
3170</pre>
3171
3172<pre class="badcode">memset(&amp;data, 0, sizeof(Struct));
3173</pre>
3174
3175<pre>if (raw_size &lt; sizeof(int)) {
3176 LOG(ERROR) &lt;&lt; "compressed record not big enough for count: " &lt;&lt; raw_size;
3177 return false;
3178}
3179</pre>
3180
Victor Costan967e1572019-09-05 05:09:38 -07003181<a name="auto"></a>
3182<h3 id="Type_deduction">Type deduction</h3>
Ted Osborne505ba682018-01-30 12:36:50 -05003183
Victor Costan967e1572019-09-05 05:09:38 -07003184<p>Use type deduction only if it makes the code clearer to readers who aren't
3185 familiar with the project, or if it makes the code safer. Do not use it
3186 merely to avoid the inconvenience of writing an explicit type.</p>
3187
3188<p class="definition"></p>
3189
3190<p>There are several contexts in which C++ allows (or even requires) types to
3191be deduced by the compiler, rather than spelled out explicitly in the code:</p>
3192<dl>
3193 <dt><a href="https://en.cppreference.com/w/cpp/language/template_argument_deduction">Function template argument deduction</a></dt>
3194 <dd>A function template can be invoked without explicit template arguments.
3195 The compiler deduces those arguments from the types of the function
3196 arguments:
3197 <pre class="neutralcode">template &lt;typename T&gt;
3198void f(T t);
3199
3200f(0); // Invokes f&lt;int&gt;(0)</pre>
3201 </dd>
3202 <dt><a href="https://en.cppreference.com/w/cpp/language/auto"><code>auto</code> variable declarations</a></dt>
3203 <dd>A variable declaration can use the <code>auto</code> keyword in place
3204 of the type. The compiler deduces the type from the variable's
3205 initializer, following the same rules as function template argument
3206 deduction with the same initializer (so long as you don't use curly braces
3207 instead of parentheses).
3208 <pre class="neutralcode">auto a = 42; // a is an int
3209auto&amp; b = a; // b is an int&amp;
3210auto c = b; // c is an int
3211auto d{42}; // d is an int, not a std::initializer_list&lt;int&gt;
3212</pre>
3213 <code>auto</code> can be qualified with <code>const</code>, and can be
3214 used as part of a pointer or reference type, but it can't be used as a
3215 template argument. A rare variant of this syntax uses
3216 <code>decltype(auto)</code> instead of <code>auto</code>, in which case
3217 the deduced type is the result of applying
3218 <a href="https://en.cppreference.com/w/cpp/language/decltype"><code>decltype</code></a>
3219 to the initializer.
3220 </dd>
3221 <dt><a href="https://en.cppreference.com/w/cpp/language/function#Return_type_deduction">Function return type deduction</a></dt>
3222 <dd><code>auto</code> (and <code>decltype(auto)</code>) can also be used in
3223 place of a function return type. The compiler deduces the return type from
3224 the <code>return</code> statements in the function body, following the same
3225 rules as for variable declarations:
3226 <pre class="neutralcode">auto f() { return 0; } // The return type of f is int</pre>
3227 <a href="#Lambda_expressions">Lambda expression</a> return types can be
3228 deduced in the same way, but this is triggered by omitting the return type,
3229 rather than by an explicit <code>auto</code>. Confusingly,
3230 <a href="trailing_return">trailing return type</a> syntax for functions
3231 also uses <code>auto</code> in the return-type position, but that doesn't
3232 rely on type deduction; it's just an alternate syntax for an explicit
3233 return type.
3234 </dd>
3235 <dt><a href="https://isocpp.org/wiki/faq/cpp14-language#generic-lambdas">Generic lambdas</a></dt>
3236 <dd>A lambda expression can use the <code>auto</code> keyword in place of
3237 one or more of its parameter types. This causes the lambda's call operator
3238 to be a function template instead of an ordinary function, with a separate
3239 template parameter for each <code>auto</code> function parameter:
3240 <pre class="neutralcode">// Sort `vec` in increasing order
3241std::sort(vec.begin(), vec.end(), [](auto lhs, auto rhs) { return lhs &gt; rhs; });</pre>
3242 </dd>
3243 <dt><a href="https://isocpp.org/wiki/faq/cpp14-language#lambda-captures">Lambda init captures</a></dt>
3244 <dd>Lambda captures can have explicit initializers, which can be used to
3245 declare wholly new variables rather than only capturing existing ones:
3246 <pre class="neutralcode">[x = 42, y = "foo"] { ... } // x is an int, and y is a const char*</pre>
3247 This syntax doesn't allow the type to be specified; instead, it's deduced
3248 using the rules for <code>auto</code> variables.
3249 </dd>
3250 <dt><a href="https://en.cppreference.com/w/cpp/language/class_template_argument_deduction">Class template argument deduction</a></dt>
3251 <dd>See <a href="#CTAD">below</a>.</dd>
3252 <dt><a href="https://en.cppreference.com/w/cpp/language/structured_binding">Structured bindings</a></dt>
3253 <dd>When declaring a tuple, struct, or array using <code>auto</code>, you can
3254 specify names for the individual elements instead of a name for the whole
3255 object; these names are called "structured bindings", and the whole
3256 declaration is called a "structured binding declaration". This syntax
3257 provides no way of specifying the type of either the enclosing object
3258 or the individual names:
3259 <pre class="neutralcode">auto [iter, success] = my_map.insert({key, value});
3260if (!success) {
3261 iter-&gt;second = value;
3262}</pre>
3263 The <code>auto</code> can also be qualified with <code>const</code>,
3264 <code>&amp;</code>, and <code>&amp;&amp;</code>, but note that these qualifiers
3265 technically apply to the anonymous tuple/struct/array, rather than the
3266 individual bindings. The rules that determine the types of the bindings
3267 are quite complex; the results tend to be unsurprising, except that
3268 the binding types typically won't be references even if the declaration
3269 declares a reference (but they will usually behave like references anyway).
3270 </dd>
3271
3272<p>(These summaries omit many details and caveats; see the links for further
3273 information.)</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003274
Victor Costanf0314ea2019-09-01 20:42:44 -07003275<p class="pros"></p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08003276
3277<ul>
Victor Costan967e1572019-09-05 05:09:38 -07003278 <li>C++ type names can be long and cumbersome, especially when they
3279 involve templates or namespaces.</li>
3280 <li>When a C++ type name is repeated within a single declaration or a
3281 small code region, the repetition may not be aiding readability.</li>
3282 <li>It is sometimes safer to let the type be deduced, since that avoids
3283 the possibility of unintended copies or type conversions.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05003284</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003285
Victor Costanf0314ea2019-09-01 20:42:44 -07003286<p class="cons"></p>
Victor Costan967e1572019-09-05 05:09:38 -07003287<p>C++ code is usually clearer when types are explicit,
3288 especially when type deduction would depend on information from
3289 distant parts of the code. In expressions like:</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003290
3291<pre class="badcode">auto foo = x.add_foo();
3292auto i = y.Find(key);
3293</pre>
3294
3295<p>it may not be obvious what the resulting types are if the type
Victor Costan967e1572019-09-05 05:09:38 -07003296 of <code>y</code> isn't very well known, or if <code>y</code> was
3297 declared many lines earlier.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003298
Victor Costan967e1572019-09-05 05:09:38 -07003299<p>Programmers have to understand when type deduction will or won't
3300 produce a reference type, or they'll get copies when they didn't
3301 mean to.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003302
Victor Costan967e1572019-09-05 05:09:38 -07003303<p>If a deduced type is used as part of an interface, then a
3304 programmer might change its type while only intending to
3305 change its value, leading to a more radical API change
3306 than intended.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003307
Victor Costanf0314ea2019-09-01 20:42:44 -07003308<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003309
Victor Costan967e1572019-09-05 05:09:38 -07003310<p>The fundamental rule is: use type deduction only to make the code
3311 clearer or safer, and do not use it merely to avoid the
3312 inconvenience of writing an explicit type. When judging whether the
3313 code is clearer, keep in mind that your readers are not necessarily
3314 on your team, or familiar with your project, so types that you and
3315 your reviewer experience as as unnecessary clutter will very often
3316 provide useful information to others. For example, you can assume that
3317 the return type of <code>make_unique&lt;Foo&gt;()</code> is obvious,
3318 but the return type of <code>MyWidgetFactory()</code> probably isn't.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003319
Victor Costan967e1572019-09-05 05:09:38 -07003320 <p>These principles applies to all forms of type deduction, but the
3321 details vary, as described in the following sections.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003322
Victor Costan967e1572019-09-05 05:09:38 -07003323<h4>Function template argument deduction</h4>
3324
3325<p>Function template argument deduction is almost always OK. Type deduction
3326 is the expected default way of interacting with function templates,
3327 because it allows function templates to act like infinite sets of ordinary
3328 function overloads. Consequently, function templates are almost always
3329 designed so that template argument deduction is clear and safe, or
3330 doesn't compile.</p>
3331
3332<h4>Local variable type deduction</h4>
3333
3334<p>For local variables, you can use type deduction to make the code clearer
3335 by eliminating type information that is obvious or irrelevant, so that
3336 the reader can focus on the meaningful parts of the code:
3337 </p><pre class="neutralcode">std::unique_ptr&lt;WidgetWithBellsAndWhistles&gt; widget_ptr =
3338 absl::make_unique&lt;WidgetWithBellsAndWhistles&gt;(arg1, arg2);
3339absl::flat_hash_map&lt;std::string,
3340 std::unique_ptr&lt;WidgetWithBellsAndWhistles&gt;&gt;::const_iterator
3341 it = my_map_.find(key);
3342std::array&lt;int, 0&gt; numbers = {4, 8, 15, 16, 23, 42};</pre>
3343
3344 <pre class="goodcode">auto widget_ptr = absl::make_unique&lt;WidgetWithBellsAndWhistles&gt;(arg1, arg2);
3345auto it = my_map_.find(key);
3346std::array numbers = {4, 8, 15, 16, 23, 42};</pre>
3347
3348<p>Types sometimes contain a mixture of useful information and boilerplate,
3349 such as <code>it</code> in the example above: it's obvious that the
3350 type is an iterator, and in many contexts the container type and even the
3351 key type aren't relevant, but the type of the values is probably useful.
3352 In such situations, it's often possible to define local variables with
3353 explicit types that convey the relevant information:
3354 </p><pre class="goodcode">auto it = my_map_.find(key);
3355if (it != my_map_.end()) {
3356 WidgetWithBellsAndWhistles&amp; widget = *it-&gt;second;
3357 // Do stuff with `widget`
3358}</pre>
3359 If the type is a template instance, and the parameters are
3360 boilerplate but the template itself is informative, you can use
3361 class template argument deduction to suppress the boilerplate. However,
3362 cases where this actually provides a meaningful benefit are quite rare.
3363 Note that class template argument deduction is also subject to a
3364 <a href="#CTAD">separate style rule</a>.
3365
3366<p>Do not use <code>decltype(auto)</code> if a simpler option will work,
3367 because it's a fairly obscure feature, so it has a high cost in code
3368 clarity.</p>
3369
3370<h4>Return type deduction</h4>
3371
3372<p>Use return type deduction (for both functions and lambdas) only if the
3373 function body has a very small number of <code>return</code> statements,
3374 and very little other code, because otherwise the reader may not be able
3375 to tell at a glance what the return type is. Furthermore, use it only
3376 if the function or lambda has a very narrow scope, because functions with
3377 deduced return types don't define abstraction boundaries: the implementation
3378 <em>is</em> the interface. In particular, public functions in header files
3379 should almost never have deduced return types.</p>
3380
3381<h4>Parameter type deduction</h4>
3382
3383<p><code>auto</code> parameter types for lambdas should be used with caution,
3384 because the actual type is determined by the code that calls the lambda,
3385 rather than by the definition of the lambda. Consequently, an explicit
3386 type will almost always be clearer unless the lambda is explicitly called
3387 very close to where it's defined (so that the reader can easily see both),
3388 or the lambda is passed to an interface so well-known that it's
3389 obvious what arguments it will eventually be called with (e.g.
3390 the <code>std::sort</code> example above).</p>
3391
3392<h4>Lambda init captures</h4>
3393
3394<p>Init captures are covered by a <a href="#Lambda_expressions">more specific
3395 style rule</a>, which largely supersedes the general rules for
3396 type deduction.</p>
3397
3398<h4>Structured bindings</h4>
3399
3400<p>Unlike other forms of type deduction, structured bindings can actually
3401 give the reader additional information, by giving meaningful names to the
3402 elements of a larger object. This means that a structured binding declaration
3403 may provide a net readability improvement over an explicit type, even in cases
3404 where <code>auto</code> would not. Structured bindings are especially
3405 beneficial when the object is a pair or tuple (as in the <code>insert</code>
3406 example above), because they don't have meaningful field names to begin with,
3407 but note that you generally <a href="#Structs_vs._Tuples">shouldn't use
3408 pairs or tuples</a> unless a pre-existing API like <code>insert</code>
3409 forces you to.</p>
3410
3411<p>If the object being bound is a struct, it may sometimes be helpful to
3412 provide names that are more specific to your usage, but keep in mind that
3413 this may also mean the names are less recognizable to your reader than the
3414 field names. We recommend using a comment to indicate the name of the
3415 underlying field, if it doesn't match the name of the binding, using the
3416 same syntax as for function parameter comments:
3417 </p><pre>auto [/*field_name1=*/ bound_name1, /*field_name2=*/ bound_name2] = ...</pre>
3418 As with function parameter comments, this can enable tools to detect if
3419 you get the order of the fields wrong.
3420
3421<h3 id="CTAD">Class template argument deduction</h3>
3422
3423<p>Use class template argument deduction only with templates that have
3424 explicitly opted into supporting it.</p>
3425
3426<p class="definition"></p>
3427<p><a href="https://en.cppreference.com/w/cpp/language/class_template_argument_deduction">Class
3428 template argument deduction</a> (often abbreviated "CTAD") occurs when
3429 a variable is declared with a type that names a template, and the template
3430 argument list is not provided (not even empty angle brackets):
3431 </p><pre class="neutralcode">std::array a = {1, 2, 3}; // `a` is a std::array&lt;int, 3&gt;</pre>
3432 The compiler deduces the arguments from the initializer using the
3433 template's "deduction guides", which can be explicit or implicit.
3434
3435<p>Explicit deduction guides look like function declarations with trailing
3436 return types, except that there's no leading <code>auto</code>, and the
3437 function name is the name of the template. For example, the above example
3438 relies on this deduction guide for <code>std::array</code>:
3439 </p><pre class="neutralcode">namespace std {
3440template &lt;class T, class... U&gt;
3441array(T, U...) -&gt; std::array&lt;T, 1 + sizeof...(U)&gt;;
3442}</pre>
3443 Constructors in a primary template (as opposed to a template specialization)
3444 also implicitly define deduction guides.
3445
3446<p>When you declare a variable that relies on CTAD, the compiler selects
3447 a deduction guide using the rules of constructor overload resolution,
3448 and that guide's return type becomes the type of the variable.</p>
3449
3450<p class="pros"></p>
3451<p>CTAD can sometimes allow you to omit boilerplate from your code.</p>
3452
3453<p class="cons"></p>
3454<p>The implicit deduction guides that are generated from constructors
3455 may have undesirable behavior, or be outright incorrect. This is
3456 particularly problematic for constructors written before CTAD was
3457 introduced in C++17, because the authors of those constructors had no
3458 way of knowing about (much less fixing) any problems that their
3459 constructors would cause for CTAD. Furthermore, adding explicit deduction
3460 guides to fix those problems might break any existing code that relies on
3461 the implicit deduction guides.</p>
3462
3463<p>CTAD also suffers from many of the same drawbacks as <code>auto</code>,
3464 because they are both mechanisms for deducing all or part of a variable's
3465 type from its initializer. CTAD does give the reader more information
3466 than <code>auto</code>, but it also doesn't give the reader an obvious
3467 cue that information has been omitted.</p>
3468
3469<p class="decision"></p>
3470<p>Do not use CTAD with a given template unless the template's maintainers
3471 have opted into supporting use of CTAD by providing at least one explicit
3472 deduction guide (all templates in the <code>std</code> namespace are
3473 also presumed to have opted in). This should be enforced with a compiler
3474 warning if available.</p>
3475
3476<p>Uses of CTAD must also follow the general rules on
3477 <a href="#Type_deduction">Type deduction</a>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003478
3479<h3 id="Lambda_expressions">Lambda expressions</h3>
3480
Ted Osborne505ba682018-01-30 12:36:50 -05003481<p>Use lambda expressions where appropriate. Prefer explicit captures
3482when the lambda will escape the current scope.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003483
Victor Costanf0314ea2019-09-01 20:42:44 -07003484<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003485<p> Lambda expressions are a concise way of creating anonymous
3486function objects. They're often useful when passing
3487functions as arguments. For example:</p>
3488
3489<pre>std::sort(v.begin(), v.end(), [](int x, int y) {
3490 return Weight(x) &lt; Weight(y);
3491});
3492</pre>
3493
3494<p> They further allow capturing variables from the enclosing scope either
3495explicitly by name, or implicitly using a default capture. Explicit captures
3496require each variable to be listed, as
3497either a value or reference capture:</p>
3498
3499<pre>int weight = 3;
3500int sum = 0;
3501// Captures `weight` by value and `sum` by reference.
3502std::for_each(v.begin(), v.end(), [weight, &amp;sum](int x) {
3503 sum += weight * x;
3504});
3505</pre>
3506
3507
Victor Costan967e1572019-09-05 05:09:38 -07003508<p>Default captures implicitly capture any variable referenced in the
3509lambda body, including <code>this</code> if any members are used:</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003510
3511<pre>const std::vector&lt;int&gt; lookup_table = ...;
3512std::vector&lt;int&gt; indices = ...;
3513// Captures `lookup_table` by reference, sorts `indices` by the value
3514// of the associated element in `lookup_table`.
3515std::sort(indices.begin(), indices.end(), [&amp;](int a, int b) {
3516 return lookup_table[a] &lt; lookup_table[b];
3517});
3518</pre>
3519
Victor Costan967e1572019-09-05 05:09:38 -07003520<p>A variable capture can also have an explicit initializer, which can
3521 be used for capturing move-only variables by value, or for other situations
3522 not handled by ordinary reference or value captures:
3523 </p><pre>std::unique_ptr&lt;Foo&gt; foo = ...;
3524[foo = std::move(foo)] () {
3525 ...
3526}</pre>
3527 Such captures (often called "init captures" or "generalized lambda captures")
3528 need not actually "capture" anything from the enclosing scope, or even have
3529 a name from the enclosing scope; this syntax is a fully general way to define
3530 members of a lambda object:
3531 <pre class="neutralcode">[foo = std::vector&lt;int&gt;({1, 2, 3})] () {
3532 ...
3533}</pre>
3534 The type of a capture with an initializer is deduced using the same rules
3535 as <code>auto</code>.
Ted Osborne505ba682018-01-30 12:36:50 -05003536
Victor Costanf0314ea2019-09-01 20:42:44 -07003537<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003538<ul>
3539 <li>Lambdas are much more concise than other ways of
3540 defining function objects to be passed to STL
3541 algorithms, which can be a readability
3542 improvement.</li>
3543
3544 <li>Appropriate use of default captures can remove
3545 redundancy and highlight important exceptions from
3546 the default.</li>
3547
3548 <li>Lambdas, <code>std::function</code>, and
3549 <code>std::bind</code> can be used in combination as a
3550 general purpose callback mechanism; they make it easy
3551 to write functions that take bound functions as
3552 arguments.</li>
3553</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003554
Victor Costanf0314ea2019-09-01 20:42:44 -07003555<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003556<ul>
3557 <li>Variable capture in lambdas can be a source of dangling-pointer
3558 bugs, particularly if a lambda escapes the current scope.</li>
3559
3560 <li>Default captures by value can be misleading because they do not prevent
3561 dangling-pointer bugs. Capturing a pointer by value doesn't cause a deep
3562 copy, so it often has the same lifetime issues as capture by reference.
3563 This is especially confusing when capturing 'this' by value, since the use
3564 of 'this' is often implicit.</li>
3565
Victor Costan967e1572019-09-05 05:09:38 -07003566 <li>Captures actually declare new variables (whether or not the captures have
3567 initializers), but they look nothing like any other variable declaration
3568 syntax in C++. In particular, there's no place for the variable's type,
3569 or even an <code>auto</code> placeholder (although init captures can
3570 indicate it indirectly, e.g. with a cast). This can make it difficult to
3571 even recognize them as declarations.</li>
3572
3573 <li>Init captures inherently rely on <a href="#Type_deduction">type
3574 deduction</a>, and suffer from many of the same drawbacks as
3575 <code>auto</code>, with the additional problem that the syntax doesn't
3576 even cue the reader that deduction is taking place.</li>
3577
Ted Osborne505ba682018-01-30 12:36:50 -05003578 <li>It's possible for use of lambdas to get out of
3579 hand; very long nested anonymous functions can make
3580 code harder to understand.</li>
3581
3582</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003583
Victor Costanf0314ea2019-09-01 20:42:44 -07003584<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003585<ul>
3586<li>Use lambda expressions where appropriate, with formatting as
3587described <a href="#Formatting_Lambda_Expressions">below</a>.</li>
3588<li>Prefer explicit captures if the lambda may escape the current scope.
3589For example, instead of:
3590<pre class="badcode">{
3591 Foo foo;
3592 ...
3593 executor-&gt;Schedule([&amp;] { Frobnicate(foo); })
3594 ...
3595}
3596// BAD! The fact that the lambda makes use of a reference to `foo` and
3597// possibly `this` (if `Frobnicate` is a member function) may not be
3598// apparent on a cursory inspection. If the lambda is invoked after
3599// the function returns, that would be bad, because both `foo`
3600// and the enclosing object could have been destroyed.
3601</pre>
3602prefer to write:
3603<pre>{
3604 Foo foo;
3605 ...
3606 executor-&gt;Schedule([&amp;foo] { Frobnicate(foo); })
3607 ...
3608}
3609// BETTER - The compile will fail if `Frobnicate` is a member
3610// function, and it's clearer that `foo` is dangerously captured by
3611// reference.
3612</pre>
3613</li>
3614<li>Use default capture by reference ([&amp;]) only when the
3615lifetime of the lambda is obviously shorter than any potential
3616captures.
3617</li>
3618<li>Use default capture by value ([=]) only as a means of binding a
3619few variables for a short lambda, where the set of captured
3620variables is obvious at a glance. Prefer not to write long or
3621complex lambdas with default capture by value.
3622</li>
Victor Costan967e1572019-09-05 05:09:38 -07003623<li>Use captures only to actually capture variables from the enclosing scope.
3624 Do not use captures with initializers to introduce new names, or
3625 to substantially change the meaning of an existing name. Instead,
3626 declare a new variable in the conventional way and then capture it,
3627 or avoid the lambda shorthand and define a function object explicitly.</li>
3628<li>See the section on <a href="#Type_deduction">type deduction</a>
3629 for guidance on specifying the parameter and return types.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05003630
3631</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003632
3633<h3 id="Template_metaprogramming">Template metaprogramming</h3>
Victor Costanf0314ea2019-09-01 20:42:44 -07003634
Ted Osborne505ba682018-01-30 12:36:50 -05003635<p>Avoid complicated template programming.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003636
Victor Costanf0314ea2019-09-01 20:42:44 -07003637<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003638<p>Template metaprogramming refers to a family of techniques that
3639exploit the fact that the C++ template instantiation mechanism is
3640Turing complete and can be used to perform arbitrary compile-time
3641computation in the type domain.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003642
Victor Costanf0314ea2019-09-01 20:42:44 -07003643<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003644<p>Template metaprogramming allows extremely flexible interfaces that
3645are type safe and high performance. Facilities like
3646
3647<a href="https://code.google.com/p/googletest/">Google Test</a>,
3648<code>std::tuple</code>, <code>std::function</code>, and
3649Boost.Spirit would be impossible without it.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003650
Victor Costanf0314ea2019-09-01 20:42:44 -07003651<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003652<p>The techniques used in template metaprogramming are often obscure
3653to anyone but language experts. Code that uses templates in
3654complicated ways is often unreadable, and is hard to debug or
3655maintain.</p>
3656
Victor Costanf0314ea2019-09-01 20:42:44 -07003657<p>Template metaprogramming often leads to extremely poor compile
Ted Osborne505ba682018-01-30 12:36:50 -05003658time error messages: even if an interface is simple, the complicated
3659implementation details become visible when the user does something
3660wrong.</p>
3661
3662<p>Template metaprogramming interferes with large scale refactoring by
3663making the job of refactoring tools harder. First, the template code
3664is expanded in multiple contexts, and it's hard to verify that the
3665transformation makes sense in all of them. Second, some refactoring
3666tools work with an AST that only represents the structure of the code
3667after template expansion. It can be difficult to automatically work
3668back to the original source construct that needs to be
3669rewritten.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003670
Victor Costanf0314ea2019-09-01 20:42:44 -07003671<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003672<p>Template metaprogramming sometimes allows cleaner and easier-to-use
3673interfaces than would be possible without it, but it's also often a
3674temptation to be overly clever. It's best used in a small number of
3675low level components where the extra maintenance burden is spread out
3676over a large number of uses.</p>
3677
3678<p>Think twice before using template metaprogramming or other
3679complicated template techniques; think about whether the average
3680member of your team will be able to understand your code well enough
3681to maintain it after you switch to another project, or whether a
3682non-C++ programmer or someone casually browsing the code base will be
3683able to understand the error messages or trace the flow of a function
3684they want to call. If you're using recursive template instantiations
3685or type lists or metafunctions or expression templates, or relying on
3686SFINAE or on the <code>sizeof</code> trick for detecting function
3687overload resolution, then there's a good chance you've gone too
3688far.</p>
3689
3690<p>If you use template metaprogramming, you should expect to put
3691considerable effort into minimizing and isolating the complexity. You
3692should hide metaprogramming as an implementation detail whenever
3693possible, so that user-facing headers are readable, and you should
3694make sure that tricky code is especially well commented. You should
3695carefully document how the code is used, and you should say something
3696about what the "generated" code looks like. Pay extra attention to the
3697error messages that the compiler emits when users make mistakes. The
3698error messages are part of your user interface, and your code should
3699be tweaked as necessary so that the error messages are understandable
3700and actionable from a user point of view.</p>
3701
Ted Osborne505ba682018-01-30 12:36:50 -05003702<h3 id="Boost">Boost</h3>
3703
Ted Osborne505ba682018-01-30 12:36:50 -05003704<p>Use only approved libraries from the Boost library
3705collection.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003706
Victor Costanf0314ea2019-09-01 20:42:44 -07003707<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003708<p> The
3709<a href="https://www.boost.org/">
3710Boost library collection</a> is a popular collection of
3711peer-reviewed, free, open-source C++ libraries.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003712
Victor Costanf0314ea2019-09-01 20:42:44 -07003713<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003714<p>Boost code is generally very high-quality, is widely
3715portable, and fills many important gaps in the C++
3716standard library, such as type traits and better binders.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003717
Victor Costanf0314ea2019-09-01 20:42:44 -07003718<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003719<p>Some Boost libraries encourage coding practices which can
3720hamper readability, such as metaprogramming and other
3721advanced template techniques, and an excessively
3722"functional" style of programming. </p>
Ted Osborne505ba682018-01-30 12:36:50 -05003723
Victor Costanf0314ea2019-09-01 20:42:44 -07003724<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003725
Victor Costanf0314ea2019-09-01 20:42:44 -07003726
Ted Osborne505ba682018-01-30 12:36:50 -05003727
3728<div>
3729<p>In order to maintain a high level of readability for
3730all contributors who might read and maintain code, we
3731only allow an approved subset of Boost features.
3732Currently, the following libraries are permitted:</p>
3733
3734<ul>
3735 <li>
3736 <a href="https://www.boost.org/libs/utility/call_traits.htm">
3737 Call Traits</a> from <code>boost/call_traits.hpp</code></li>
3738
3739 <li><a href="https://www.boost.org/libs/utility/compressed_pair.htm">
3740 Compressed Pair</a> from <code>boost/compressed_pair.hpp</code></li>
3741
3742 <li><a href="https://www.boost.org/libs/graph/">
3743 The Boost Graph Library (BGL)</a> from <code>boost/graph</code>,
3744 except serialization (<code>adj_list_serialize.hpp</code>) and
3745 parallel/distributed algorithms and data structures
3746 (<code>boost/graph/parallel/*</code> and
3747 <code>boost/graph/distributed/*</code>).</li>
3748
3749 <li><a href="https://www.boost.org/libs/property_map/">
3750 Property Map</a> from <code>boost/property_map</code>, except
3751 parallel/distributed property maps (<code>boost/property_map/parallel/*</code>).</li>
3752
3753 <li><a href="https://www.boost.org/libs/iterator/">
3754 Iterator</a> from <code>boost/iterator</code></li>
3755
3756 <li>The part of <a href="https://www.boost.org/libs/polygon/">
3757 Polygon</a> that deals with Voronoi diagram
3758 construction and doesn't depend on the rest of
3759 Polygon:
3760 <code>boost/polygon/voronoi_builder.hpp</code>,
3761 <code>boost/polygon/voronoi_diagram.hpp</code>, and
3762 <code>boost/polygon/voronoi_geometry_type.hpp</code></li>
3763
3764 <li><a href="https://www.boost.org/libs/bimap/">
3765 Bimap</a> from <code>boost/bimap</code></li>
3766
3767 <li><a href="https://www.boost.org/libs/math/doc/html/dist.html">
3768 Statistical Distributions and Functions</a> from
3769 <code>boost/math/distributions</code></li>
3770
3771 <li><a href="https://www.boost.org/libs/math/doc/html/special.html">
3772 Special Functions</a> from <code>boost/math/special_functions</code></li>
3773
Victor Costanf0314ea2019-09-01 20:42:44 -07003774 <li><a href="https://www.boost.org/libs/math/doc/html/root_finding.html">
3775 Root Finding Functions</a> from <code>boost/math/tools</code></li>
3776
Ted Osborne505ba682018-01-30 12:36:50 -05003777 <li><a href="https://www.boost.org/libs/multi_index/">
3778 Multi-index</a> from <code>boost/multi_index</code></li>
3779
3780 <li><a href="https://www.boost.org/libs/heap/">
3781 Heap</a> from <code>boost/heap</code></li>
3782
3783 <li>The flat containers from
3784 <a href="https://www.boost.org/libs/container/">Container</a>:
3785 <code>boost/container/flat_map</code>, and
3786 <code>boost/container/flat_set</code></li>
3787
3788 <li><a href="https://www.boost.org/libs/intrusive/">Intrusive</a>
3789 from <code>boost/intrusive</code>.</li>
3790
3791 <li><a href="https://www.boost.org/libs/sort/">The
3792 <code>boost/sort</code> library</a>.</li>
3793
3794 <li><a href="https://www.boost.org/libs/preprocessor/">Preprocessor</a>
3795 from <code>boost/preprocessor</code>.</li>
3796</ul>
3797
3798<p>We are actively considering adding other Boost
3799features to the list, so this list may be expanded in
3800the future.</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07003801</div>
Ted Osborne505ba682018-01-30 12:36:50 -05003802
Ted Osborne505ba682018-01-30 12:36:50 -05003803
Ted Osborne505ba682018-01-30 12:36:50 -05003804
3805<h3 id="std_hash">std::hash</h3>
3806
Ted Osborne505ba682018-01-30 12:36:50 -05003807<p>Do not define specializations of <code>std::hash</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003808
Victor Costanf0314ea2019-09-01 20:42:44 -07003809<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003810<p><code>std::hash&lt;T&gt;</code> is the function object that the
3811C++11 hash containers use to hash keys of type <code>T</code>,
3812unless the user explicitly specifies a different hash function. For
Victor Costanf0314ea2019-09-01 20:42:44 -07003813example, <code>std::unordered_map&lt;int, std::string&gt;</code> is a hash
Ted Osborne505ba682018-01-30 12:36:50 -05003814map that uses <code>std::hash&lt;int&gt;</code> to hash its keys,
Victor Costanf0314ea2019-09-01 20:42:44 -07003815whereas <code>std::unordered_map&lt;int, std::string, MyIntHash&gt;</code>
Ted Osborne505ba682018-01-30 12:36:50 -05003816uses <code>MyIntHash</code>.</p>
3817
3818<p><code>std::hash</code> is defined for all integral, floating-point,
3819pointer, and <code>enum</code> types, as well as some standard library
3820types such as <code>string</code> and <code>unique_ptr</code>. Users
3821can enable it to work for their own types by defining specializations
3822of it for those types.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003823
Victor Costanf0314ea2019-09-01 20:42:44 -07003824<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003825<p><code>std::hash</code> is easy to use, and simplifies the code
3826since you don't have to name it explicitly. Specializing
3827<code>std::hash</code> is the standard way of specifying how to
3828hash a type, so it's what outside resources will teach, and what
3829new engineers will expect.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003830
Victor Costanf0314ea2019-09-01 20:42:44 -07003831<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003832<p><code>std::hash</code> is hard to specialize. It requires a lot
3833of boilerplate code, and more importantly, it combines responsibility
3834for identifying the hash inputs with responsibility for executing the
3835hashing algorithm itself. The type author has to be responsible for
3836the former, but the latter requires expertise that a type author
3837usually doesn't have, and shouldn't need. The stakes here are high
3838because low-quality hash functions can be security vulnerabilities,
3839due to the emergence of
3840<a href="https://emboss.github.io/blog/2012/12/14/breaking-murmur-hash-flooding-dos-reloaded/">
3841hash flooding attacks</a>.</p>
3842
3843<p>Even for experts, <code>std::hash</code> specializations are
3844inordinately difficult to implement correctly for compound types,
3845because the implementation cannot recursively call <code>std::hash</code>
3846on data members. High-quality hash algorithms maintain large
3847amounts of internal state, and reducing that state to the
3848<code>size_t</code> bytes that <code>std::hash</code>
3849returns is usually the slowest part of the computation, so it
3850should not be done more than once.</p>
3851
3852<p>Due to exactly that issue, <code>std::hash</code> does not work
3853with <code>std::pair</code> or <code>std::tuple</code>, and the
3854language does not allow us to extend it to support them.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003855
Victor Costanf0314ea2019-09-01 20:42:44 -07003856<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003857<p>You can use <code>std::hash</code> with the types that it supports
3858"out of the box", but do not specialize it to support additional types.
3859If you need a hash table with a key type that <code>std::hash</code>
3860does not support, consider using legacy hash containers (e.g.
3861<code>hash_map</code>) for now; they use a different default hasher,
3862which is unaffected by this prohibition.</p>
3863
3864<p>If you want to use the standard hash containers anyway, you will
3865need to specify a custom hasher for the key type, e.g.</p>
3866<pre>std::unordered_map&lt;MyKeyType, Value, MyKeyTypeHasher&gt; my_map;
3867</pre><p>
3868Consult with the type's owners to see if there is an existing hasher
3869that you can use; otherwise work with them to provide one,
3870 or roll your own.</p>
3871
3872<p>We are planning to provide a hash function that can work with any type,
3873using a new customization mechanism that doesn't have the drawbacks of
3874<code>std::hash</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003875
Ted Osborne505ba682018-01-30 12:36:50 -05003876
Ted Osborne505ba682018-01-30 12:36:50 -05003877
Victor Costan967e1572019-09-05 05:09:38 -07003878<h3 id="Other_Features"><a name="C++11">Other C++ Features</a></h3>
Ted Osborne505ba682018-01-30 12:36:50 -05003879
Victor Costan967e1572019-09-05 05:09:38 -07003880<p>As with <a href="#Boost">Boost</a>, some modern C++
Ted Osborne505ba682018-01-30 12:36:50 -05003881extensions encourage coding practices that hamper
3882readability&#8212;for example by removing
3883checked redundancy (such as type names) that may be
3884helpful to readers, or by encouraging template
3885metaprogramming. Other extensions duplicate functionality
3886available through existing mechanisms, which may lead to confusion
3887and conversion costs.</p>
3888
Victor Costanf0314ea2019-09-01 20:42:44 -07003889<p class="decision"></p>
Victor Costan967e1572019-09-05 05:09:38 -07003890<p>In addition to what's described in the rest of the style
3891guide, the following C++ features may not be used:</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003892
3893<ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003894
Ted Osborne505ba682018-01-30 12:36:50 -05003895
3896 <li>Compile-time rational numbers
3897 (<code>&lt;ratio&gt;</code>), because of concerns that
3898 it's tied to a more template-heavy interface
3899 style.</li>
3900
3901 <li>The <code>&lt;cfenv&gt;</code> and
3902 <code>&lt;fenv.h&gt;</code> headers, because many
3903 compilers do not support those features reliably.</li>
3904
Victor Costan967e1572019-09-05 05:09:38 -07003905 <li>The <code>&lt;filesystem&gt;</code> header, which
3906
3907 does not have sufficient support for testing, and suffers
3908 from inherent security vulnerabilities.</li>
3909
Ted Osborne505ba682018-01-30 12:36:50 -05003910
Ted Osborne505ba682018-01-30 12:36:50 -05003911</ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003912
3913<h3 id="Nonstandard_Extensions">Nonstandard Extensions</h3>
3914
Ted Osborne505ba682018-01-30 12:36:50 -05003915<p>Nonstandard extensions to C++ may not be used unless otherwise specified.</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07003916
3917<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003918<p>Compilers support various extensions that are not part of standard C++. Such
3919 extensions include GCC's <code>__attribute__</code>, intrinsic functions such
3920 as <code>__builtin_prefetch</code>, designated initializers (e.g.
3921 <code>Foo f = {.field = 3}</code>), inline assembly, <code>__COUNTER__</code>,
3922 <code>__PRETTY_FUNCTION__</code>, compound statement expressions (e.g.
3923 <code>foo = ({ int x; Bar(&amp;x); x })</code>, variable-length arrays and
Victor Costan6dfd9d92018-02-05 18:30:35 -08003924 <code>alloca()</code>, and the "<a href="https://en.wikipedia.org/wiki/Elvis_operator">Elvis Operator</a>"
3925 <code>a?:b</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003926
Victor Costanf0314ea2019-09-01 20:42:44 -07003927<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003928 <ul>
3929 <li>Nonstandard extensions may provide useful features that do not exist
3930 in standard C++. For example, some people think that designated
3931 initializers are more readable than standard C++ features like
3932 constructors.</li>
3933 <li>Important performance guidance to the compiler can only be specified
3934 using extensions.</li>
3935 </ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003936
Victor Costanf0314ea2019-09-01 20:42:44 -07003937<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003938 <ul>
3939 <li>Nonstandard extensions do not work in all compilers. Use of nonstandard
3940 extensions reduces portability of code.</li>
3941 <li>Even if they are supported in all targeted compilers, the extensions
3942 are often not well-specified, and there may be subtle behavior differences
3943 between compilers.</li>
3944 <li>Nonstandard extensions add to the language features that a reader must
3945 know to understand the code.</li>
3946 </ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003947
Victor Costanf0314ea2019-09-01 20:42:44 -07003948<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003949<p>Do not use nonstandard extensions. You may use portability wrappers that
3950 are implemented using nonstandard extensions, so long as those wrappers
Victor Costanf0314ea2019-09-01 20:42:44 -07003951
Ted Osborne505ba682018-01-30 12:36:50 -05003952 are provided by a designated project-wide
3953 portability header.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003954
3955<h3 id="Aliases">Aliases</h3>
3956
Ted Osborne505ba682018-01-30 12:36:50 -05003957<p>Public aliases are for the benefit of an API's user, and should be clearly documented.</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07003958
3959<p class="definition"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003960<p>There are several ways to create names that are aliases of other entities:</p>
3961<pre>typedef Foo Bar;
3962using Bar = Foo;
3963using other_namespace::Foo;
3964</pre>
3965
Victor Costan6dfd9d92018-02-05 18:30:35 -08003966 <p>In new code, <code>using</code> is preferable to <code>typedef</code>,
3967 because it provides a more consistent syntax with the rest of C++ and works
3968 with templates.</p>
3969
Ted Osborne505ba682018-01-30 12:36:50 -05003970 <p>Like other declarations, aliases declared in a header file are part of that
3971 header's public API unless they're in a function definition, in the private portion of a class,
3972 or in an explicitly-marked internal namespace. Aliases in such areas or in .cc files are
3973 implementation details (because client code can't refer to them), and are not restricted by this
3974 rule.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05003975
Victor Costanf0314ea2019-09-01 20:42:44 -07003976<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003977 <ul>
3978 <li>Aliases can improve readability by simplifying a long or complicated name.</li>
3979 <li>Aliases can reduce duplication by naming in one place a type used repeatedly in an API,
3980 which <em>might</em> make it easier to change the type later.
3981 </li>
3982 </ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003983
Victor Costanf0314ea2019-09-01 20:42:44 -07003984<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05003985 <ul>
3986 <li>When placed in a header where client code can refer to them, aliases increase the
3987 number of entities in that header's API, increasing its complexity.</li>
3988 <li>Clients can easily rely on unintended details of public aliases, making
3989 changes difficult.</li>
3990 <li>It can be tempting to create a public alias that is only intended for use
3991 in the implementation, without considering its impact on the API, or on maintainability.</li>
3992 <li>Aliases can create risk of name collisions</li>
3993 <li>Aliases can reduce readability by giving a familiar construct an unfamiliar name</li>
3994 <li>Type aliases can create an unclear API contract:
3995 it is unclear whether the alias is guaranteed to be identical to the type it aliases,
3996 to have the same API, or only to be usable in specified narrow ways</li>
3997 </ul>
Ted Osborne505ba682018-01-30 12:36:50 -05003998
Victor Costanf0314ea2019-09-01 20:42:44 -07003999<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05004000<p>Don't put an alias in your public API just to save typing in the implementation;
4001 do so only if you intend it to be used by your clients.</p>
4002<p>When defining a public alias, document the intent of
4003the new name, including whether it is guaranteed to always be the same as the type
4004it's currently aliased to, or whether a more limited compatibility is
4005intended. This lets the user know whether they can treat the types as
4006substitutable or whether more specific rules must be followed, and can help the
4007implementation retain some degree of freedom to change the alias.</p>
4008<p>Don't put namespace aliases in your public API. (See also <a href="#Namespaces">Namespaces</a>).
4009</p>
4010
4011<p>For example, these aliases document how they are intended to be used in client code:</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08004012<pre>namespace mynamespace {
Ted Osborne505ba682018-01-30 12:36:50 -05004013// Used to store field measurements. DataPoint may change from Bar* to some internal type.
4014// Client code should treat it as an opaque pointer.
Victor Costan6dfd9d92018-02-05 18:30:35 -08004015using DataPoint = foo::Bar*;
Ted Osborne505ba682018-01-30 12:36:50 -05004016
4017// A set of measurements. Just an alias for user convenience.
4018using TimeSeries = std::unordered_set&lt;DataPoint, std::hash&lt;DataPoint&gt;, DataPointComparator&gt;;
Victor Costan6dfd9d92018-02-05 18:30:35 -08004019} // namespace mynamespace
Ted Osborne505ba682018-01-30 12:36:50 -05004020</pre>
4021
4022<p>These aliases don't document intended use, and half of them aren't meant for client use:</p>
4023
Victor Costan6dfd9d92018-02-05 18:30:35 -08004024<pre class="badcode">namespace mynamespace {
Ted Osborne505ba682018-01-30 12:36:50 -05004025// Bad: none of these say how they should be used.
Victor Costan6dfd9d92018-02-05 18:30:35 -08004026using DataPoint = foo::Bar*;
Ted Osborne505ba682018-01-30 12:36:50 -05004027using std::unordered_set; // Bad: just for local convenience
4028using std::hash; // Bad: just for local convenience
4029typedef unordered_set&lt;DataPoint, hash&lt;DataPoint&gt;, DataPointComparator&gt; TimeSeries;
Victor Costan6dfd9d92018-02-05 18:30:35 -08004030} // namespace mynamespace
Ted Osborne505ba682018-01-30 12:36:50 -05004031</pre>
4032
4033<p>However, local convenience aliases are fine in function definitions, private sections of
4034 classes, explicitly marked internal namespaces, and in .cc files:</p>
4035
4036<pre>// In a .cc file
Victor Costan6dfd9d92018-02-05 18:30:35 -08004037using foo::Bar;
Ted Osborne505ba682018-01-30 12:36:50 -05004038</pre>
4039
Ted Osborne505ba682018-01-30 12:36:50 -05004040<h2 id="Naming">Naming</h2>
4041
4042<p>The most important consistency rules are those that govern
4043naming. The style of a name immediately informs us what sort of
4044thing the named entity is: a type, a variable, a function, a
4045constant, a macro, etc., without requiring us to search for the
4046declaration of that entity. The pattern-matching engine in our
4047brains relies a great deal on these naming rules.
4048</p>
4049
4050<p>Naming rules are pretty arbitrary, but
4051 we feel that
4052consistency is more important than individual preferences in this
4053area, so regardless of whether you find them sensible or not,
4054the rules are the rules.</p>
4055
4056<h3 id="General_Naming_Rules">General Naming Rules</h3>
4057
Victor Costanf0314ea2019-09-01 20:42:44 -07004058<p>Optimize for readability using names that would be clear
4059even to people on a different team.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004060
Victor Costanf0314ea2019-09-01 20:42:44 -07004061<p>Use names that describe the purpose or intent of the object.
Ted Osborne505ba682018-01-30 12:36:50 -05004062Do not worry about saving horizontal space as it is far
4063more important to make your code immediately
Victor Costanf0314ea2019-09-01 20:42:44 -07004064understandable by a new reader. Minimize the use of
4065abbreviations that would likely be unknown to someone outside
4066your project (especially acronyms and initialisms). Do not
4067abbreviate by deleting letters within a word. As a rule of thumb,
4068an abbreviation is probably OK if it's listed in
4069 Wikipedia. Generally speaking, descriptiveness should be
4070proportional to the name's scope of visibility. For example,
4071<code>n</code> may be a fine name within a 5-line function,
4072but within the scope of a class, it's likely too vague.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08004073
Victor Costanf0314ea2019-09-01 20:42:44 -07004074<pre>class MyClass {
4075 public:
4076 int CountFooErrors(const std::vector&lt;Foo&gt;&amp; foos) {
4077 int n = 0; // Clear meaning given limited scope and context
4078 for (const auto&amp; foo : foos) {
4079 ...
4080 ++n;
4081 }
4082 return n;
4083 }
4084 void DoSomethingImportant() {
4085 std::string fqdn = ...; // Well-known abbreviation for Fully Qualified Domain Name
4086 }
4087 private:
4088 const int kMaxAllowedConnections = ...; // Clear meaning within context
4089};
Ted Osborne505ba682018-01-30 12:36:50 -05004090</pre>
4091
Victor Costanf0314ea2019-09-01 20:42:44 -07004092<pre class="badcode">class MyClass {
4093 public:
4094 int CountFooErrors(const std::vector&lt;Foo&gt;&amp; foos) {
4095 int total_number_of_foo_errors = 0; // Overly verbose given limited scope and context
4096 for (int foo_index = 0; foo_index &lt; foos.size(); ++foo_index) { // Use idiomatic `i`
4097 ...
4098 ++total_number_of_foo_errors;
4099 }
4100 return total_number_of_foo_errors;
4101 }
4102 void DoSomethingImportant() {
4103 int cstmr_id = ...; // Deletes internal letters
4104 }
4105 private:
4106 const int kNum = ...; // Unclear meaning within broad scope
4107};
Ted Osborne505ba682018-01-30 12:36:50 -05004108</pre>
4109
4110<p>Note that certain universally-known abbreviations are OK, such as
4111<code>i</code> for an iteration variable and <code>T</code> for a
4112template parameter.</p>
4113
Victor Costanf0314ea2019-09-01 20:42:44 -07004114<p>For the purposes of the naming rules below, a "word" is anything that you
4115would write in English without internal spaces. This includes abbreviations and
4116acronyms; e.g., for "<a href="https://en.wikipedia.org/wiki/Camel_case">camel
4117case</a>" or "Pascal case," in which the first letter of each word is
4118capitalized, use a name like <code>StartRpc()</code>, not
4119<code>StartRPC()</code>.</p>
Victor Costan6dfd9d92018-02-05 18:30:35 -08004120
Ted Osborne505ba682018-01-30 12:36:50 -05004121<p>Template parameters should follow the naming style for their
4122category: type template parameters should follow the rules for
4123<a href="#Type_Names">type names</a>, and non-type template
4124parameters should follow the rules for <a href="#Variable_Names">
4125variable names</a>.
4126
Victor Costanf0314ea2019-09-01 20:42:44 -07004127</p><h3 id="File_Names">File Names</h3>
Ted Osborne505ba682018-01-30 12:36:50 -05004128
Ted Osborne505ba682018-01-30 12:36:50 -05004129<p>Filenames should be all lowercase and can include
4130underscores (<code>_</code>) or dashes (<code>-</code>).
4131Follow the convention that your
Victor Costanf0314ea2019-09-01 20:42:44 -07004132
Ted Osborne505ba682018-01-30 12:36:50 -05004133project uses. If there is no consistent
4134local pattern to follow, prefer "_".</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004135
4136<p>Examples of acceptable file names:</p>
4137
4138<ul>
4139 <li><code>my_useful_class.cc</code></li>
4140 <li><code>my-useful-class.cc</code></li>
4141 <li><code>myusefulclass.cc</code></li>
4142 <li><code>myusefulclass_test.cc // _unittest and _regtest are deprecated.</code></li>
4143</ul>
4144
4145<p>C++ files should end in <code>.cc</code> and header files should end in
4146<code>.h</code>. Files that rely on being textually included at specific points
4147should end in <code>.inc</code> (see also the section on
4148<a href="#Self_contained_Headers">self-contained headers</a>).</p>
4149
4150<p>Do not use filenames that already exist in
4151<code>/usr/include</code>, such as <code>db.h</code>.</p>
4152
4153<p>In general, make your filenames very specific. For
4154example, use <code>http_server_logs.h</code> rather than
4155<code>logs.h</code>. A very common case is to have a pair
4156of files called, e.g., <code>foo_bar.h</code> and
4157<code>foo_bar.cc</code>, defining a class called
4158<code>FooBar</code>.</p>
4159
Ted Osborne505ba682018-01-30 12:36:50 -05004160<h3 id="Type_Names">Type Names</h3>
4161
Ted Osborne505ba682018-01-30 12:36:50 -05004162<p>Type names start with a capital letter and have a capital
4163letter for each new word, with no underscores:
4164<code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004165
4166<p>The names of all types &#8212; classes, structs, type aliases,
4167enums, and type template parameters &#8212; have the same naming convention.
4168Type names should start with a capital letter and have a capital letter
4169for each new word. No underscores. For example:</p>
4170
4171<pre>// classes and structs
4172class UrlTable { ...
4173class UrlTableTester { ...
4174struct UrlTableProperties { ...
4175
4176// typedefs
Victor Costanf0314ea2019-09-01 20:42:44 -07004177typedef hash_map&lt;UrlTableProperties *, std::string&gt; PropertiesMap;
Ted Osborne505ba682018-01-30 12:36:50 -05004178
4179// using aliases
Victor Costanf0314ea2019-09-01 20:42:44 -07004180using PropertiesMap = hash_map&lt;UrlTableProperties *, std::string&gt;;
Ted Osborne505ba682018-01-30 12:36:50 -05004181
4182// enums
4183enum UrlTableErrors { ...
4184</pre>
4185
Ted Osborne505ba682018-01-30 12:36:50 -05004186<h3 id="Variable_Names">Variable Names</h3>
4187
Ted Osborne505ba682018-01-30 12:36:50 -05004188<p>The names of variables (including function parameters) and data members are
4189all lowercase, with underscores between words. Data members of classes (but not
4190structs) additionally have trailing underscores. For instance:
4191<code>a_local_variable</code>, <code>a_struct_data_member</code>,
4192<code>a_class_data_member_</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004193
Victor Costanf0314ea2019-09-01 20:42:44 -07004194<h4>Common Variable names</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004195
4196<p>For example:</p>
4197
Victor Costanf0314ea2019-09-01 20:42:44 -07004198<pre>std::string table_name; // OK - lowercase with underscore.
Ted Osborne505ba682018-01-30 12:36:50 -05004199</pre>
4200
Victor Costanf0314ea2019-09-01 20:42:44 -07004201<pre class="badcode">std::string tableName; // Bad - mixed case.
Ted Osborne505ba682018-01-30 12:36:50 -05004202</pre>
4203
Victor Costanf0314ea2019-09-01 20:42:44 -07004204<h4>Class Data Members</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004205
4206<p>Data members of classes, both static and non-static, are
4207named like ordinary nonmember variables, but with a
4208trailing underscore.</p>
4209
4210<pre>class TableInfo {
4211 ...
4212 private:
Victor Costanf0314ea2019-09-01 20:42:44 -07004213 std::string table_name_; // OK - underscore at end.
Ted Osborne505ba682018-01-30 12:36:50 -05004214 static Pool&lt;TableInfo&gt;* pool_; // OK.
4215};
4216</pre>
4217
Victor Costanf0314ea2019-09-01 20:42:44 -07004218<h4>Struct Data Members</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004219
4220<p>Data members of structs, both static and non-static,
4221are named like ordinary nonmember variables. They do not have
4222the trailing underscores that data members in classes have.</p>
4223
4224<pre>struct UrlTableProperties {
Victor Costanf0314ea2019-09-01 20:42:44 -07004225 std::string name;
Ted Osborne505ba682018-01-30 12:36:50 -05004226 int num_entries;
4227 static Pool&lt;UrlTableProperties&gt;* pool;
4228};
4229</pre>
4230
4231
4232<p>See <a href="#Structs_vs._Classes">Structs vs.
4233Classes</a> for a discussion of when to use a struct
4234versus a class.</p>
4235
Ted Osborne505ba682018-01-30 12:36:50 -05004236<h3 id="Constant_Names">Constant Names</h3>
4237
Victor Costanf0314ea2019-09-01 20:42:44 -07004238<p>Variables declared constexpr or const, and whose value is fixed for
4239the duration of the program, are named with a leading "k" followed
4240by mixed case. Underscores can be used as separators in the rare cases
4241where capitalization cannot be used for separation. For example:</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004242
4243<pre>const int kDaysInAWeek = 7;
Victor Costanb89a7752018-07-31 10:17:48 -07004244const int kAndroid8_0_0 = 24; // Android 8.0.0
Ted Osborne505ba682018-01-30 12:36:50 -05004245</pre>
4246
Victor Costanf0314ea2019-09-01 20:42:44 -07004247<p>All such variables with static storage duration (i.e. statics and globals,
4248see <a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration">
4249Storage Duration</a> for details) should be named this way. This
4250convention is optional for variables of other storage classes, e.g. automatic
4251variables, otherwise the usual variable naming rules apply.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004252
4253<h3 id="Function_Names">Function Names</h3>
4254
Ted Osborne505ba682018-01-30 12:36:50 -05004255<p>Regular functions have mixed case; accessors and mutators may be named
4256like variables.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004257
4258<p>Ordinarily, functions should start with a capital letter and have a
Victor Costan6dfd9d92018-02-05 18:30:35 -08004259capital letter for each new word.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004260
4261<pre>AddTableEntry()
4262DeleteUrl()
4263OpenFileOrDie()
4264</pre>
4265
4266<p>(The same naming rule applies to class- and namespace-scope
4267constants that are exposed as part of an API and that are intended to look
Victor Costan6dfd9d92018-02-05 18:30:35 -08004268like functions, because the fact that they're objects rather than functions
4269is an unimportant implementation detail.)</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004270
4271<p>Accessors and mutators (get and set functions) may be named like
4272variables. These often correspond to actual member variables, but this is
4273not required. For example, <code>int count()</code> and <code>void
4274set_count(int count)</code>.</p>
4275
Ted Osborne505ba682018-01-30 12:36:50 -05004276<h3 id="Namespace_Names">Namespace Names</h3>
4277
Ted Osborne505ba682018-01-30 12:36:50 -05004278Namespace names are all lower-case. Top-level namespace names are
4279based on the project name
4280. Avoid collisions
4281between nested namespaces and well-known top-level namespaces.
Ted Osborne505ba682018-01-30 12:36:50 -05004282
Ted Osborne505ba682018-01-30 12:36:50 -05004283<p>The name of a top-level namespace should usually be the
4284name of the project or team whose code is contained in that
4285namespace. The code in that namespace should usually be in
Victor Costan6dfd9d92018-02-05 18:30:35 -08004286a directory whose basename matches the namespace name (or in
Ted Osborne505ba682018-01-30 12:36:50 -05004287subdirectories thereof).</p>
4288
4289
4290
Ted Osborne505ba682018-01-30 12:36:50 -05004291<p>Keep in mind that the <a href="#General_Naming_Rules">rule
4292against abbreviated names</a> applies to namespaces just as much
4293as variable names. Code inside the namespace seldom needs to
4294mention the namespace name, so there's usually no particular need
4295for abbreviation anyway.</p>
4296
4297<p>Avoid nested namespaces that match well-known top-level
4298namespaces. Collisions between namespace names can lead to surprising
4299build breaks because of name lookup rules. In particular, do not
4300create any nested <code>std</code> namespaces. Prefer unique project
4301identifiers
4302(<code>websearch::index</code>, <code>websearch::index_util</code>)
4303over collision-prone names like <code>websearch::util</code>.</p>
4304
4305<p>For <code>internal</code> namespaces, be wary of other code being
4306added to the same <code>internal</code> namespace causing a collision
4307(internal helpers within a team tend to be related and may lead to
4308collisions). In such a situation, using the filename to make a unique
4309internal name is helpful
4310(<code>websearch::index::frobber_internal</code> for use
4311in <code>frobber.h</code>)</p>
4312
Ted Osborne505ba682018-01-30 12:36:50 -05004313<h3 id="Enumerator_Names">Enumerator Names</h3>
4314
Ted Osborne505ba682018-01-30 12:36:50 -05004315<p>Enumerators (for both scoped and unscoped enums) should be named <i>either</i> like
4316<a href="#Constant_Names">constants</a> or like
4317<a href="#Macro_Names">macros</a>: either <code>kEnumName</code> or
4318<code>ENUM_NAME</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004319
4320<p>Preferably, the individual enumerators should be named
4321like <a href="#Constant_Names">constants</a>. However, it
4322is also acceptable to name them like
4323<a href="#Macro_Names">macros</a>. The enumeration name,
4324<code>UrlTableErrors</code> (and
4325<code>AlternateUrlTableErrors</code>), is a type, and
4326therefore mixed case.</p>
4327
4328<pre>enum UrlTableErrors {
Victor Costanf0314ea2019-09-01 20:42:44 -07004329 kOk = 0,
Ted Osborne505ba682018-01-30 12:36:50 -05004330 kErrorOutOfMemory,
4331 kErrorMalformedInput,
4332};
4333enum AlternateUrlTableErrors {
4334 OK = 0,
4335 OUT_OF_MEMORY = 1,
4336 MALFORMED_INPUT = 2,
4337};
4338</pre>
4339
4340<p>Until January 2009, the style was to name enum values
4341like <a href="#Macro_Names">macros</a>. This caused
4342problems with name collisions between enum values and
4343macros. Hence, the change to prefer constant-style naming
4344was put in place. New code should prefer constant-style
4345naming if possible. However, there is no reason to change
4346old code to use constant-style names, unless the old
4347names are actually causing a compile-time problem.</p>
4348
4349
4350
Ted Osborne505ba682018-01-30 12:36:50 -05004351<h3 id="Macro_Names">Macro Names</h3>
4352
Ted Osborne505ba682018-01-30 12:36:50 -05004353<p>You're not really going to <a href="#Preprocessor_Macros">
4354define a macro</a>, are you? If you do, they're like this:
Victor Costan6dfd9d92018-02-05 18:30:35 -08004355<code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN_AND_ADULTS_ALIKE</code>.
4356</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004357
4358<p>Please see the <a href="#Preprocessor_Macros">description
4359of macros</a>; in general macros should <em>not</em> be used.
4360However, if they are absolutely needed, then they should be
4361named with all capitals and underscores.</p>
4362
4363<pre>#define ROUND(x) ...
4364#define PI_ROUNDED 3.0
4365</pre>
4366
Ted Osborne505ba682018-01-30 12:36:50 -05004367<h3 id="Exceptions_to_Naming_Rules">Exceptions to Naming Rules</h3>
4368
Ted Osborne505ba682018-01-30 12:36:50 -05004369<p>If you are naming something that is analogous to an
4370existing C or C++ entity then you can follow the existing
4371naming convention scheme.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004372
4373<dl>
4374 <dt><code>bigopen()</code></dt>
4375 <dd>function name, follows form of <code>open()</code></dd>
4376
4377 <dt><code>uint</code></dt>
4378 <dd><code>typedef</code></dd>
4379
4380 <dt><code>bigpos</code></dt>
4381 <dd><code>struct</code> or <code>class</code>, follows
4382 form of <code>pos</code></dd>
4383
4384 <dt><code>sparse_hash_map</code></dt>
4385 <dd>STL-like entity; follows STL naming conventions</dd>
4386
4387 <dt><code>LONGLONG_MAX</code></dt>
4388 <dd>a constant, as in <code>INT_MAX</code></dd>
4389</dl>
4390
Ted Osborne505ba682018-01-30 12:36:50 -05004391<h2 id="Comments">Comments</h2>
4392
Victor Costanf0314ea2019-09-01 20:42:44 -07004393<p>Comments are absolutely vital to keeping our code readable. The following rules describe what you
4394should comment and where. But remember: while comments are very important, the best code is
4395self-documenting. Giving sensible names to types and variables is much better than using obscure
4396names that you must then explain through comments.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004397
4398<p>When writing your comments, write for your audience: the
Victor Costanf0314ea2019-09-01 20:42:44 -07004399next
Ted Osborne505ba682018-01-30 12:36:50 -05004400contributor who will need to
4401understand your code. Be generous &#8212; the next
4402one may be you!</p>
4403
4404<h3 id="Comment_Style">Comment Style</h3>
4405
Ted Osborne505ba682018-01-30 12:36:50 -05004406<p>Use either the <code>//</code> or <code>/* */</code>
4407syntax, as long as you are consistent.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004408
4409<p>You can use either the <code>//</code> or the <code>/*
4410*/</code> syntax; however, <code>//</code> is
4411<em>much</em> more common. Be consistent with how you
4412comment and what style you use where.</p>
4413
Ted Osborne505ba682018-01-30 12:36:50 -05004414<h3 id="File_Comments">File Comments</h3>
4415
Victor Costanf0314ea2019-09-01 20:42:44 -07004416<div>
Ted Osborne505ba682018-01-30 12:36:50 -05004417<p>Start each file with license boilerplate.</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07004418</div>
Ted Osborne505ba682018-01-30 12:36:50 -05004419
4420<p>File comments describe the contents of a file. If a file declares,
4421implements, or tests exactly one abstraction that is documented by a comment
4422at the point of declaration, file comments are not required. All other files
4423must have file comments.</p>
4424
Victor Costanf0314ea2019-09-01 20:42:44 -07004425<h4>Legal Notice and Author
Ted Osborne505ba682018-01-30 12:36:50 -05004426Line</h4>
4427
4428
4429
Victor Costanf0314ea2019-09-01 20:42:44 -07004430<div>
Ted Osborne505ba682018-01-30 12:36:50 -05004431<p>Every file should contain license
4432boilerplate. Choose the appropriate boilerplate for the
4433license used by the project (for example, Apache 2.0,
4434BSD, LGPL, GPL).</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07004435</div>
Ted Osborne505ba682018-01-30 12:36:50 -05004436
4437<p>If you make significant changes to a file with an
Victor Costan6dfd9d92018-02-05 18:30:35 -08004438author line, consider deleting the author line.
4439New files should usually not contain copyright notice or
4440author line.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004441
Victor Costanf0314ea2019-09-01 20:42:44 -07004442<h4>File Contents</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004443
4444<p>If a <code>.h</code> declares multiple abstractions, the file-level comment
4445should broadly describe the contents of the file, and how the abstractions are
4446related. A 1 or 2 sentence file-level comment may be sufficient. The detailed
4447documentation about individual abstractions belongs with those abstractions,
4448not at the file level.</p>
4449
4450<p>Do not duplicate comments in both the <code>.h</code> and the
4451<code>.cc</code>. Duplicated comments diverge.</p>
4452
Ted Osborne505ba682018-01-30 12:36:50 -05004453<h3 id="Class_Comments">Class Comments</h3>
4454
Ted Osborne505ba682018-01-30 12:36:50 -05004455<p>Every non-obvious class declaration should have an accompanying
4456comment that describes what it is for and how it should be used.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004457
4458<pre>// Iterates over the contents of a GargantuanTable.
4459// Example:
4460// GargantuanTableIterator* iter = table-&gt;NewIterator();
4461// for (iter-&gt;Seek("foo"); !iter-&gt;done(); iter-&gt;Next()) {
4462// process(iter-&gt;key(), iter-&gt;value());
4463// }
4464// delete iter;
4465class GargantuanTableIterator {
4466 ...
4467};
4468</pre>
4469
4470<p>The class comment should provide the reader with enough information to know
4471how and when to use the class, as well as any additional considerations
4472necessary to correctly use the class. Document the synchronization assumptions
4473the class makes, if any. If an instance of the class can be accessed by
4474multiple threads, take extra care to document the rules and invariants
4475surrounding multithreaded use.</p>
4476
4477<p>The class comment is often a good place for a small example code snippet
4478demonstrating a simple and focused usage of the class.</p>
4479
4480<p>When sufficiently separated (e.g. <code>.h</code> and <code>.cc</code>
4481files), comments describing the use of the class should go together with its
4482interface definition; comments about the class operation and implementation
4483should accompany the implementation of the class's methods.</p>
4484
Ted Osborne505ba682018-01-30 12:36:50 -05004485<h3 id="Function_Comments">Function Comments</h3>
4486
Ted Osborne505ba682018-01-30 12:36:50 -05004487<p>Declaration comments describe use of the function (when it is
4488non-obvious); comments at the definition of a function describe
4489operation.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004490
Victor Costanf0314ea2019-09-01 20:42:44 -07004491<h4>Function Declarations</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004492
4493<p>Almost every function declaration should have comments immediately
4494preceding it that describe what the function does and how to use
4495it. These comments may be omitted only if the function is simple and
4496obvious (e.g. simple accessors for obvious properties of the
Victor Costanf0314ea2019-09-01 20:42:44 -07004497class). These comments should open with descriptive verbs in the
4498indicative mood ("Opens the file") rather than verbs in the imperative
4499("Open the file"). The comment describes the function; it does not
4500tell the function what to do. In general, these comments do not
4501describe how the function performs its task. Instead, that should be
4502left to comments in the function definition.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004503
4504<p>Types of things to mention in comments at the function
4505declaration:</p>
4506
4507<ul>
4508 <li>What the inputs and outputs are.</li>
4509
4510 <li>For class member functions: whether the object
4511 remembers reference arguments beyond the duration of
4512 the method call, and whether it will free them or
4513 not.</li>
4514
4515 <li>If the function allocates memory that the caller
4516 must free.</li>
4517
4518 <li>Whether any of the arguments can be a null
4519 pointer.</li>
4520
4521 <li>If there are any performance implications of how a
4522 function is used.</li>
4523
4524 <li>If the function is re-entrant. What are its
4525 synchronization assumptions?</li>
4526 </ul>
4527
4528<p>Here is an example:</p>
4529
4530<pre>// Returns an iterator for this table. It is the client's
4531// responsibility to delete the iterator when it is done with it,
4532// and it must not use the iterator once the GargantuanTable object
4533// on which the iterator was created has been deleted.
4534//
4535// The iterator is initially positioned at the beginning of the table.
4536//
4537// This method is equivalent to:
4538// Iterator* iter = table-&gt;NewIterator();
4539// iter-&gt;Seek("");
4540// return iter;
4541// If you are going to immediately seek to another place in the
4542// returned iterator, it will be faster to use NewIterator()
4543// and avoid the extra seek.
4544Iterator* GetIterator() const;
4545</pre>
4546
4547<p>However, do not be unnecessarily verbose or state the
Victor Costan6dfd9d92018-02-05 18:30:35 -08004548completely obvious.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004549
4550<p>When documenting function overrides, focus on the
4551specifics of the override itself, rather than repeating
4552the comment from the overridden function. In many of these
4553cases, the override needs no additional documentation and
4554thus no comment is required.</p>
4555
4556<p>When commenting constructors and destructors, remember
4557that the person reading your code knows what constructors
4558and destructors are for, so comments that just say
4559something like "destroys this object" are not useful.
4560Document what constructors do with their arguments (for
4561example, if they take ownership of pointers), and what
4562cleanup the destructor does. If this is trivial, just
4563skip the comment. It is quite common for destructors not
4564to have a header comment.</p>
4565
Victor Costanf0314ea2019-09-01 20:42:44 -07004566<h4>Function Definitions</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004567
4568<p>If there is anything tricky about how a function does
4569its job, the function definition should have an
4570explanatory comment. For example, in the definition
4571comment you might describe any coding tricks you use,
4572give an overview of the steps you go through, or explain
4573why you chose to implement the function in the way you
4574did rather than using a viable alternative. For instance,
4575you might mention why it must acquire a lock for the
4576first half of the function but why it is not needed for
4577the second half.</p>
4578
4579<p>Note you should <em>not</em> just repeat the comments
4580given with the function declaration, in the
4581<code>.h</code> file or wherever. It's okay to
4582recapitulate briefly what the function does, but the
4583focus of the comments should be on how it does it.</p>
4584
Ted Osborne505ba682018-01-30 12:36:50 -05004585<h3 id="Variable_Comments">Variable Comments</h3>
4586
Ted Osborne505ba682018-01-30 12:36:50 -05004587<p>In general the actual name of the variable should be
4588descriptive enough to give a good idea of what the variable
4589is used for. In certain cases, more comments are required.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004590
Victor Costanf0314ea2019-09-01 20:42:44 -07004591<h4>Class Data Members</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004592
4593<p>The purpose of each class data member (also called an instance
4594variable or member variable) must be clear. If there are any
4595invariants (special values, relationships between members, lifetime
4596requirements) not clearly expressed by the type and name, they must be
4597commented. However, if the type and name suffice (<code>int
4598num_events_;</code>), no comment is needed.</p>
4599
4600<p>In particular, add comments to describe the existence and meaning
4601of sentinel values, such as nullptr or -1, when they are not
4602obvious. For example:</p>
4603
4604<pre>private:
4605 // Used to bounds-check table accesses. -1 means
4606 // that we don't yet know how many entries the table has.
4607 int num_total_entries_;
4608</pre>
4609
Victor Costanf0314ea2019-09-01 20:42:44 -07004610<h4>Global Variables</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004611
4612<p>All global variables should have a comment describing what they
4613are, what they are used for, and (if unclear) why it needs to be
4614global. For example:</p>
4615
4616<pre>// The total number of tests cases that we run through in this regression test.
4617const int kNumTestCases = 6;
4618</pre>
4619
Ted Osborne505ba682018-01-30 12:36:50 -05004620<h3 id="Implementation_Comments">Implementation Comments</h3>
4621
Ted Osborne505ba682018-01-30 12:36:50 -05004622<p>In your implementation you should have comments in tricky,
4623non-obvious, interesting, or important parts of your code.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004624
Victor Costanf0314ea2019-09-01 20:42:44 -07004625<h4>Explanatory Comments</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004626
4627<p>Tricky or complicated code blocks should have comments
4628before them. Example:</p>
4629
Victor Costanf0314ea2019-09-01 20:42:44 -07004630<pre>// Divide result by two, taking into account that x
Ted Osborne505ba682018-01-30 12:36:50 -05004631// contains the carry from the add.
Victor Costanf0314ea2019-09-01 20:42:44 -07004632for (int i = 0; i &lt; result-&gt;size(); ++i) {
Ted Osborne505ba682018-01-30 12:36:50 -05004633 x = (x &lt;&lt; 8) + (*result)[i];
4634 (*result)[i] = x &gt;&gt; 1;
4635 x &amp;= 1;
4636}
4637</pre>
4638
Victor Costanf0314ea2019-09-01 20:42:44 -07004639<h4>Line-end Comments</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004640
4641<p>Also, lines that are non-obvious should get a comment
4642at the end of the line. These end-of-line comments should
4643be separated from the code by 2 spaces. Example:</p>
4644
4645<pre>// If we have enough memory, mmap the data portion too.
4646mmap_budget = max&lt;int64&gt;(0, mmap_budget - index_-&gt;length());
4647if (mmap_budget &gt;= data_size_ &amp;&amp; !MmapData(mmap_chunk_bytes, mlock))
4648 return; // Error already logged.
4649</pre>
4650
4651<p>Note that there are both comments that describe what
4652the code is doing, and comments that mention that an
4653error has already been logged when the function
4654returns.</p>
4655
Victor Costanf0314ea2019-09-01 20:42:44 -07004656<h4 id="Function_Argument_Comments" class="stylepoint_subsection">Function Argument Comments</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004657
4658<p>When the meaning of a function argument is nonobvious, consider
4659one of the following remedies:</p>
4660
4661<ul>
4662 <li>If the argument is a literal constant, and the same constant is
4663 used in multiple function calls in a way that tacitly assumes they're
4664 the same, you should use a named constant to make that constraint
4665 explicit, and to guarantee that it holds.</li>
4666
4667 <li>Consider changing the function signature to replace a <code>bool</code>
4668 argument with an <code>enum</code> argument. This will make the argument
4669 values self-describing.</li>
4670
4671 <li>For functions that have several configuration options, consider
4672 defining a single class or struct to hold all the options
4673 ,
4674 and pass an instance of that.
4675 This approach has several advantages. Options are referenced by name
4676 at the call site, which clarifies their meaning. It also reduces
4677 function argument count, which makes function calls easier to read and
4678 write. As an added benefit, you don't have to change call sites when
4679 you add another option.
4680 </li>
4681
4682 <li>Replace large or complex nested expressions with named variables.</li>
4683
4684 <li>As a last resort, use comments to clarify argument meanings at the
Victor Costan6dfd9d92018-02-05 18:30:35 -08004685 call site. </li>
Ted Osborne505ba682018-01-30 12:36:50 -05004686</ul>
4687
4688Consider the following example:
4689
4690<pre class="badcode">// What are these arguments?
4691const DecimalNumber product = CalculateProduct(values, 7, false, nullptr);
4692</pre>
4693
4694<p>versus:</p>
4695
4696<pre>ProductOptions options;
4697options.set_precision_decimals(7);
4698options.set_use_cache(ProductOptions::kDontUseCache);
4699const DecimalNumber product =
4700 CalculateProduct(values, options, /*completion_callback=*/nullptr);
4701</pre>
4702
Victor Costanf0314ea2019-09-01 20:42:44 -07004703<h4 id="Implementation_Comment_Donts">Don'ts</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05004704
4705<p>Do not state the obvious. In particular, don't literally describe what
4706code does, unless the behavior is nonobvious to a reader who understands
4707C++ well. Instead, provide higher level comments that describe <i>why</i>
4708the code does what it does, or make the code self describing.</p>
4709
4710Compare this:
4711
4712<pre class="badcode">// Find the element in the vector. &lt;-- Bad: obvious!
4713auto iter = std::find(v.begin(), v.end(), element);
4714if (iter != v.end()) {
4715 Process(element);
4716}
4717</pre>
4718
4719To this:
4720
4721<pre>// Process "element" unless it was already processed.
4722auto iter = std::find(v.begin(), v.end(), element);
4723if (iter != v.end()) {
4724 Process(element);
4725}
4726</pre>
4727
4728Self-describing code doesn't need a comment. The comment from
4729the example above would be obvious:
4730
4731<pre>if (!IsAlreadyProcessed(element)) {
4732 Process(element);
4733}
4734</pre>
4735
Victor Costanf0314ea2019-09-01 20:42:44 -07004736<h3 id="Punctuation,_Spelling_and_Grammar">Punctuation, Spelling, and Grammar</h3>
Ted Osborne505ba682018-01-30 12:36:50 -05004737
Ted Osborne505ba682018-01-30 12:36:50 -05004738<p>Pay attention to punctuation, spelling, and grammar; it is
4739easier to read well-written comments than badly written
4740ones.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004741
4742<p>Comments should be as readable as narrative text, with
4743proper capitalization and punctuation. In many cases,
4744complete sentences are more readable than sentence
4745fragments. Shorter comments, such as comments at the end
4746of a line of code, can sometimes be less formal, but you
4747should be consistent with your style.</p>
4748
4749<p>Although it can be frustrating to have a code reviewer
4750point out that you are using a comma when you should be
4751using a semicolon, it is very important that source code
4752maintain a high level of clarity and readability. Proper
4753punctuation, spelling, and grammar help with that
4754goal.</p>
4755
Ted Osborne505ba682018-01-30 12:36:50 -05004756<h3 id="TODO_Comments">TODO Comments</h3>
4757
Ted Osborne505ba682018-01-30 12:36:50 -05004758<p>Use <code>TODO</code> comments for code that is temporary,
4759a short-term solution, or good-enough but not perfect.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004760
4761<p><code>TODO</code>s should include the string
4762<code>TODO</code> in all caps, followed by the
4763
4764name, e-mail address, bug ID, or other
4765identifier
4766of the person or issue with the best context
4767about the problem referenced by the <code>TODO</code>. The
4768main purpose is to have a consistent <code>TODO</code> that
4769can be searched to find out how to get more details upon
4770request. A <code>TODO</code> is not a commitment that the
4771person referenced will fix the problem. Thus when you create
4772a <code>TODO</code> with a name, it is almost always your
4773name that is given.</p>
4774
4775
4776
4777<div>
4778<pre>// TODO(kl@gmail.com): Use a "*" here for concatenation operator.
4779// TODO(Zeke) change this to use relations.
4780// TODO(bug 12345): remove the "Last visitors" feature
4781</pre>
4782</div>
4783
4784<p>If your <code>TODO</code> is of the form "At a future
4785date do something" make sure that you either include a
4786very specific date ("Fix by November 2005") or a very
4787specific event ("Remove this code when all clients can
4788handle XML responses.").</p>
4789
Ted Osborne505ba682018-01-30 12:36:50 -05004790<h2 id="Formatting">Formatting</h2>
4791
4792<p>Coding style and formatting are pretty arbitrary, but a
4793
4794project is much easier to follow
4795if everyone uses the same style. Individuals may not agree with every
4796aspect of the formatting rules, and some of the rules may take
4797some getting used to, but it is important that all
4798
4799project contributors follow the
Victor Costanf0314ea2019-09-01 20:42:44 -07004800style rules so that
Ted Osborne505ba682018-01-30 12:36:50 -05004801they can all read and understand
4802everyone's code easily.</p>
4803
4804
4805
Victor Costanf0314ea2019-09-01 20:42:44 -07004806<div>
4807<p>To help you format code correctly, we've created a
Ted Osborne505ba682018-01-30 12:36:50 -05004808<a href="https://raw.githubusercontent.com/google/styleguide/gh-pages/google-c-style.el">
4809settings file for emacs</a>.</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07004810</div>
Ted Osborne505ba682018-01-30 12:36:50 -05004811
4812<h3 id="Line_Length">Line Length</h3>
4813
Ted Osborne505ba682018-01-30 12:36:50 -05004814<p>Each line of text in your code should be at most 80
4815characters long.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004816
4817
4818
Victor Costanf0314ea2019-09-01 20:42:44 -07004819<div>
4820<p>We recognize that this rule is
Ted Osborne505ba682018-01-30 12:36:50 -05004821controversial, but so much existing code already adheres
4822to it, and we feel that consistency is important.</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07004823</div>
Ted Osborne505ba682018-01-30 12:36:50 -05004824
Victor Costanf0314ea2019-09-01 20:42:44 -07004825<p class="pros"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05004826<p>Those who favor this rule
4827argue that it is rude to force them to resize
4828their windows and there is no need for anything longer.
4829Some folks are used to having several code windows
4830side-by-side, and thus don't have room to widen their
4831windows in any case. People set up their work environment
4832assuming a particular maximum window width, and 80
4833columns has been the traditional standard. Why change
4834it?</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004835
Victor Costanf0314ea2019-09-01 20:42:44 -07004836<p class="cons"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05004837<p>Proponents of change argue that a wider line can make
4838code more readable. The 80-column limit is an hidebound
4839throwback to 1960s mainframes; modern equipment has wide screens that
4840can easily show longer lines.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004841
Victor Costanf0314ea2019-09-01 20:42:44 -07004842<p class="decision"></p>
Ted Osborne505ba682018-01-30 12:36:50 -05004843<p> 80 characters is the maximum.</p>
4844
Victor Costanb89a7752018-07-31 10:17:48 -07004845<p>A line may exceed 80 characters if it is</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004846
Victor Costanb89a7752018-07-31 10:17:48 -07004847<ul>
4848 <li>a comment line which is not feasible to split without harming
4849 readability, ease of cut and paste or auto-linking -- e.g. if a line
4850 contains an example command or a literal URL longer than 80 characters.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05004851
Victor Costanb89a7752018-07-31 10:17:48 -07004852 <li>a raw-string literal with content that exceeds 80 characters. Except for
4853 test code, such literals should appear near the top of a file.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05004854
Victor Costanb89a7752018-07-31 10:17:48 -07004855 <li>an include statement.</li>
4856
4857 <li>a <a href="#The__define_Guard">header guard</a></li>
4858
4859 <li>a using-declaration</li>
4860</ul>
4861
Ted Osborne505ba682018-01-30 12:36:50 -05004862<h3 id="Non-ASCII_Characters">Non-ASCII Characters</h3>
4863
Ted Osborne505ba682018-01-30 12:36:50 -05004864<p>Non-ASCII characters should be rare, and must use UTF-8
4865formatting.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004866
4867<p>You shouldn't hard-code user-facing text in source,
4868even English, so use of non-ASCII characters should be
4869rare. However, in certain cases it is appropriate to
4870include such words in your code. For example, if your
4871code parses data files from foreign sources, it may be
4872appropriate to hard-code the non-ASCII string(s) used in
4873those data files as delimiters. More commonly, unittest
4874code (which does not need to be localized) might
4875contain non-ASCII strings. In such cases, you should use
4876UTF-8, since that is an encoding
4877understood by most tools able to handle more than just
4878ASCII.</p>
4879
4880<p>Hex encoding is also OK, and encouraged where it
4881enhances readability &#8212; for example,
4882<code>"\xEF\xBB\xBF"</code>, or, even more simply,
4883<code>u8"\uFEFF"</code>, is the Unicode zero-width
4884no-break space character, which would be invisible if
4885included in the source as straight UTF-8.</p>
4886
4887<p>Use the <code>u8</code> prefix
4888to guarantee that a string literal containing
4889<code>\uXXXX</code> escape sequences is encoded as UTF-8.
4890Do not use it for strings containing non-ASCII characters
4891encoded as UTF-8, because that will produce incorrect
4892output if the compiler does not interpret the source file
4893as UTF-8. </p>
4894
4895<p>You shouldn't use the C++11 <code>char16_t</code> and
4896<code>char32_t</code> character types, since they're for
4897non-UTF-8 text. For similar reasons you also shouldn't
4898use <code>wchar_t</code> (unless you're writing code that
4899interacts with the Windows API, which uses
4900<code>wchar_t</code> extensively).</p>
4901
Ted Osborne505ba682018-01-30 12:36:50 -05004902<h3 id="Spaces_vs._Tabs">Spaces vs. Tabs</h3>
4903
Ted Osborne505ba682018-01-30 12:36:50 -05004904<p>Use only spaces, and indent 2 spaces at a time.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004905
4906<p>We use spaces for indentation. Do not use tabs in your
4907code. You should set your editor to emit spaces when you
4908hit the tab key.</p>
4909
Ted Osborne505ba682018-01-30 12:36:50 -05004910<h3 id="Function_Declarations_and_Definitions">Function Declarations and Definitions</h3>
4911
Ted Osborne505ba682018-01-30 12:36:50 -05004912<p>Return type on the same line as function name, parameters
4913on the same line if they fit. Wrap parameter lists which do
4914not fit on a single line as you would wrap arguments in a
4915<a href="#Function_Calls">function call</a>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05004916
4917<p>Functions look like this:</p>
4918
4919
4920<pre>ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
4921 DoSomething();
4922 ...
4923}
4924</pre>
4925
4926<p>If you have too much text to fit on one line:</p>
4927
4928<pre>ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,
4929 Type par_name3) {
4930 DoSomething();
4931 ...
4932}
4933</pre>
4934
4935<p>or if you cannot fit even the first parameter:</p>
4936
4937<pre>ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
4938 Type par_name1, // 4 space indent
4939 Type par_name2,
4940 Type par_name3) {
4941 DoSomething(); // 2 space indent
4942 ...
4943}
4944</pre>
4945
4946<p>Some points to note:</p>
4947
4948<ul>
4949 <li>Choose good parameter names.</li>
4950
Victor Costan6dfd9d92018-02-05 18:30:35 -08004951 <li>A parameter name may be omitted only if the parameter is not used in the
4952 function's definition.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05004953
4954 <li>If you cannot fit the return type and the function
4955 name on a single line, break between them.</li>
4956
4957 <li>If you break after the return type of a function
4958 declaration or definition, do not indent.</li>
4959
4960 <li>The open parenthesis is always on the same line as
4961 the function name.</li>
4962
4963 <li>There is never a space between the function name
4964 and the open parenthesis.</li>
4965
4966 <li>There is never a space between the parentheses and
4967 the parameters.</li>
4968
4969 <li>The open curly brace is always on the end of the last line of the function
4970 declaration, not the start of the next line.</li>
4971
4972 <li>The close curly brace is either on the last line by
4973 itself or on the same line as the open curly brace.</li>
4974
4975 <li>There should be a space between the close
4976 parenthesis and the open curly brace.</li>
4977
4978 <li>All parameters should be aligned if possible.</li>
4979
4980 <li>Default indentation is 2 spaces.</li>
4981
4982 <li>Wrapped parameters have a 4 space indent.</li>
4983</ul>
4984
4985<p>Unused parameters that are obvious from context may be omitted:</p>
4986
4987<pre>class Foo {
4988 public:
Victor Costanf0314ea2019-09-01 20:42:44 -07004989 Foo(const Foo&amp;) = delete;
4990 Foo&amp; operator=(const Foo&amp;) = delete;
Ted Osborne505ba682018-01-30 12:36:50 -05004991};
4992</pre>
4993
4994<p>Unused parameters that might not be obvious should comment out the variable
4995name in the function definition:</p>
4996
4997<pre>class Shape {
4998 public:
4999 virtual void Rotate(double radians) = 0;
5000};
5001
5002class Circle : public Shape {
5003 public:
5004 void Rotate(double radians) override;
5005};
5006
5007void Circle::Rotate(double /*radians*/) {}
5008</pre>
5009
5010<pre class="badcode">// Bad - if someone wants to implement later, it's not clear what the
5011// variable means.
5012void Circle::Rotate(double) {}
5013</pre>
5014
5015<p>Attributes, and macros that expand to attributes, appear at the very
5016beginning of the function declaration or definition, before the
5017return type:</p>
Victor Costanf0314ea2019-09-01 20:42:44 -07005018<pre>ABSL_MUST_USE_RESULT bool IsOk();
Ted Osborne505ba682018-01-30 12:36:50 -05005019</pre>
5020
Ted Osborne505ba682018-01-30 12:36:50 -05005021<h3 id="Formatting_Lambda_Expressions">Lambda Expressions</h3>
5022
Ted Osborne505ba682018-01-30 12:36:50 -05005023<p>Format parameters and bodies as for any other function, and capture
5024lists like other comma-separated lists.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005025
Ted Osborne505ba682018-01-30 12:36:50 -05005026<p>For by-reference captures, do not leave a space between the
5027ampersand (&amp;) and the variable name.</p>
5028<pre>int x = 0;
5029auto x_plus_n = [&amp;x](int n) -&gt; int { return x + n; }
5030</pre>
5031<p>Short lambdas may be written inline as function arguments.</p>
5032<pre>std::set&lt;int&gt; blacklist = {7, 8, 9};
5033std::vector&lt;int&gt; digits = {3, 9, 1, 8, 4, 7, 1};
5034digits.erase(std::remove_if(digits.begin(), digits.end(), [&amp;blacklist](int i) {
5035 return blacklist.find(i) != blacklist.end();
5036 }),
5037 digits.end());
5038</pre>
5039
Victor Costanf0314ea2019-09-01 20:42:44 -07005040<h3 id="Floating_Literals">Floating-point Literals</h3>
5041
5042<p>Floating-point literals should always have a radix point, with digits on both
5043sides, even if they use exponential notation. Readability is improved if all
5044floating-point literals take this familiar form, as this helps ensure that they
5045are not mistaken for integer literals, and that the
5046<code>E</code>/<code>e</code> of the exponential notation is not mistaken for a
5047hexadecimal digit. It is fine to initialize a floating-point variable with an
5048integer literal (assuming the variable type can exactly represent that integer),
5049but note that a number in exponential notation is never an integer literal.
5050</p>
5051
5052<pre class="badcode">float f = 1.f;
5053long double ld = -.5L;
5054double d = 1248e6;
5055</pre>
5056
5057<pre class="goodcode">float f = 1.0f;
5058float f2 = 1; // Also OK
5059long double ld = -0.5L;
5060double d = 1248.0e6;
5061</pre>
5062
Ted Osborne505ba682018-01-30 12:36:50 -05005063
5064<h3 id="Function_Calls">Function Calls</h3>
5065
Ted Osborne505ba682018-01-30 12:36:50 -05005066<p>Either write the call all on a single line, wrap the
5067arguments at the parenthesis, or start the arguments on a new
5068line indented by four spaces and continue at that 4 space
5069indent. In the absence of other considerations, use the
5070minimum number of lines, including placing multiple arguments
5071on each line where appropriate.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005072
5073<p>Function calls have the following format:</p>
5074<pre>bool result = DoSomething(argument1, argument2, argument3);
5075</pre>
5076
5077<p>If the arguments do not all fit on one line, they
5078should be broken up onto multiple lines, with each
5079subsequent line aligned with the first argument. Do not
5080add spaces after the open paren or before the close
5081paren:</p>
5082<pre>bool result = DoSomething(averyveryveryverylongargument1,
5083 argument2, argument3);
5084</pre>
5085
5086<p>Arguments may optionally all be placed on subsequent
5087lines with a four space indent:</p>
5088<pre>if (...) {
5089 ...
5090 ...
5091 if (...) {
5092 bool result = DoSomething(
5093 argument1, argument2, // 4 space indent
5094 argument3, argument4);
5095 ...
5096 }
5097</pre>
5098
5099<p>Put multiple arguments on a single line to reduce the
5100number of lines necessary for calling a function unless
5101there is a specific readability problem. Some find that
5102formatting with strictly one argument on each line is
5103more readable and simplifies editing of the arguments.
5104However, we prioritize for the reader over the ease of
5105editing arguments, and most readability problems are
5106better addressed with the following techniques.</p>
5107
5108<p>If having multiple arguments in a single line decreases
5109readability due to the complexity or confusing nature of the
5110expressions that make up some arguments, try creating
5111variables that capture those arguments in a descriptive name:</p>
5112<pre>int my_heuristic = scores[x] * y + bases[x];
5113bool result = DoSomething(my_heuristic, x, y, z);
5114</pre>
5115
5116<p>Or put the confusing argument on its own line with
5117an explanatory comment:</p>
5118<pre>bool result = DoSomething(scores[x] * y + bases[x], // Score heuristic.
5119 x, y, z);
5120</pre>
5121
5122<p>If there is still a case where one argument is
5123significantly more readable on its own line, then put it on
5124its own line. The decision should be specific to the argument
5125which is made more readable rather than a general policy.</p>
5126
5127<p>Sometimes arguments form a structure that is important
5128for readability. In those cases, feel free to format the
5129arguments according to that structure:</p>
5130<pre>// Transform the widget by a 3x3 matrix.
5131my_widget.Transform(x1, x2, x3,
5132 y1, y2, y3,
5133 z1, z2, z3);
5134</pre>
5135
Ted Osborne505ba682018-01-30 12:36:50 -05005136<h3 id="Braced_Initializer_List_Format">Braced Initializer List Format</h3>
5137
Ted Osborne505ba682018-01-30 12:36:50 -05005138<p>Format a <a href="#Braced_Initializer_List">braced initializer list</a>
5139exactly like you would format a function call in its place.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005140
5141<p>If the braced list follows a name (e.g. a type or
5142variable name), format as if the <code>{}</code> were the
5143parentheses of a function call with that name. If there
5144is no name, assume a zero-length name.</p>
5145
5146<pre>// Examples of braced init list on a single line.
5147return {foo, bar};
5148functioncall({foo, bar});
5149std::pair&lt;int, int&gt; p{foo, bar};
5150
5151// When you have to wrap.
5152SomeFunction(
5153 {"assume a zero-length name before {"},
5154 some_other_function_parameter);
5155SomeType variable{
5156 some, other, values,
5157 {"assume a zero-length name before {"},
5158 SomeOtherType{
5159 "Very long string requiring the surrounding breaks.",
5160 some, other values},
5161 SomeOtherType{"Slightly shorter string",
5162 some, other, values}};
5163SomeType variable{
5164 "This is too long to fit all in one line"};
5165MyType m = { // Here, you could also break before {.
5166 superlongvariablename1,
5167 superlongvariablename2,
5168 {short, interior, list},
5169 {interiorwrappinglist,
5170 interiorwrappinglist2}};
5171</pre>
5172
Ted Osborne505ba682018-01-30 12:36:50 -05005173<h3 id="Conditionals">Conditionals</h3>
5174
Ted Osborne505ba682018-01-30 12:36:50 -05005175<p>Prefer no spaces inside parentheses. The <code>if</code>
5176and <code>else</code> keywords belong on separate lines.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005177
5178<p>There are two acceptable formats for a basic
5179conditional statement. One includes spaces between the
5180parentheses and the condition, and one does not.</p>
5181
5182<p>The most common form is without spaces. Either is
5183fine, but <em>be consistent</em>. If you are modifying a
5184file, use the format that is already present. If you are
5185writing new code, use the format that the other files in
5186that directory or project use. If in doubt and you have
5187no personal preference, do not add the spaces.</p>
5188
5189<pre>if (condition) { // no spaces inside parentheses
5190 ... // 2 space indent.
5191} else if (...) { // The else goes on the same line as the closing brace.
5192 ...
5193} else {
5194 ...
5195}
5196</pre>
5197
5198<p>If you prefer you may add spaces inside the
5199parentheses:</p>
5200
5201<pre>if ( condition ) { // spaces inside parentheses - rare
5202 ... // 2 space indent.
5203} else { // The else goes on the same line as the closing brace.
5204 ...
5205}
5206</pre>
5207
5208<p>Note that in all cases you must have a space between
5209the <code>if</code> and the open parenthesis. You must
5210also have a space between the close parenthesis and the
5211curly brace, if you're using one.</p>
5212
5213<pre class="badcode">if(condition) { // Bad - space missing after IF.
5214if (condition){ // Bad - space missing before {.
5215if(condition){ // Doubly bad.
5216</pre>
5217
5218<pre>if (condition) { // Good - proper space after IF and before {.
5219</pre>
5220
5221<p>Short conditional statements may be written on one
5222line if this enhances readability. You may use this only
5223when the line is brief and the statement does not use the
5224<code>else</code> clause.</p>
5225
5226<pre>if (x == kFoo) return new Foo();
5227if (x == kBar) return new Bar();
5228</pre>
5229
5230<p>This is not allowed when the if statement has an
5231<code>else</code>:</p>
5232
5233<pre class="badcode">// Not allowed - IF statement on one line when there is an ELSE clause
5234if (x) DoThis();
5235else DoThat();
5236</pre>
5237
5238<p>In general, curly braces are not required for
5239single-line statements, but they are allowed if you like
5240them; conditional or loop statements with complex
5241conditions or statements may be more readable with curly
Victor Costanf0314ea2019-09-01 20:42:44 -07005242braces. Some
Ted Osborne505ba682018-01-30 12:36:50 -05005243projects require that an
Victor Costan6dfd9d92018-02-05 18:30:35 -08005244<code>if</code> must always have an accompanying
Ted Osborne505ba682018-01-30 12:36:50 -05005245brace.</p>
5246
5247<pre>if (condition)
5248 DoSomething(); // 2 space indent.
5249
5250if (condition) {
5251 DoSomething(); // 2 space indent.
5252}
5253</pre>
5254
5255<p>However, if one part of an
5256<code>if</code>-<code>else</code> statement uses curly
5257braces, the other part must too:</p>
5258
5259<pre class="badcode">// Not allowed - curly on IF but not ELSE
5260if (condition) {
5261 foo;
5262} else
5263 bar;
5264
5265// Not allowed - curly on ELSE but not IF
5266if (condition)
5267 foo;
5268else {
5269 bar;
5270}
5271</pre>
5272
5273<pre>// Curly braces around both IF and ELSE required because
5274// one of the clauses used braces.
5275if (condition) {
5276 foo;
5277} else {
5278 bar;
5279}
5280</pre>
5281
Ted Osborne505ba682018-01-30 12:36:50 -05005282<h3 id="Loops_and_Switch_Statements">Loops and Switch Statements</h3>
5283
Ted Osborne505ba682018-01-30 12:36:50 -05005284<p>Switch statements may use braces for blocks. Annotate
5285non-trivial fall-through between cases.
5286Braces are optional for single-statement loops.
Victor Costan6dfd9d92018-02-05 18:30:35 -08005287Empty loop bodies should use either empty braces or <code>continue</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005288
5289<p><code>case</code> blocks in <code>switch</code>
5290statements can have curly braces or not, depending on
5291your preference. If you do include curly braces they
5292should be placed as shown below.</p>
5293
5294<p>If not conditional on an enumerated value, switch
5295statements should always have a <code>default</code> case
5296(in the case of an enumerated value, the compiler will
5297warn you if any values are not handled). If the default
Victor Costan6dfd9d92018-02-05 18:30:35 -08005298case should never execute, treat this as an error. For example:
Ted Osborne505ba682018-01-30 12:36:50 -05005299
Victor Costanf0314ea2019-09-01 20:42:44 -07005300</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005301
5302<div>
5303<pre>switch (var) {
5304 case 0: { // 2 space indent
5305 ... // 4 space indent
5306 break;
5307 }
5308 case 1: {
5309 ...
5310 break;
5311 }
5312 default: {
5313 assert(false);
5314 }
5315}
5316</pre>
Victor Costanf0314ea2019-09-01 20:42:44 -07005317</div>
Ted Osborne505ba682018-01-30 12:36:50 -05005318
Victor Costan4b9c0c02018-02-20 14:58:48 -08005319<p>Fall-through from one case label to
5320another must be annotated using the
5321<code>ABSL_FALLTHROUGH_INTENDED;</code> macro (defined in
Ted Osborne505ba682018-01-30 12:36:50 -05005322
Victor Costan4b9c0c02018-02-20 14:58:48 -08005323<code>absl/base/macros.h</code>).
5324<code>ABSL_FALLTHROUGH_INTENDED;</code> should be placed at a
5325point of execution where a fall-through to the next case
5326label occurs. A common exception is consecutive case
5327labels without intervening code, in which case no
5328annotation is needed.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005329
Victor Costan4b9c0c02018-02-20 14:58:48 -08005330<pre>switch (x) {
5331 case 41: // No annotation needed here.
5332 case 43:
5333 if (dont_be_picky) {
5334 // Use this instead of or along with annotations in comments.
5335 ABSL_FALLTHROUGH_INTENDED;
5336 } else {
5337 CloseButNoCigar();
5338 break;
5339 }
5340 case 42:
5341 DoSomethingSpecial();
5342 ABSL_FALLTHROUGH_INTENDED;
5343 default:
5344 DoSomethingGeneric();
5345 break;
5346}
5347</pre>
Ted Osborne505ba682018-01-30 12:36:50 -05005348
5349<p> Braces are optional for single-statement loops.</p>
5350
5351<pre>for (int i = 0; i &lt; kSomeNumber; ++i)
5352 printf("I love you\n");
5353
5354for (int i = 0; i &lt; kSomeNumber; ++i) {
5355 printf("I take it back\n");
5356}
5357</pre>
5358
5359
Victor Costan6dfd9d92018-02-05 18:30:35 -08005360<p>Empty loop bodies should use either an empty pair of braces or
5361<code>continue</code> with no braces, rather than a single semicolon.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005362
5363<pre>while (condition) {
5364 // Repeat test until it returns false.
5365}
5366for (int i = 0; i &lt; kSomeNumber; ++i) {} // Good - one newline is also OK.
5367while (condition) continue; // Good - continue indicates no logic.
5368</pre>
5369
5370<pre class="badcode">while (condition); // Bad - looks like part of do/while loop.
5371</pre>
5372
Ted Osborne505ba682018-01-30 12:36:50 -05005373<h3 id="Pointer_and_Reference_Expressions">Pointer and Reference Expressions</h3>
5374
Ted Osborne505ba682018-01-30 12:36:50 -05005375<p>No spaces around period or arrow. Pointer operators do not
5376have trailing spaces.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005377
5378<p>The following are examples of correctly-formatted
5379pointer and reference expressions:</p>
5380
5381<pre>x = *p;
5382p = &amp;x;
5383x = r.y;
5384x = r-&gt;y;
5385</pre>
5386
5387<p>Note that:</p>
5388
5389<ul>
5390 <li>There are no spaces around the period or arrow when
5391 accessing a member.</li>
5392
5393 <li>Pointer operators have no space after the
5394 <code>*</code> or <code>&amp;</code>.</li>
5395</ul>
5396
5397<p>When declaring a pointer variable or argument, you may
5398place the asterisk adjacent to either the type or to the
5399variable name:</p>
5400
5401<pre>// These are fine, space preceding.
5402char *c;
Victor Costanf0314ea2019-09-01 20:42:44 -07005403const std::string &amp;str;
Ted Osborne505ba682018-01-30 12:36:50 -05005404
5405// These are fine, space following.
5406char* c;
Victor Costanf0314ea2019-09-01 20:42:44 -07005407const std::string&amp; str;
Ted Osborne505ba682018-01-30 12:36:50 -05005408</pre>
5409
Victor Costan6dfd9d92018-02-05 18:30:35 -08005410<p>You should do this consistently within a single
5411file,
5412so, when modifying an existing file, use the style in
5413that file.</p>
5414
Ted Osborne505ba682018-01-30 12:36:50 -05005415It is allowed (if unusual) to declare multiple variables in the same
5416declaration, but it is disallowed if any of those have pointer or
5417reference decorations. Such declarations are easily misread.
5418<pre>// Fine if helpful for readability.
5419int x, y;
5420</pre>
5421<pre class="badcode">int x, *y; // Disallowed - no &amp; or * in multiple declaration
5422char * c; // Bad - spaces on both sides of *
Victor Costanf0314ea2019-09-01 20:42:44 -07005423const std::string &amp; str; // Bad - spaces on both sides of &amp;
Ted Osborne505ba682018-01-30 12:36:50 -05005424</pre>
5425
Ted Osborne505ba682018-01-30 12:36:50 -05005426<h3 id="Boolean_Expressions">Boolean Expressions</h3>
5427
Ted Osborne505ba682018-01-30 12:36:50 -05005428<p>When you have a boolean expression that is longer than the
5429<a href="#Line_Length">standard line length</a>, be
5430consistent in how you break up the lines.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005431
5432<p>In this example, the logical AND operator is always at
5433the end of the lines:</p>
5434
5435<pre>if (this_one_thing &gt; this_other_thing &amp;&amp;
5436 a_third_thing == a_fourth_thing &amp;&amp;
5437 yet_another &amp;&amp; last_one) {
5438 ...
5439}
5440</pre>
5441
5442<p>Note that when the code wraps in this example, both of
5443the <code>&amp;&amp;</code> logical AND operators are at
5444the end of the line. This is more common in Google code,
5445though wrapping all operators at the beginning of the
5446line is also allowed. Feel free to insert extra
5447parentheses judiciously because they can be very helpful
5448in increasing readability when used
5449appropriately. Also note that you should always use
5450the punctuation operators, such as
5451<code>&amp;&amp;</code> and <code>~</code>, rather than
5452the word operators, such as <code>and</code> and
5453<code>compl</code>.</p>
5454
Ted Osborne505ba682018-01-30 12:36:50 -05005455<h3 id="Return_Values">Return Values</h3>
5456
Ted Osborne505ba682018-01-30 12:36:50 -05005457<p>Do not needlessly surround the <code>return</code>
5458expression with parentheses.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005459
5460<p>Use parentheses in <code>return expr;</code> only
5461where you would use them in <code>x = expr;</code>.</p>
5462
5463<pre>return result; // No parentheses in the simple case.
5464// Parentheses OK to make a complex expression more readable.
5465return (some_long_condition &amp;&amp;
5466 another_condition);
5467</pre>
5468
5469<pre class="badcode">return (value); // You wouldn't write var = (value);
5470return(result); // return is not a function!
5471</pre>
5472
Ted Osborne505ba682018-01-30 12:36:50 -05005473
Ted Osborne505ba682018-01-30 12:36:50 -05005474
5475<h3 id="Variable_and_Array_Initialization">Variable and Array Initialization</h3>
5476
Ted Osborne505ba682018-01-30 12:36:50 -05005477<p>Your choice of <code>=</code>, <code>()</code>, or
5478<code>{}</code>.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005479
5480<p>You may choose between <code>=</code>,
5481<code>()</code>, and <code>{}</code>; the following are
5482all correct:</p>
5483
5484<pre>int x = 3;
5485int x(3);
5486int x{3};
Victor Costanf0314ea2019-09-01 20:42:44 -07005487std::string name = "Some Name";
5488std::string name("Some Name");
5489std::string name{"Some Name"};
Ted Osborne505ba682018-01-30 12:36:50 -05005490</pre>
5491
5492<p>Be careful when using a braced initialization list <code>{...}</code>
5493on a type with an <code>std::initializer_list</code> constructor.
5494A nonempty <i>braced-init-list</i> prefers the
5495<code>std::initializer_list</code> constructor whenever
5496possible. Note that empty braces <code>{}</code> are special, and
5497will call a default constructor if available. To force the
5498non-<code>std::initializer_list</code> constructor, use parentheses
5499instead of braces.</p>
5500
Victor Costan6dfd9d92018-02-05 18:30:35 -08005501<pre>std::vector&lt;int&gt; v(100, 1); // A vector containing 100 items: All 1s.
5502std::vector&lt;int&gt; v{100, 1}; // A vector containing 2 items: 100 and 1.
Ted Osborne505ba682018-01-30 12:36:50 -05005503</pre>
5504
5505<p>Also, the brace form prevents narrowing of integral
5506types. This can prevent some types of programming
5507errors.</p>
5508
5509<pre>int pi(3.14); // OK -- pi == 3.
5510int pi{3.14}; // Compile error: narrowing conversion.
5511</pre>
5512
Ted Osborne505ba682018-01-30 12:36:50 -05005513<h3 id="Preprocessor_Directives">Preprocessor Directives</h3>
5514
Ted Osborne505ba682018-01-30 12:36:50 -05005515<p>The hash mark that starts a preprocessor directive should
5516always be at the beginning of the line.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005517
5518<p>Even when preprocessor directives are within the body
5519of indented code, the directives should start at the
5520beginning of the line.</p>
5521
5522<pre>// Good - directives at beginning of line
5523 if (lopsided_score) {
5524#if DISASTER_PENDING // Correct -- Starts at beginning of line
5525 DropEverything();
5526# if NOTIFY // OK but not required -- Spaces after #
5527 NotifyClient();
5528# endif
5529#endif
5530 BackToNormal();
5531 }
5532</pre>
5533
5534<pre class="badcode">// Bad - indented directives
5535 if (lopsided_score) {
5536 #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line
5537 DropEverything();
5538 #endif // Wrong! Do not indent "#endif"
5539 BackToNormal();
5540 }
5541</pre>
5542
Ted Osborne505ba682018-01-30 12:36:50 -05005543<h3 id="Class_Format">Class Format</h3>
5544
Ted Osborne505ba682018-01-30 12:36:50 -05005545<p>Sections in <code>public</code>, <code>protected</code> and
5546<code>private</code> order, each indented one space.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005547
5548<p>The basic format for a class definition (lacking the
5549comments, see <a href="#Class_Comments">Class
5550Comments</a> for a discussion of what comments are
5551needed) is:</p>
5552
5553<pre>class MyClass : public OtherClass {
5554 public: // Note the 1 space indent!
5555 MyClass(); // Regular 2 space indent.
5556 explicit MyClass(int var);
5557 ~MyClass() {}
5558
5559 void SomeFunction();
5560 void SomeFunctionThatDoesNothing() {
5561 }
5562
5563 void set_some_var(int var) { some_var_ = var; }
5564 int some_var() const { return some_var_; }
5565
5566 private:
5567 bool SomeInternalFunction();
5568
5569 int some_var_;
5570 int some_other_var_;
5571};
5572</pre>
5573
5574<p>Things to note:</p>
5575
5576<ul>
5577 <li>Any base class name should be on the same line as
5578 the subclass name, subject to the 80-column limit.</li>
5579
5580 <li>The <code>public:</code>, <code>protected:</code>,
5581 and <code>private:</code> keywords should be indented
5582 one space.</li>
5583
5584 <li>Except for the first instance, these keywords
5585 should be preceded by a blank line. This rule is
5586 optional in small classes.</li>
5587
5588 <li>Do not leave a blank line after these
5589 keywords.</li>
5590
5591 <li>The <code>public</code> section should be first,
5592 followed by the <code>protected</code> and finally the
5593 <code>private</code> section.</li>
5594
5595 <li>See <a href="#Declaration_Order">Declaration
5596 Order</a> for rules on ordering declarations within
5597 each of these sections.</li>
5598</ul>
5599
Ted Osborne505ba682018-01-30 12:36:50 -05005600<h3 id="Constructor_Initializer_Lists">Constructor Initializer Lists</h3>
5601
Ted Osborne505ba682018-01-30 12:36:50 -05005602<p>Constructor initializer lists can be all on one line or
5603with subsequent lines indented four spaces.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005604
5605<p>The acceptable formats for initializer lists are:</p>
5606
5607<pre>// When everything fits on one line:
5608MyClass::MyClass(int var) : some_var_(var) {
5609 DoSomething();
5610}
5611
5612// If the signature and initializer list are not all on one line,
5613// you must wrap before the colon and indent 4 spaces:
5614MyClass::MyClass(int var)
5615 : some_var_(var), some_other_var_(var + 1) {
5616 DoSomething();
5617}
5618
5619// When the list spans multiple lines, put each member on its own line
5620// and align them:
5621MyClass::MyClass(int var)
5622 : some_var_(var), // 4 space indent
5623 some_other_var_(var + 1) { // lined up
5624 DoSomething();
5625}
5626
5627// As with any other code block, the close curly can be on the same
5628// line as the open curly, if it fits.
5629MyClass::MyClass(int var)
5630 : some_var_(var) {}
5631</pre>
5632
Ted Osborne505ba682018-01-30 12:36:50 -05005633<h3 id="Namespace_Formatting">Namespace Formatting</h3>
5634
Ted Osborne505ba682018-01-30 12:36:50 -05005635<p>The contents of namespaces are not indented.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005636
5637<p><a href="#Namespaces">Namespaces</a> do not add an
5638extra level of indentation. For example, use:</p>
5639
5640<pre>namespace {
5641
5642void foo() { // Correct. No extra indentation within namespace.
5643 ...
5644}
5645
5646} // namespace
5647</pre>
5648
5649<p>Do not indent within a namespace:</p>
5650
5651<pre class="badcode">namespace {
5652
Victor Costan6dfd9d92018-02-05 18:30:35 -08005653 // Wrong! Indented when it should not be.
Ted Osborne505ba682018-01-30 12:36:50 -05005654 void foo() {
5655 ...
5656 }
5657
5658} // namespace
5659</pre>
5660
5661<p>When declaring nested namespaces, put each namespace
5662on its own line.</p>
5663
5664<pre>namespace foo {
5665namespace bar {
5666</pre>
5667
Ted Osborne505ba682018-01-30 12:36:50 -05005668<h3 id="Horizontal_Whitespace">Horizontal Whitespace</h3>
5669
Ted Osborne505ba682018-01-30 12:36:50 -05005670<p>Use of horizontal whitespace depends on location. Never put
5671trailing whitespace at the end of a line.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005672
Victor Costanf0314ea2019-09-01 20:42:44 -07005673<h4>General</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05005674
5675<pre>void f(bool b) { // Open braces should always have a space before them.
5676 ...
5677int i = 0; // Semicolons usually have no space before them.
5678// Spaces inside braces for braced-init-list are optional. If you use them,
5679// put them on both sides!
5680int x[] = { 0 };
5681int x[] = {0};
5682
5683// Spaces around the colon in inheritance and initializer lists.
5684class Foo : public Bar {
5685 public:
5686 // For inline function implementations, put spaces between the braces
5687 // and the implementation itself.
5688 Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces.
5689 void Reset() { baz_ = 0; } // Spaces separating braces from implementation.
5690 ...
5691</pre>
5692
5693<p>Adding trailing whitespace can cause extra work for
5694others editing the same file, when they merge, as can
5695removing existing trailing whitespace. So: Don't
5696introduce trailing whitespace. Remove it if you're
5697already changing that line, or do it in a separate
Victor Costanf0314ea2019-09-01 20:42:44 -07005698clean-up
Ted Osborne505ba682018-01-30 12:36:50 -05005699operation (preferably when no-one
5700else is working on the file).</p>
5701
Victor Costanf0314ea2019-09-01 20:42:44 -07005702<h4>Loops and Conditionals</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05005703
5704<pre>if (b) { // Space after the keyword in conditions and loops.
5705} else { // Spaces around else.
5706}
5707while (test) {} // There is usually no space inside parentheses.
5708switch (i) {
5709for (int i = 0; i &lt; 5; ++i) {
5710// Loops and conditions may have spaces inside parentheses, but this
5711// is rare. Be consistent.
5712switch ( i ) {
5713if ( test ) {
5714for ( int i = 0; i &lt; 5; ++i ) {
5715// For loops always have a space after the semicolon. They may have a space
5716// before the semicolon, but this is rare.
5717for ( ; i &lt; 5 ; ++i) {
5718 ...
5719
5720// Range-based for loops always have a space before and after the colon.
5721for (auto x : counts) {
5722 ...
5723}
5724switch (i) {
5725 case 1: // No space before colon in a switch case.
5726 ...
5727 case 2: break; // Use a space after a colon if there's code after it.
5728</pre>
5729
Victor Costanf0314ea2019-09-01 20:42:44 -07005730<h4>Operators</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05005731
5732<pre>// Assignment operators always have spaces around them.
5733x = 0;
5734
5735// Other binary operators usually have spaces around them, but it's
5736// OK to remove spaces around factors. Parentheses should have no
5737// internal padding.
5738v = w * x + y / z;
5739v = w*x + y/z;
5740v = w * (x + z);
5741
5742// No spaces separating unary operators and their arguments.
5743x = -5;
5744++x;
5745if (x &amp;&amp; !y)
5746 ...
5747</pre>
5748
Victor Costanf0314ea2019-09-01 20:42:44 -07005749<h4>Templates and Casts</h4>
Ted Osborne505ba682018-01-30 12:36:50 -05005750
5751<pre>// No spaces inside the angle brackets (&lt; and &gt;), before
5752// &lt;, or between &gt;( in a cast
Victor Costanf0314ea2019-09-01 20:42:44 -07005753std::vector&lt;std::string&gt; x;
Ted Osborne505ba682018-01-30 12:36:50 -05005754y = static_cast&lt;char*&gt;(x);
5755
5756// Spaces between type and pointer are OK, but be consistent.
5757std::vector&lt;char *&gt; x;
5758</pre>
5759
Ted Osborne505ba682018-01-30 12:36:50 -05005760<h3 id="Vertical_Whitespace">Vertical Whitespace</h3>
5761
Ted Osborne505ba682018-01-30 12:36:50 -05005762<p>Minimize use of vertical whitespace.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005763
Victor Costanb89a7752018-07-31 10:17:48 -07005764<p>This is more a principle than a rule: don't use blank lines when
5765you don't have to. In particular, don't put more than one or two blank
5766lines between functions, resist starting functions with a blank line,
5767don't end functions with a blank line, and be sparing with your use of
5768blank lines. A blank line within a block of code serves like a
5769paragraph break in prose: visually separating two thoughts.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005770
Victor Costanb89a7752018-07-31 10:17:48 -07005771<p>The basic principle is: The more code that fits on one screen, the
5772easier it is to follow and understand the control flow of the
5773program. Use whitespace purposefully to provide separation in that
5774flow.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005775
5776<p>Some rules of thumb to help when blank lines may be
5777useful:</p>
5778
5779<ul>
5780 <li>Blank lines at the beginning or end of a function
Victor Costanb89a7752018-07-31 10:17:48 -07005781 do not help readability.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05005782
5783 <li>Blank lines inside a chain of if-else blocks may
5784 well help readability.</li>
Victor Costanb89a7752018-07-31 10:17:48 -07005785
5786 <li>A blank line before a comment line usually helps
5787 readability &#8212; the introduction of a new comment suggests
5788 the start of a new thought, and the blank line makes it clear
5789 that the comment goes with the following thing instead of the
5790 preceding.</li>
Ted Osborne505ba682018-01-30 12:36:50 -05005791</ul>
5792
Ted Osborne505ba682018-01-30 12:36:50 -05005793<h2 id="Exceptions_to_the_Rules">Exceptions to the Rules</h2>
5794
5795<p>The coding conventions described above are mandatory.
5796However, like all good rules, these sometimes have exceptions,
5797which we discuss here.</p>
5798
Victor Costanf0314ea2019-09-01 20:42:44 -07005799
Ted Osborne505ba682018-01-30 12:36:50 -05005800
5801<div>
5802<h3 id="Existing_Non-conformant_Code">Existing Non-conformant Code</h3>
5803
Ted Osborne505ba682018-01-30 12:36:50 -05005804<p>You may diverge from the rules when dealing with code that
5805does not conform to this style guide.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005806
5807<p>If you find yourself modifying code that was written
5808to specifications other than those presented by this
5809guide, you may have to diverge from these rules in order
5810to stay consistent with the local conventions in that
5811code. If you are in doubt about how to do this, ask the
5812original author or the person currently responsible for
5813the code. Remember that <em>consistency</em> includes
5814local consistency, too.</p>
5815
Victor Costanf0314ea2019-09-01 20:42:44 -07005816</div>
Ted Osborne505ba682018-01-30 12:36:50 -05005817
Victor Costanf0314ea2019-09-01 20:42:44 -07005818
Ted Osborne505ba682018-01-30 12:36:50 -05005819
5820<h3 id="Windows_Code">Windows Code</h3>
5821
Ted Osborne505ba682018-01-30 12:36:50 -05005822<p> Windows
5823programmers have developed their own set of coding
5824conventions, mainly derived from the conventions in Windows
5825headers and other Microsoft code. We want to make it easy
5826for anyone to understand your code, so we have a single set
5827of guidelines for everyone writing C++ on any platform.</p>
Ted Osborne505ba682018-01-30 12:36:50 -05005828
Ted Osborne505ba682018-01-30 12:36:50 -05005829<p>It is worth reiterating a few of the guidelines that
5830you might forget if you are used to the prevalent Windows
5831style:</p>
5832
5833<ul>
5834 <li>Do not use Hungarian notation (for example, naming
5835 an integer <code>iNum</code>). Use the Google naming
5836 conventions, including the <code>.cc</code> extension
5837 for source files.</li>
5838
5839 <li>Windows defines many of its own synonyms for
5840 primitive types, such as <code>DWORD</code>,
5841 <code>HANDLE</code>, etc. It is perfectly acceptable,
5842 and encouraged, that you use these types when calling
5843 Windows API functions. Even so, keep as close as you
5844 can to the underlying C++ types. For example, use
5845 <code>const TCHAR *</code> instead of
5846 <code>LPCTSTR</code>.</li>
5847
5848 <li>When compiling with Microsoft Visual C++, set the
5849 compiler to warning level 3 or higher, and treat all
5850 warnings as errors.</li>
5851
5852 <li>Do not use <code>#pragma once</code>; instead use
5853 the standard Google include guards. The path in the
5854 include guards should be relative to the top of your
5855 project tree.</li>
5856
5857 <li>In fact, do not use any nonstandard extensions,
5858 like <code>#pragma</code> and <code>__declspec</code>,
5859 unless you absolutely must. Using
5860 <code>__declspec(dllimport)</code> and
5861 <code>__declspec(dllexport)</code> is allowed; however,
5862 you must use them through macros such as
5863 <code>DLLIMPORT</code> and <code>DLLEXPORT</code>, so
5864 that someone can easily disable the extensions if they
5865 share the code.</li>
5866</ul>
5867
5868<p>However, there are just a few rules that we
5869occasionally need to break on Windows:</p>
5870
5871<ul>
Victor Costanf0314ea2019-09-01 20:42:44 -07005872 <li>Normally we <a href="#Multiple_Inheritance">strongly discourage
Ted Osborne505ba682018-01-30 12:36:50 -05005873 the use of multiple implementation inheritance</a>;
5874 however, it is required when using COM and some ATL/WTL
5875 classes. You may use multiple implementation
5876 inheritance to implement COM or ATL/WTL classes and
5877 interfaces.</li>
5878
5879 <li>Although you should not use exceptions in your own
5880 code, they are used extensively in the ATL and some
5881 STLs, including the one that comes with Visual C++.
5882 When using the ATL, you should define
5883 <code>_ATL_NO_EXCEPTIONS</code> to disable exceptions.
5884 You should investigate whether you can also disable
5885 exceptions in your STL, but if not, it is OK to turn on
5886 exceptions in the compiler. (Note that this is only to
5887 get the STL to compile. You should still not write
5888 exception handling code yourself.)</li>
5889
5890 <li>The usual way of working with precompiled headers
5891 is to include a header file at the top of each source
5892 file, typically with a name like <code>StdAfx.h</code>
5893 or <code>precompile.h</code>. To make your code easier
5894 to share with other projects, avoid including this file
5895 explicitly (except in <code>precompile.cc</code>), and
5896 use the <code>/FI</code> compiler option to include the
5897 file automatically.</li>
5898
5899 <li>Resource headers, which are usually named
5900 <code>resource.h</code> and contain only macros, do not
5901 need to conform to these style guidelines.</li>
5902</ul>
5903
Victor Costan6dfd9d92018-02-05 18:30:35 -08005904<h2 id="Parting_Words">Parting Words</h2>
Ted Osborne505ba682018-01-30 12:36:50 -05005905
5906<p>Use common sense and <em>BE CONSISTENT</em>.</p>
5907
5908<p>If you are editing code, take a few minutes to look at the
5909code around you and determine its style. If they use spaces
5910around their <code>if</code> clauses, you should, too. If their
5911comments have little boxes of stars around them, make your
5912comments have little boxes of stars around them too.</p>
5913
5914<p>The point of having style guidelines is to have a common
5915vocabulary of coding so people can concentrate on what you are
5916saying, rather than on how you are saying it. We present global
5917style rules here so people know the vocabulary. But local style
5918is also important. If code you add to a file looks drastically
5919different from the existing code around it, the discontinuity
5920throws readers out of their rhythm when they go to read it. Try
5921to avoid this.</p>
5922
5923
5924
5925<p>OK, enough writing about writing code; the code itself is much
5926more interesting. Have fun!</p>
5927
5928<hr>
Ted Osborne505ba682018-01-30 12:36:50 -05005929</div>
5930</body>
5931</html>