forked from RobotLocomotion/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cppguide.html
6723 lines (5434 loc) · 255 KB
/
cppguide.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Google C++ Style Guide for Drake</title>
<link rel="stylesheet" type="text/css" href="include/styleguide.css">
<script language="javascript" src="include/styleguide.js"></script>
<link rel="shortcut icon" type="image/x-icon" href="https://drake.mit.edu/_static/favicon.ico" />
</head>
<body onload="initStyleGuide();">
<div id="content">
<h1>Google C++ Style Guide for Drake</h1>
<div class="horizontal_toc" id="tocDiv"></div>
<h2 id="Background" class="ignoreLink">Background</h2>
<p class="drake">Forked and adapted from the
<a href="https://google.github.io/styleguide/cppguide.html">Google style
guide</a>. Many references to Google are deliberately left in to minimize
merge conflicts.</p>
<p>C++ is one of the main development languages used by
many of Google's open-source projects. As every C++
programmer knows, the language has many powerful features, but
this power brings with it complexity, which in turn can make
code more bug-prone and harder to read and maintain.</p>
<p>The goal of this guide is to manage this complexity by
describing in detail the dos and don'ts of writing C++ code
. These rules exist to
keep the code base manageable while still allowing
coders to use C++ language features productively.</p>
<p><em>Style</em>, also known as readability, is what we call
the conventions that govern our C++ code. The term Style is a
bit of a misnomer, since these conventions cover far more than
just source file formatting.</p>
<p>
Most code in Drake conforms to the requirements in this guide. Where
Drake-specific rules contradict previous Google conventions, the text is
retained for reference but otherwise marked <span class="nondrake">with a
strikethrough</span>. The style is intentionally difficult to read in the
normal course of perusal. Copying-and-pasting, or even simply highlighting the
text, will facilitate reading if necessary.
Rules specific to Drake <span class="drake">are highlighted like this</span> for
clarity and easier maintainability.
</p>
<p class="drake">
Drake does not use <a href="https://github.com/abseil/abseil-cpp">Abseil</a>;
please ignore any suggestions or rules that regard Abseil.
</p>
<p>Note that this guide is not a C++ tutorial: we assume that
the reader is familiar with the language. </p>
<h3 id="Goals">Goals of the Style Guide</h3>
<p>Why do we have this document?</p>
<p>There are a few core goals that we believe this guide should
serve. These are the fundamental <b>why</b>s that
underlie all of the individual rules. By bringing these ideas to
the fore, we hope to ground discussions and make it clearer to our
broader community why the rules are in place and why particular
decisions have been made. If you understand what goals each rule is
serving, it should be clearer to everyone when a rule may be waived
(some can be), and what sort of argument or alternative would be
necessary to change a rule in the guide.</p>
<p>The goals of the style guide as we currently see them are as follows:</p>
<dl>
<dt>Style rules should pull their weight</dt>
<dd>The benefit of a style rule
must be large enough to justify asking all of our engineers to
remember it. The benefit is measured relative to the codebase we would
get without the rule, so a rule against a very harmful practice may
still have a small benefit if people are unlikely to do it
anyway. This principle mostly explains the rules we don’t have, rather
than the rules we do: for example, <code>goto</code> contravenes many
of the following principles, but is already vanishingly rare, so the Style
Guide doesn’t discuss it.</dd>
<dt>Optimize for the reader, not the writer</dt>
<dd>Our codebase (and most individual components submitted to it) is
expected to continue for quite some time. As a result, more time will
be spent reading most of our code than writing it. We explicitly
choose to optimize for the experience of our average software engineer
reading, maintaining, and debugging code in our codebase rather than
ease when writing said code. "Leave a trace for the reader" is a
particularly common sub-point of this principle: When something
surprising or unusual is happening in a snippet of code (for example,
transfer of pointer ownership), leaving textual hints for the reader
at the point of use is valuable (<code>std::unique_ptr</code>
demonstrates the ownership transfer unambiguously at the call
site). </dd>
<dt>Be consistent with existing code</dt>
<dd>Using one style consistently through our codebase lets us focus on
other (more important) issues. Consistency also allows for
automation: tools that format your code or adjust
your <code>#include</code>s only work properly when your code is
consistent with the expectations of the tooling. In many cases, rules
that are attributed to "Be Consistent" boil down to "Just pick one and
stop worrying about it"; the potential value of allowing flexibility
on these points is outweighed by the cost of having people argue over
them. </dd>
<dt>Be consistent with the broader C++ community when appropriate</dt>
<dd>Consistency with the way other organizations use C++ has value for
the same reasons as consistency within our code base. If a feature in
the C++ standard solves a problem, or if some idiom is widely known
and accepted, that's an argument for using it. However, sometimes
standard features and idioms are flawed, or were just designed without
our codebase's needs in mind. In those cases (as described below) it's
appropriate to constrain or ban standard features. In some cases we
prefer a homegrown or third-party library over a library defined in
the C++ Standard, either out of perceived superiority or insufficient
value to transition the codebase to the standard interface.</dd>
<dt>Avoid surprising or dangerous constructs</dt>
<dd>C++ has features that are more surprising or dangerous than one
might think at a glance. Some style guide restrictions are in place to
prevent falling into these pitfalls. There is a high bar for style
guide waivers on such restrictions, because waiving such rules often
directly risks compromising program correctness.
</dd>
<dt>Avoid constructs that our average C++ programmer would find tricky
or hard to maintain</dt>
<dd>C++ has features that may not be generally appropriate because of
the complexity they introduce to the code. In widely used
code, it may be more acceptable to use
trickier language constructs, because any benefits of more complex
implementation are multiplied widely by usage, and the cost in understanding
the complexity does not need to be paid again when working with new
portions of the codebase. When in doubt, waivers to rules of this type
can be sought by asking
your project leads. This is specifically
important for our codebase because code ownership and team membership
changes over time: even if everyone that works with some piece of code
currently understands it, such understanding is not guaranteed to hold a
few years from now.</dd>
<dt>Be mindful of our scale</dt>
<dd>With a codebase of 100+ million lines and thousands of engineers,
some mistakes and simplifications for one engineer can become costly
for many. For instance it's particularly important to
avoid polluting the global namespace: name collisions across a
codebase of hundreds of millions of lines are difficult to work with
and hard to avoid if everyone puts things into the global
namespace.</dd>
<dt>Concede to optimization when necessary</dt>
<dd>Performance optimizations can sometimes be necessary and
appropriate, even when they conflict with the other principles of this
document.</dd>
</dl>
<p>The intent of this document is to provide maximal guidance with
reasonable restriction. As always, common sense and good taste should
prevail. By this we specifically refer to the established conventions
of the entire Google C++ community, not just your personal preferences
or those of your team. Be skeptical about and reluctant to use
clever or unusual constructs: the absence of a prohibition is not the
same as a license to proceed. Use your judgment, and if you are
unsure, please don't hesitate to ask your project leads to get additional
input.</p>
<h2 id="C++_Version">C++ Version</h2>
<p>Currently, code should target C++17, i.e., should not use C++2x
features. The C++ version targeted by this guide will advance
(aggressively) over time.</p>
<p>Do not use
<a href="#Nonstandard_Extensions">non-standard extensions</a>.</p>
<div>Consider portability to other environments
before using features from C++14 and C++17 in your project.
</div>
<h2 id="Header_Files">Header Files</h2>
<p>In general, every <code>.cc</code> file should have an
associated <code>.h</code> file. There are some common
exceptions, such as unit tests and small <code>.cc</code> files containing
just a <code>main()</code> function.</p>
<p>Correct use of header files can make a huge difference to
the readability, size and performance of your code.</p>
<p>The following rules will guide you through the various
pitfalls of using header files.</p>
<a id="The_-inl.h_Files"></a>
<h3 id="Self_contained_Headers">Self-contained Headers</h3>
<p>Header files should be self-contained (compile on their own) and
end in <code>.h</code>. Non-header files that are meant for inclusion
should end in <code>.inc</code> and be used sparingly.</p>
<p>All header files should be self-contained. Users and refactoring
tools should not have to adhere to special conditions to include the
header. Specifically, a header should
have <a href="#The__define_Guard">header guards</a> and include all
other headers it needs.</p>
<p>Prefer placing the definitions for template and inline functions in
the same file as their declarations. The definitions of these
constructs must be included into every <code>.cc</code> file that uses
them, or the program may fail to link in some build configurations. If
declarations and definitions are in different files, including the
former should transitively include the latter. Do not move these
definitions to separately included header files (<code>-inl.h</code>);
this practice was common in the past, but is no longer allowed.</p>
<p>As an exception, a template that is explicitly instantiated for
all relevant sets of template arguments, or that is a private
implementation detail of a class, is allowed to be defined in the one
and only <code>.cc</code> file that instantiates the template.</p>
<p>There are rare cases where a file designed to be included is not
self-contained. These are typically intended to be included at unusual
locations, such as the middle of another file. They might not
use <a href="#The__define_Guard">header guards</a>, and might not include
their prerequisites. Name such files with the <code>.inc</code>
extension. Use sparingly, and prefer self-contained headers when
possible.</p>
<h3 id="The__pragma_once_Guard">The #pragma once Guard</h3>
<p>All header files should have <code class="drake">#pragma once</code><code class="nondrake">#define</code> guards to
prevent multiple inclusion.
<span class="nondrake">The format of the symbol name
should be
<code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.</p>
</span>
<p>To guarantee uniqueness, they should
be based on the full path in a project's source tree. For
example, the file <code>foo/src/bar/baz.h</code> in
project <code>foo</code> should have the following
guard:</p>
<pre>#ifndef FOO_BAR_BAZ_H_
#define FOO_BAR_BAZ_H_
...
#endif // FOO_BAR_BAZ_H_
</pre>
<p class="drake">
The advantages of using #pragma once are (1) it does not need to be updated
each time the name of the header file changes, and (2) it prevents silly
mistakes that occur when a developer copy-pastes a header file and forgets
to update its #define guard. The known drawbacks of using #pragma once,
namely the possibility of lack of compiler support and
compiler-dependent-behavior, is mitigated since Drake has
a <a href="http://drake.mit.edu/developers.html#supported-configurations">limited
set of officially supported platform configurations</a> on which correct
behavior will be
guaranteed. (<a href="https://github.com/RobotLocomotion/drake/issues/2104">#2104</a>)
</p>
<h3 id="Include_What_You_Use">Include What You Use</h3>
<p>If a source or header file refers to a symbol defined elsewhere,
the file should directly include a header file which properly intends
to provide a declaration or definition of that symbol. It should not
include header files for any other reason.
</p>
<p>Do not rely on transitive inclusions. This allows people to remove
no-longer-needed <code>#include</code> statements from their headers without
breaking clients. This also applies to related headers
- <code>foo.cc</code> should include <code>bar.h</code> if it uses a
symbol from it even if <code>foo.h</code>
includes <code>bar.h</code>.</p>
<p class="drake"><a name="iwyu_exception"/>
While we encourage you to Include What You Use (IWYU) since it improves code
transparency and readability, it will not be strictly enforced. Instead, we
enforce a “weak include” style that simply requires every symbol referenced
within a file be covered by the transitive closure of all #include
statements in the file. We decided to make this exception because (1) we can
always adopt an IWYU rule later, (2) to reduce verbosity, and (3) we don’t
have a tool to enforce IWYU at this time.
</p>
<h3 id="Forward_Declarations">Forward Declarations</h3>
<p>Avoid using forward declarations where possible.
Instead, <a href="#Include_What_You_Use">include the headers you need</a>.
</p>
<p class="definition"></p>
<p>A "forward declaration" is a declaration of an entity
without an associated definition.</p>
<pre>// In a C++ source file:
class B;
void FuncInB();
extern int variable_in_b;
ABSL_DECLARE_FLAG(flag_in_b);
</pre>
<p class="pros"></p>
<ul>
<li>Forward declarations can save compile time, as
<code>#include</code>s force the compiler to open
more files and process more input.</li>
<li>Forward declarations can save on unnecessary
recompilation. <code>#include</code>s can force
your code to be recompiled more often, due to unrelated
changes in the header.</li>
</ul>
<p class="cons"></p>
<ul>
<li>Forward declarations can hide a dependency, allowing
user code to skip necessary recompilation when headers
change.</li>
<li>A forward declaration as opposed to an #include statement
makes it difficult for automatic tooling to discover the module
defining the symbol.</li>
<li>A forward declaration may be broken by subsequent
changes to the library. Forward declarations of functions
and templates can prevent the header owners from making
otherwise-compatible changes to their APIs, such as
widening a parameter type, adding a template parameter
with a default value, or migrating to a new namespace.</li>
<li>Forward declaring symbols from namespace
<code>std::</code> yields undefined behavior.</li>
<li>It can be difficult to determine whether a forward
declaration or a full <code>#include</code> is needed.
Replacing an <code>#include</code> with a forward
declaration can silently change the meaning of
code:
<pre>// b.h:
struct B {};
struct D : B {};
// good_user.cc:
#include "b.h"
void f(B*);
void f(void*);
void test(D* x) { f(x); } // calls f(B*)
</pre>
If the <code>#include</code> was replaced with forward
decls for <code>B</code> and <code>D</code>,
<code>test()</code> would call <code>f(void*)</code>.
</li>
<li>Forward declaring multiple symbols from a header
can be more verbose than simply
<code>#include</code>ing the header.</li>
<li>Structuring code to enable forward declarations
(e.g., using pointer members instead of object members)
can make the code slower and more complex.</li>
</ul>
<p class="decision"></p>
Try to avoid forward declarations of entities
defined in another project.
<h3 id="Inline_Functions">Inline Functions</h3>
<p>Define functions inline only when they are small, say, 10
lines or fewer.</p>
<p class="definition"></p>
<p>You can declare functions in a way that allows the compiler to expand
them inline rather than calling them through the usual
function call mechanism.
<span class="drake">To achieve this, define the function in the header
(<tt>*.h</tt>) file, instead of the <tt>*.cc</tt> file.</span>
</p>
<p class="drake">Note that
<a href="https://en.cppreference.com/w/cpp/language/class_template#Explicit_instantiation">
explicit template instantiation</a> enables the use of templated classes or
functions without defining them in the header file.</p>
<p class="drake">The C++ keyword <tt>inline</tt> is a separate concept
related to linking, not function inlining. Some function definitions need
to be marked with the <tt>inline</tt> keyword to avoid linking errors related
to multiple definitions.</p>
<p class="pros"></p>
<p>Inlining a function can generate more efficient object
code, as long as the inlined function is small. Feel free
to inline accessors and mutators, and other short,
performance-critical functions.</p>
<p class="cons"></p>
<p>Overuse of inlining can actually make programs slower.
Depending on a function's size, inlining it can cause the
code size to increase or decrease. Inlining a very small
accessor function will usually decrease code size while
inlining a very large function can dramatically increase
code size. On modern processors smaller code usually runs
faster due to better use of the instruction cache.</p>
<p class="decision"></p>
<p>A decent rule of thumb is to not inline a function if
it is more than 10 lines long. Beware of destructors,
which are often longer than they appear because of
implicit member- and base-destructor calls!</p>
<p>Another useful rule of thumb: it's typically not cost
effective to inline functions with loops or switch
statements (unless, in the common case, the loop or
switch statement is never executed).</p>
<p>It is important to know that functions are not always
inlined even if they are declared as such; for example,
virtual and recursive functions are not normally inlined.
Usually recursive functions should not be inline. The
main reason for making a virtual function inline is to
place its definition in the class, either for convenience
or to document its behavior, e.g., for accessors and
mutators.</p>
<p class="drake">The use of a numerical scalar class template is not a
sufficient reason on its own to place a method definition in a header file.
When a class is templated only on its numerical scalar type, Drake provides the
<a href="https://drake.mit.edu/doxygen_cxx/group__default__scalars.html">
default scalars</a> macros to declare and define the template instantiations
that allow placing definitions into the <tt>*.cc</tt> file. These macros should
be used whenever practical, and the class's method definitions should be placed
into the <tt>*.cc</tt> file in most cases, consistent with the above rules of
thumb.</p>
<p class="drake">Example header file:</p>
<pre class="drake">#include "drake/common/default_scalars.h"
namespace sample {
template <typename T>
class MySystem final : public LeafSystem<T> {
public:
// Expensive functions such as this constructor or destructor are not inlined.
MySystem();
~MySystem() final;
// Short and inexpensive accessors can be inlined.
int size() { return get_output_port(0).size(); }
private:
// This calculation function is also expensive, and therefore isn't inlined.
void CalcFoo(const Context<T>& context, BasicVector<T>* output);
};
} // namespace sample
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::sample::MySystem)
</pre>
<p class="drake">Example cc file:</p>
<pre class="drake">#include "my_system.h"
namespace sample {
// Even though the constructor appears to be short, by virtue of implicitly
// calling the LeafSystem base class constructor it fails to meet the 10-line
// rule of thumb.
template <typename T>
MySystem<T>::MySystem() = default;
// Ditto for the destructor.
template <typename T>
MySystem<T>::~MySystem() = default;
template <typename T>
void MySystem<T>::CalcFoo(
const Context<T>& context,
BasicVector<T>* output) {
// ... (10+ lines long, etc.) ...
}
} // namespace sample
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::sample::MySystem)
</pre>
<h3 id="Names_and_Order_of_Includes">Names and Order of Includes</h3>
<p>Include headers in the following order: Related header, C system headers,
C++ standard library headers,
other libraries' headers, your project's
headers.</p>
<p class="drake">Separate each category of #include statements with a blank
line. Then, accept whatever clang-format enforces.</p>
<p>
All of a project's header files should be
listed as descendants of the project's source
directory without use of UNIX directory aliases
<code>.</code> (the current directory) or <code>..</code>
(the parent directory). For example,
<code>google-awesome-project/src/base/logging.h</code>
should be included as:</p>
<pre>#include "base/logging.h"
</pre>
<p>In <code><var>dir/foo</var>.cc</code> or
<code><var>dir/foo_test</var>.cc</code>, whose main
purpose is to implement or test the stuff in
<code><var>dir2/foo2</var>.h</code>, order your includes
as follows:</p>
<ol>
<li><code><var>dir2/foo2</var>.h</code>.</li>
<li>A blank line</li>
<li>C system headers (more precisely: headers in angle brackets with the
<code>.h</code> extension), e.g., <code><unistd.h></code>,
<code><stdlib.h></code>.</li>
<li>A blank line</li>
<li>C++ standard library headers (without file extension), e.g.,
<code><algorithm></code>, <code><cstddef></code>.</li>
<li>A blank line</li>
<div>
<li>Other libraries' <code>.h</code> files.</li>
</div>
<li>
Your project's <code>.h</code>
files.</li>
</ol>
<p>Separate each non-empty group with one blank line.</p>
<p>With the preferred ordering, if the related header
<code><var>dir2/foo2</var>.h</code> omits any necessary
includes, the build of <code><var>dir/foo</var>.cc</code>
or <code><var>dir/foo</var>_test.cc</code> will break.
Thus, this rule ensures that build breaks show up first
for the people working on these files, not for innocent
people in other packages.</p>
<p><code><var>dir/foo</var>.cc</code> and
<code><var>dir2/foo2</var>.h</code> are usually in the same
directory (e.g., <code>base/basictypes_test.cc</code> and
<code>base/basictypes.h</code>), but may sometimes be in different
directories too.</p>
<p>Note that the C headers such as <code>stddef.h</code>
are essentially interchangeable with their C++ counterparts
(<code>cstddef</code>).
<span class="nondrake">Either style is acceptable</span>
<span class="drake">Prefer <code>cstddef</code></span>, but prefer consistency
with existing code.</p>
<p>Within each section the includes should be ordered
alphabetically. Note that older code might not conform to
this rule and should be fixed when convenient.</p>
<p>For example, the includes in
<code>google-awesome-project/src/foo/internal/fooserver.cc</code>
might look like this:</p>
<pre>#include "foo/server/fooserver.h"
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "foo/server/bar.h"
</pre>
<p><b>Exception:</b></p>
<p>Sometimes, system-specific code needs
conditional includes. Such code can put conditional
includes after other includes. Of course, keep your
system-specific code small and localized. Example:</p>
<pre>#include "foo/public/fooserver.h"
#include "base/port.h" // For LANG_CXX11.
#ifdef LANG_CXX11
#include <initializer_list>
#endif // LANG_CXX11
</pre>
<h2 id="Scoping">Scoping</h2>
<h3 id="Namespaces">Namespaces</h3>
<p>With few exceptions, place code in a namespace. Namespaces
should have unique names based on the project name, and possibly
its path. Do not use <i>using-directives</i> (e.g.,
<code>using namespace foo</code>). Do not use
inline namespaces. For unnamed namespaces, see
<a href="#Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and
Static Variables</a>.
</p><p class="definition"></p>
<p>Namespaces subdivide the global scope
into distinct, named scopes, and so are useful for preventing
name collisions in the global scope.</p>
<p class="pros"></p>
<p>Namespaces provide a method for preventing name conflicts
in large programs while allowing most code to use reasonably
short names.</p>
<p>For example, if two different projects have a class
<code>Foo</code> in the global scope, these symbols may
collide at compile time or at runtime. If each project
places their code in a namespace, <code>project1::Foo</code>
and <code>project2::Foo</code> are now distinct symbols that
do not collide, and code within each project's namespace
can continue to refer to <code>Foo</code> without the prefix.</p>
<p>Inline namespaces automatically place their names in
the enclosing scope. Consider the following snippet, for
example:</p>
<pre class="neutralcode">namespace outer {
inline namespace inner {
void foo();
} // namespace inner
} // namespace outer
</pre>
<p>The expressions <code>outer::inner::foo()</code> and
<code>outer::foo()</code> are interchangeable. Inline
namespaces are primarily intended for ABI compatibility
across versions.</p>
<p class="cons"></p>
<p>Namespaces can be confusing, because they complicate
the mechanics of figuring out what definition a name refers
to.</p>
<p>Inline namespaces, in particular, can be confusing
because names aren't actually restricted to the namespace
where they are declared. They are only useful as part of
some larger versioning policy.</p>
<p>In some contexts, it's necessary to repeatedly refer to
symbols by their fully-qualified names. For deeply-nested
namespaces, this can add a lot of clutter.</p>
<p class="decision"></p>
<p>Namespaces should be used as follows:</p>
<ul>
<li>Follow the rules on <a href="#Namespace_Names">Namespace Names</a>.
</li><li>Terminate multi-line namespaces with comments as shown in the given examples.
</li><li>
<p>Namespaces wrap the entire source file after
includes,
<a href="https://gflags.github.io/gflags/">
gflags</a> definitions/declarations
and forward declarations of classes from other namespaces.</p>
<pre>// In the .h file
namespace mynamespace {
// All declarations are within the namespace scope.
// Notice the lack of indentation.
class MyClass {
public:
...
void Foo();
};
} // namespace mynamespace
</pre>
<pre>// In the .cc file
namespace mynamespace {
// Definition of functions is within scope of the namespace.
void MyClass::Foo() {
...
}
} // namespace mynamespace
</pre>
<p>More complex <code>.cc</code> files might have additional details,
like flags or using-declarations.</p>
<pre>#include "a.h"
ABSL_FLAG(bool, someflag, false, "dummy flag");
namespace mynamespace {
using ::foo::Bar;
...code for mynamespace... // Code goes against the left margin.
} // namespace mynamespace
</pre>
</li>
<li>To place generated protocol
message code in a namespace, use the
<code>package</code> specifier in the
<code>.proto</code> file. See
<a href="https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#package">
Protocol Buffer Packages</a>
for details.</li>
<li>Do not declare anything in namespace
<code>std</code>, including forward declarations of
standard library classes. Declaring entities in
namespace <code>std</code> is undefined behavior, i.e.,
not portable. To declare entities from the standard
library, include the appropriate header file.</li>
<li><p>You may not use a <i>using-directive</i>
to make all names from a namespace available.</p>
<pre class="badcode">// Forbidden -- This pollutes the namespace.
using namespace foo;
</pre>
</li>
<li><p>Do not use <i>Namespace aliases</i> at namespace scope
in header files except in explicitly marked
internal-only namespaces, because anything imported into a namespace
in a header file becomes part of the public
API exported by that file.</p>
<pre>// Shorten access to some commonly used names in .cc files.
namespace baz = ::foo::bar::baz;
</pre>
<pre>// Shorten access to some commonly used names (in a .h file).
namespace librarian {
namespace impl { // Internal, not part of the API.
namespace sidetable = ::pipeline_diagnostics::sidetable;
} // namespace impl
inline void my_inline_function() {
// namespace alias local to a function (or method).
namespace baz = ::foo::bar::baz;
...
}
} // namespace librarian
</pre>
</li><li>Do not use inline namespaces.</li>
</ul>
<h3 id="Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and Static
Variables</h3>
<p>When definitions in a <code>.cc</code> file do not need to be
referenced outside that file, place them in an unnamed
namespace or declare them <code>static</code>. Do not use either
of these constructs in <code>.h</code> files.
</p><p class="definition"></p>
<p>All declarations can be given internal linkage by placing them in unnamed
namespaces. Functions and variables can also be given internal linkage by
declaring them <code>static</code>. This means that anything you're declaring
can't be accessed from another file. If a different file declares something with
the same name, then the two entities are completely independent.</p>
<p class="decision"></p>
<p>Use of internal linkage in <code>.cc</code> files is encouraged
for all code that does not need to be referenced elsewhere.
Do not use internal linkage in <code>.h</code> files.</p>
<p>Format unnamed namespaces like named namespaces. In the
terminating comment, leave the namespace name empty:</p>
<pre>namespace {
...
} // namespace
</pre>
<h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3>
<p>Prefer placing nonmember functions in a namespace; use completely global
functions rarely. Do not use a class simply to group static members. Static
methods of a class should generally be closely related to instances of the
class or the class's static data.</p>
<p class="pros"></p>
<p>Nonmember and static member functions can be useful in
some situations. Putting nonmember functions in a
namespace avoids polluting the global namespace.</p>
<p class="cons"></p>
<p>Nonmember and static member functions may make more sense
as members of a new class, especially if they access
external resources or have significant dependencies.</p>
<p class="decision"></p>
<p>Sometimes it is useful to define a
function not bound to a class instance. Such a function
can be either a static member or a nonmember function.
Nonmember functions should not depend on external
variables, and should nearly always exist in a namespace.
Do not create classes only to group static members;
this is no different than just giving the names a
common prefix, and such grouping is usually unnecessary anyway.</p>
<p>If you define a nonmember function and it is only
needed in its <code>.cc</code> file, use
<a href="#Unnamed_Namespaces_and_Static_Variables">internal linkage</a> to limit
its scope.</p>
<h3 id="Local_Variables">Local Variables</h3>
<p>Place a function's variables in the narrowest scope
possible, and initialize variables in the declaration.</p>
<p>C++ allows you to declare variables anywhere in a
function. We encourage you to declare them in as local a
scope as possible, and as close to the first use as
possible. This makes it easier for the reader to find the
declaration and see what type the variable is and what it
was initialized to. In particular, initialization should
be used instead of declaration and assignment, e.g.,:</p>
<pre class="badcode">int i;
i = f(); // Bad -- initialization separate from declaration.
</pre>
<pre>int j = g(); // Good -- declaration has initialization.
</pre>
<pre class="badcode">std::vector<int> v;
v.push_back(1); // Prefer initializing using brace initialization.
v.push_back(2);
</pre>
<pre>std::vector<int> v = {1, 2}; // Good -- v starts initialized.
</pre>
<p>Variables needed for <code>if</code>, <code>while</code>
and <code>for</code> statements should normally be declared
within those statements, so that such variables are confined
to those scopes. E.g.:</p>
<pre>while (const char* p = strchr(str, '/')) str = p + 1;
</pre>
<p>There is one caveat: if the variable is an object, its
constructor is invoked every time it enters scope and is
created, and its destructor is invoked every time it goes
out of scope.</p>
<pre class="badcode">// Inefficient implementation:
for (int i = 0; i < 1000000; ++i) {
Foo f; // My ctor and dtor get called 1000000 times each.
f.DoSomething(i);
}
</pre>
<p>It may be more efficient to declare such a variable
used in a loop outside that loop:</p>
<pre>Foo f; // My ctor and dtor get called once each.
for (int i = 0; i < 1000000; ++i) {
f.DoSomething(i);
}
</pre>
<h3 id="Static_and_Global_Variables">Static and Global Variables</h3>
<p>Objects with
<a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration">
static storage duration</a> are forbidden unless they are
<a href="http://en.cppreference.com/w/cpp/types/is_destructible">trivially
destructible</a>. Informally this means that the destructor does not do
anything, even taking member and base destructors into account. More formally it
means that the type has no user-defined or virtual destructor and that all bases
and non-static members are trivially destructible.
Static function-local variables may use dynamic initialization.
Use of dynamic initialization for static class member variables or variables at
namespace scope is discouraged, but allowed in limited circumstances; see below
for details.</p>
<p>As a rule of thumb: a global variable satisfies these requirements if its
declaration, considered in isolation, could be <code>constexpr</code>.</p>
<p class="definition"></p>
<p>Every object has a <dfn>storage duration</dfn>, which correlates with its
lifetime. Objects with static storage duration live from the point of their
initialization until the end of the program. Such objects appear as variables at
namespace scope ("global variables"), as static data members of classes, or as
function-local variables that are declared with the <code>static</code>
specifier. Function-local static variables are initialized when control first
passes through their declaration; all other objects with static storage duration
are initialized as part of program start-up. All objects with static storage
duration are destroyed at program exit (which happens before unjoined threads
are terminated).</p>
<p>Initialization may be <dfn>dynamic</dfn>, which means that something
non-trivial happens during initialization. (For example, consider a constructor
that allocates memory, or a variable that is initialized with the current
process ID.) The other kind of initialization is <dfn>static</dfn>
initialization. The two aren't quite opposites, though: static
initialization <em>always</em> happens to objects with static storage duration
(initializing the object either to a given constant or to a representation
consisting of all bytes set to zero), whereas dynamic initialization happens
after that, if required.</p>
<p class="pros"></p>
<p>Global and static variables are very useful for a large number of
applications: named constants, auxiliary data structures internal to some
translation unit, command-line flags, logging, registration mechanisms,
background infrastructure, etc.</p>
<p class="cons"></p>
<p>Global and static variables that use dynamic initialization or have
non-trivial destructors create complexity that can easily lead to hard-to-find
bugs. Dynamic initialization is not ordered across translation units, and
neither is destruction (except that destruction
happens in reverse order of initialization). When one initialization refers to
another variable with static storage duration, it is possible that this causes
an object to be accessed before its lifetime has begun (or after its lifetime
has ended). Moreover, when a program starts threads that are not joined at exit,
those threads may attempt to access objects after their lifetime has ended if
their destructor has already run.</p>
<p class="decision"></p>
<h4>Decision on destruction</h4>
<p>When destructors are trivial, their execution is not subject to ordering at
all (they are effectively not "run"); otherwise we are exposed to the risk of
accessing objects after the end of their lifetime. Therefore, we only allow
objects with static storage duration if they are trivially destructible.
Fundamental types (like pointers and <code>int</code>) are trivially
destructible, as are arrays of trivially destructible types. Note that
variables marked with <code>constexpr</code> are trivially destructible.</p>
<pre>const int kNum = 10; // allowed
struct X { int n; };
const X kX[] = {{1}, {2}, {3}}; // allowed
void foo() {
static const char* const kMessages[] = {"hello", "world"}; // allowed
}
// allowed: constexpr guarantees trivial destructor
constexpr std::array<int, 3> kArray = {{1, 2, 3}};</pre>
<pre class="badcode">// bad: non-trivial destructor
const std::string kFoo = "foo";
// bad for the same reason, even though kBar is a reference (the
// rule also applies to lifetime-extended temporary objects)
const std::string& kBar = StrCat("a", "b", "c");