forked from google/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cppguide.html
6170 lines (4869 loc) · 201 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>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Google C++ Style Guide</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://www.google.com/favicon.ico" />
</head>
<body onload="initStyleGuide();">
<div id="content">
<h1>Google C++ Style Guide</h1>
<div class="horizontal_toc" id="tocDiv"></div>
<div class="main_body">
<h2 class="ignoreLink" id="Background">Background</h2>
<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 open-source projects developed by
Google conform to the requirements in this guide.
</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>
<div class="stylebody">
<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>
</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 unittests 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>
<div class="summary">
<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>
</div>
<div class="stylebody">
<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>
</div>
<h3 id="The__define_Guard">The #define Guard</h3>
<div class="summary">
<p>All header files should have <code>#define</code> guards to
prevent multiple inclusion. The format of the symbol name
should be
<code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.</p>
</div>
<div class="stylebody">
<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>
</div>
<h3 id="Forward_Declarations">Forward Declarations</h3>
<div class="summary">
<p>Avoid using forward declarations where possible.
Just <code>#include</code> the headers you need.</p>
</div>
<div class="stylebody">
<div class="definition">
<p>A "forward declaration" is a declaration of a class,
function, or template without an associated definition.</p>
</div>
<div class="pros">
<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>
</div>
<div class="cons">
<ul>
<li>Forward declarations can hide a dependency, allowing
user code to skip necessary recompilation when headers
change.</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>
</div>
<div class="decision">
<ul>
<li>Try to avoid forward declarations of entities
defined in another project.</li>
<li>When using a function declared in a header file,
always <code>#include</code> that header.</li>
<li>When using a class template, prefer to
<code>#include</code> its header file.</li>
</ul>
<p>Please see <a href="#Names_and_Order_of_Includes">Names and Order
of Includes</a> for rules about when to #include a header.</p>
</div>
</div>
<h3 id="Inline_Functions">Inline Functions</h3>
<div class="summary">
<p>Define functions inline only when they are small, say, 10
lines or fewer.</p>
</div>
<div class="stylebody">
<div class="definition">
<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.</p>
</div>
<div class="pros">
<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>
</div>
<div class="cons">
<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>
</div>
<div class="decision">
<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>
</div>
</div>
<h3 id="Names_and_Order_of_Includes">Names and Order of Includes</h3>
<div class="summary">
<p>Use standard order for readability and to avoid hidden
dependencies: Related header, C library, C++ library, other libraries'
<code>.h</code>, your project's <code>.h</code>.</p>
</div>
<div class="stylebody">
<p>
All of a project's header files should be
listed as descendants of the project's source
directory without use of UNIX directory shortcuts
<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>C system files.</li>
<li>C++ system files.</li>
<li>Other libraries' <code>.h</code>
files.</li>
<li>
Your project's <code>.h</code>
files.</li>
</ol>
<p>With the preferred ordering, if
<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>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>You should include all the headers that define the symbols you rely
upon, except in the unusual case of <a href="#Forward_Declarations">forward
declaration</a>. If you rely on symbols from <code>bar.h</code>,
don't count on the fact that you included <code>foo.h</code> which
(currently) includes <code>bar.h</code>: include <code>bar.h</code>
yourself, unless <code>foo.h</code> explicitly demonstrates its intent
to provide you the symbols of <code>bar.h</code>. However, any
includes present in the related header do not need to be included
again in the related <code>cc</code> (i.e., <code>foo.cc</code> can
rely on <code>foo.h</code>'s includes).</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 <hash_map>
#include <vector>
#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "foo/server/bar.h"
</pre>
<p class="exception">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>
</div>
<h2 id="Scoping">Scoping</h2>
<h3 id="Namespaces">Namespaces</h3>
<div class="summary">
<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></div>
<div class="stylebody">
<div class="definition">
<p>Namespaces subdivide the global scope
into distinct, named scopes, and so are useful for preventing
name collisions in the global scope.</p>
</div>
<div class="pros">
<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>namespace X {
inline namespace Y {
void foo();
} // namespace Y
} // namespace X
</pre>
<p>The expressions <code>X::Y::foo()</code> and
<code>X::foo()</code> are interchangeable. Inline
namespaces are primarily intended for ABI compatibility
across versions.</p>
</div>
<div class="cons">
<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>
</div>
<div class="decision">
<p>Namespaces should be used as follows:</p>
<ul>
<li>Follow the rules on <a href="#Namespace_Names">Namespace Names</a>.
</li><li>Terminate 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"
DEFINE_FLAG(bool, someflag, false, "dummy flag");
namespace a {
using ::foo::bar;
...code for a... // Code goes against the left margin.
} // namespace a
</pre>
</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>
</div>
</div>
<h3 id="Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and Static
Variables</h3>
<div class="summary">
<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></div>
<div class="stylebody">
<div class="definition">
<p>All declarations can be given internal linkage by placing them in
unnamed namespaces, and functions and variables can 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>
</div>
<div class="decision">
<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>
</div>
</div>
<h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3>
<div class="summary">
<p>Prefer placing nonmember functions in a namespace; use completely global
functions rarely. Prefer grouping functions with a namespace instead of
using a class as if it were a namespace. Static methods of a class should
generally be closely related to instances of the class or the class's static
data.</p>
</div>
<div class="stylebody">
<div class="pros">
<p>Nonmember and static member functions can be useful in
some situations. Putting nonmember functions in a
namespace avoids polluting the global namespace.</p>
</div>
<div class="cons">
<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>
</div>
<div class="decision">
<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.
Rather than creating classes only to group static member
functions which do not share static data, use
<a href="#Namespaces">namespaces</a> instead. For a header
<code>myproject/foo_bar.h</code>, for example, write</p>
<pre>namespace myproject {
namespace foo_bar {
void Function1();
void Function2();
} // namespace foo_bar
} // namespace myproject
</pre>
<p>instead of</p>
<pre class="badcode">namespace myproject {
class FooBar {
public:
static void Function1();
static void Function2();
};
} // namespace myproject
</pre>
<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>
</div>
</div>
<h3 id="Local_Variables">Local Variables</h3>
<div class="summary">
<p>Place a function's variables in the narrowest scope
possible, and initialize variables in the declaration.</p>
</div>
<div class="stylebody">
<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>
</div>
<h3 id="Static_and_Global_Variables">Static and Global Variables</h3>
<div class="summary">
<p>Variables of class type with <a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration">
static storage duration</a> are forbidden: they cause hard-to-find bugs due
to indeterminate order of construction and destruction. However, such
variables are allowed if they are <code>constexpr</code>: they have no
dynamic initialization or destruction.</p>
</div>
<div class="stylebody">
<p>Objects with static storage duration, including global
variables, static variables, static class member
variables, and function static variables, must be Plain
Old Data (POD): only ints, chars, floats, or pointers, or
arrays/structs of POD.</p>
<p>The order in which class constructors and initializers
for static variables are called is only partially
specified in C++ and can even change from build to build,
which can cause bugs that are difficult to find.
Therefore in addition to banning globals of class type,
we do not allow non-local static variables to be initialized
with the result of a function, unless that function (such
as getenv(), or getpid()) does not itself depend on any
other globals. However, a static POD variable within
function scope may be initialized with the result of a
function, since its initialization order is well-defined
and does not occur until control passes through its
declaration.</p>
<p>Likewise, global and static variables are destroyed
when the program terminates, regardless of whether the
termination is by returning from <code>main()</code> or
by calling <code>exit()</code>. The order in which
destructors are called is defined to be the reverse of
the order in which the constructors were called. Since
constructor order is indeterminate, so is destructor
order. For example, at program-end time a static variable
might have been destroyed, but code still running
— perhaps in another thread
— tries to access it and fails. Or the
destructor for a static <code>string</code> variable
might be run prior to the destructor for another variable
that contains a reference to that string.</p>
<p>One way to alleviate the destructor problem is to
terminate the program by calling
<code>quick_exit()</code> instead of <code>exit()</code>.
The difference is that <code>quick_exit()</code> does not
invoke destructors and does not invoke any handlers that
were registered by calling <code>atexit()</code>. If you
have a handler that needs to run when a program
terminates via <code>quick_exit()</code> (flushing logs,
for example), you can register it using
<code>at_quick_exit()</code>. (If you have a handler that
needs to run at both <code>exit()</code> and
<code>quick_exit()</code>, you need to register it in
both places.)</p>
<p>As a result we only allow static variables to contain
POD data. This rule completely disallows
<code>std::vector</code> (use C arrays instead), or
<code>string</code> (use <code>const char []</code>).</p>
<p>If you need a static or global
variable of a class type, consider initializing a pointer
(which will never be freed), from either your main()
function or from pthread_once(). Note that this must be a
raw pointer, not a "smart" pointer, since the smart
pointer's destructor will have the order-of-destructor
issue that we are trying to avoid.</p>
</div>
<h2 id="Classes">Classes</h2>
<p>Classes are the fundamental unit of code in C++. Naturally,
we use them extensively. This section lists the main dos and
don'ts you should follow when writing a class.</p>
<h3 id="Doing_Work_in_Constructors">Doing Work in Constructors</h3>
<div class="summary">
<p>Avoid virtual method calls in constructors, and avoid
initialization that can fail if you can't signal an error.</p>
</div>
<div class="stylebody">
<div class="definition">
<p>It is possible to perform arbitrary initialization in the body
of the constructor.</p>
</div>
<div class="pros">
<ul>
<li>No need to worry about whether the class has been initialized or
not.</li>
<li>Objects that are fully initialized by constructor call can
be <code>const</code> and may also be easier to use with standard containers
or algorithms.</li>
</ul>
</div>
<div class="cons">
<ul>
<li>If the work calls virtual functions, these calls
will not get dispatched to the subclass
implementations. Future modification to your class can
quietly introduce this problem even if your class is
not currently subclassed, causing much confusion.</li>
<li>There is no easy way for constructors to signal errors, short of
crashing the program (not always appropriate) or using exceptions
(which are <a href="#Exceptions">forbidden</a>).</li>
<li>If the work fails, we now have an object whose initialization
code failed, so it may be an unusual state requiring a <code>bool
IsValid()</code> state checking mechanism (or similar) which is easy
to forget to call.</li>
<li>You cannot take the address of a constructor, so whatever work
is done in the constructor cannot easily be handed off to, for
example, another thread.</li>
</ul>
</div>
<div class="decision">
<p>Constructors should never call virtual functions. If appropriate
for your code
,
terminating the program may be an appropriate error handling
response. Otherwise, consider a factory function
or <code>Init()</code> method. Avoid <code>Init()</code> methods on objects with
no other states that affect which public methods may be called
(semi-constructed objects of this form are particularly hard to work
with correctly).</p>
</div>
</div>
<a id="Explicit_Constructors"></a>
<h3 id="Implicit_Conversions">Implicit Conversions</h3>
<div class="summary">
<p>Do not define implicit conversions. Use the <code>explicit</code>
keyword for conversion operators and single-argument
constructors.</p>
</div>
<div class="stylebody">