forked from google/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cppguide.html
5817 lines (4515 loc) · 179 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>
</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 the main development language 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>One way in which we keep the code base manageable is by
enforcing <em>consistency</em>. It is very
important that any
programmer be able to look at
another's code and quickly understand it. Maintaining a uniform
style and following conventions means that we can more easily
use "pattern-matching" to infer what various symbols are and
what invariants are true about them. Creating common, required
idioms and patterns makes code much easier to understand. In
some cases there might be good arguments for changing certain
style rules, but we nonetheless keep things as they are in
order to preserve consistency.</p>
<p>Another issue this guide addresses is that of C++ feature
bloat. C++ is a huge language with many advanced features. In
some cases we constrain, or even ban, use of certain features.
We do this to keep code simple and to avoid the various common
errors and problems that these features can cause. This guide
lists these features and explains why their use is
restricted.</p>
<p> 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>
<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 and end in <code>.h</code>. Files that
are meant for textual inclusion, but are not headers, should end in
<code>.inc</code>. Separate <code>-inl.h</code> headers are disallowed.</p>
</div>
<div class="stylebody">
<p>All header files should be self-contained. In other
words, users and refactoring tools should not have to adhere to special
conditions in order to include the header. Specifically, a
header should have <a href="#The__define_Guard">header guards</a>,
should include all other headers it needs, and should not require any
particular symbols to be defined.</p>
<p>There are rare cases where a file is not meant to be self-contained, but
instead is meant to be textually included at a specific point in the code.
Examples are files that need to be included multiple times or
platform-specific extensions that essentially are part of other headers. Such
files should use the file extension <code>.inc</code>.</p>
<p>If a template or inline function is declared in a <code>.h</code> file,
define it in that same file. 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. Do not move these
definitions to separate <code>-inl.h</code> files.</p>
<p>As an exception, a function template that is explicitly
instantiated for all relevant sets of template arguments, or
that is a private member of a class, may
be defined in the only <code>.cc</code> file that
instantiates the template.</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>You may forward declare ordinary classes in order to avoid
unnecessary <code>#include</code>s.</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.
<code>#include</code> lines can often be replaced with
forward declarations of whatever symbols are actually
used by the client code.</p>
</div>
<div class="pros">
<ul>
<li>Unnecessary <code>#include</code>s force the
compiler to open more files and process more
input.</li>
<li>They can also force your code to be recompiled more
often, due to changes in the header.</li>
</ul>
</div>
<div class="cons">
<ul>
<li>It can be difficult to determine the correct form
of a forward declaration in the presence of features
like templates, typedefs, default parameters, and using
declarations.</li>
<li>It can be difficult to determine whether a forward
declaration or a full <code>#include</code> is needed
for a given piece of code, particularly when implicit
conversion operations are involved. In extreme cases,
replacing an <code>#include</code> with a forward
declaration can silently change the meaning of
code.</li>
<li>Forward declaring multiple symbols from a header
can be more verbose than simply
<code>#include</code>ing the header.</li>
<li>Forward declarations of functions and templates can
prevent the header owners from making
otherwise-compatible changes to their APIs; for
example, widening a parameter type, or adding a
template parameter with a default value.</li>
<li>Forward declaring symbols from namespace
<code>std::</code> usually yields undefined
behavior.</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>
<li>The practical efficiency benefits of forward
declarations are unproven.</li>
</ul>
</div>
<div class="decision">
<ul>
<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>
<li>When using an ordinary class, relying on a forward
declaration is OK, but be wary of situations where a
forward declaration may be insufficient or incorrect;
when in doubt, just <code>#include</code> the
appropriate header.</li>
<li>Do not replace data members with pointers just to
avoid an <code>#include</code>.</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 less.</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="Function_Parameter_Ordering">Function Parameter Ordering</h3>
<div class="summary">
<p>When defining a function, parameter order is: inputs, then
outputs.</p>
</div>
<div class="stylebody">
<p>Parameters to C/C++ functions are either input to the
function, output from the function, or both. Input
parameters are usually values or <code>const</code>
references, while output and input/output parameters will
be non-<code>const</code> pointers. When ordering
function parameters, put all input-only parameters before
any output parameters. In particular, do not add new
parameters to the end of the function just because they
are new; place new input-only parameters before the
output parameters.</p>
<p>This is not a hard-and-fast rule. Parameters that are
both input and output (often classes/structs) muddy the
waters, and, as always, consistency with related
functions may require you to bend the rule.</p>
</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 cases 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>Unnamed namespaces in <code>.cc</code> files are
encouraged. With named namespaces, choose the name based on
the
project, and possibly its
path. Do not use a <i>using-directive</i>.
Do not use inline namespaces.</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 (hierarchical) axis of naming, in
addition to the (also hierarchical) name axis provided by
classes.</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.</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();
}
}
</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 provide an
additional (hierarchical) axis of naming, in addition to
the (also hierarchical) name axis provided by
classes.</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>Use of unnamed namespaces in header files can easily
cause violations of the C++ One Definition Rule
(ODR).</p>
</div>
<div class="decision">
<p>Use namespaces according to the policy described
below. Terminate namespaces with comments as shown in the
given examples.</p>
</div>
<h4 class="stylepoint_subsection">Unnamed Namespaces</h4>
<ul>
<li>
<p>Unnamed namespaces are allowed and even encouraged
in <code>.cc</code> files, to avoid link time naming
conflicts:</p>
<pre>namespace { // This is in a .cc file.
// The content of a namespace is not indented.
//
// This function is guaranteed not to generate a colliding symbol
// with other symbols at link time, and is only visible to
// callers in this .cc file.
bool UpdateInternals(Frobber* f, int newval) {
...
}
} // namespace
</pre>
<p>However, file-scope declarations that are
associated with a particular class may be declared in
that class as types, static data members or static
member functions rather than as members of an unnamed
namespace.</p>
</li>
<li>Do not use unnamed namespaces in <code>.h</code>
files.</li>
</ul>
<h4 class="stylepoint_subsection">Named Namespaces</h4>
<p>Named namespaces should be used as follows:</p>
<ul>
<li>
<p>Namespaces wrap the entire source file after
includes,
<a href="http://google-gflags.googlecode.com/">
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>The typical <code>.cc</code> file might have more
complex detail, including the need to reference
classes in other namespaces.</p>
<pre>#include "a.h"
DEFINE_bool(someflag, false, "dummy flag");
class C; // Forward declaration of class C in the global namespace.
namespace a { class A; } // Forward declaration of a::A.
namespace b {
...code for b... // Code goes against the left margin.
} // namespace b
</pre>
</li>
<li>Do not declare anything in namespace
<code>std</code>, not even 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>You may use a <i>using-declaration</i>
anywhere in a <code>.cc</code> file, and in functions,
methods or classes in <code>.h</code> files.</p>
<pre>// OK in .cc files.
// Must be in a function, method or class in .h files.
using ::foo::bar;
</pre>
</li>
<li><p>Namespace aliases are allowed anywhere in a <code>
.cc</code> file, anywhere inside the named namespace
that wraps an entire <code>.h</code> file, and in
functions and methods.</p>
<pre>// Shorten access to some commonly used names in .cc files.
namespace fbz = ::foo::bar::baz;
// Shorten access to some commonly used names (in a .h file).
namespace librarian {
// The following alias is available to all files including
// this header (in namespace librarian):
// alias names should therefore be chosen consistently
// within a project.
namespace pd_s = ::pipeline_diagnostics::sidetable;
inline void my_inline_function() {
// namespace alias local to a function (or method).
namespace fbz = ::foo::bar::baz;
...
}
} // namespace librarian
</pre>
<p>Note that an alias in a .h file is visible to
everyone #including that file, so public headers
(those available outside a project) and headers
transitively #included by them, should avoid defining
aliases, as part of the general goal of keeping
public APIs as small as possible.</p>
</li>
<li>Do not use inline namespaces.</li>
</ul>
</div>
<h3 id="Nested_Classes">Nested Classes</h3>
<div class="summary">
<p>Although you may use public nested classes when they are
part of an interface, consider a <a href="#Namespaces">namespace</a>
to keep declarations out of the global scope.</p>
</div>
<div class="stylebody">
<div class="definition">
<p>A class can define another class within it; this is also
called a <i>member class</i>.</p>
<pre>class Foo {
private:
// Bar is a member class, nested within Foo.
class Bar {
...
};
};
</pre>
</div>
<div class="pros">
<p>This is useful when the nested (or member) class is only
used by the enclosing class; making it a member puts it
in the enclosing class scope rather than polluting the
outer scope with the class name. Nested classes can be
forward declared within the enclosing class and then
defined in the <code>.cc</code> file to avoid including
the nested class definition in the enclosing class
declaration, since the nested class definition is usually
only relevant to the implementation.</p>
</div>
<div class="cons">
<p>Nested classes can be forward-declared only within the
definition of the enclosing class. Thus, any header file
manipulating a <code>Foo::Bar*</code> pointer will have
to include the full class declaration for
<code>Foo</code>.</p>
</div>
<div class="decision">
<p>Do not make nested classes public unless they are
actually part of the interface, e.g., a class that holds a
set of options for some method. </p>
</div>
</div>
<h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3>
<div class="summary">
<p>Prefer nonmember functions within a namespace or static
member functions to global functions; use completely global
functions rarely.</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, or even necessary, 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.</p>
<p>Functions defined in the same compilation unit as
production classes may introduce unnecessary coupling and
link-time dependencies when directly called from other
compilation units; static member functions are
particularly susceptible to this. Consider extracting a
new class, or placing the functions in a namespace
possibly in a separate library.</p>
<p>If you must define a nonmember function and it is only
needed in its <code>.cc</code> file, use an unnamed
<a href="#Namespaces">namespace</a> or
<code>static</code> linkage (eg <code>static int Foo()
{...}</code>) 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">vector<int> v;
v.push_back(1); // Prefer initializing using brace initialization.
v.push_back(2);
</pre>
<pre>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>Static or global variables of class type 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 static POD 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. (This prohibition does not apply to a static
variable within function scope, 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>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 doing complex initialization in constructors (in
particular, initialization that can fail or that requires
virtual method calls).</p>
</div>
<div class="stylebody">
<div class="definition">
<p>It is possible to perform initialization in the body
of the constructor.</p>
</div>
<div class="pros">
<p>Convenience in typing. No need to worry about whether the
class has been initialized or not.</p>
</div>
<div class="cons">
<p>The problems with doing work in constructors are:</p>
<ul>
<li>There is no easy way for constructors to signal
errors, short of 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
indeterminate state.</li>
<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>If someone creates a global variable of this type
(which is against the rules, but still), the
constructor code will be called before
<code>main()</code>, possibly breaking some implicit
assumptions in the constructor code. For instance,
<a href="http://google-gflags.googlecode.com/">gflags</a>
will not yet have been initialized.</li>
</ul>
</div>
<div class="decision">
<p>Constructors should never call virtual functions or
attempt to raise non-fatal failures. If your object requires
non-trivial initialization, consider using
a factory function or <code>Init()</code>
method.</p>
</div>
</div>
<h3 id="Initialization">Initialization</h3>
<div class="summary">
<p>If your class defines member variables, you must provide an
in-class initializer for every member variable or write a
constructor (which can be a default constructor). If you do
not declare any constructors yourself then the compiler
will generate a default constructor for you, which may
leave some fields uninitialized or initialized to
inappropriate values.</p>
</div>
<div class="stylebody">
<div class="definition">
<p>The default constructor is called when we
<code>new</code> a class object with no arguments. It is always
called when calling <code>new[]</code> (for arrays). In-class
member initialization means declaring a member variable using a
construction like <code>int count_ = 17;</code> or
<code>string name_{"abc"};</code>, as opposed to just
<code>int count_;</code> or <code>string name_;</code>.</p>
</div>