-
Notifications
You must be signed in to change notification settings - Fork 2
/
cppguide.xml
2940 lines (2762 loc) · 109 KB
/
cppguide.xml
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
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
<GUIDE title="OpenGeoSys C++ Style Guide">
<p>
This styleguide is derived from the <a href="http://code.google.com/p/google-styleguide/">Google C++ Style Guide</a> and is hosted on <a href="https://github.com/ufz/styleguide">Github</a>. Some <a href="https://github.com/ufz/styleguide/compare/9df0dce4fa1441f9de7ff99760c61e01b6d3b79c...gh-pages">modifications</a> were made to match the <a href="http://www.opengeosys.net" target="blank">OpenGeoSys</a> development needs. The original authors are Benjy Weinberger, Craig Silverstein, Gregory Eitzmann, Mark Mentovai and Tashana Landray.
</p>
<CATEGORY title="Most important rules to remember">
<ul>
<li><strong>Never</strong> use global variables. <a href="#Global_variables">More…</a></li>
<li>Give <strong>descriptive names</strong> to functions, variables, and file names; eschew abbreviation. <a href="#Naming">More…</a>
<ul>
<li>Variable names start lowercase and then camel case. Class member
variables start with an underscore.</li>
<li>Regular functions or class methods start lowercase an then camel case.</li>
</ul></li>
<li>Define only <strong>one class per header file</strong>. The file name must match the
class that is defined in the file. <a href="#Header_Files">More…</a></li>
<li><strong>Document</strong> your code. <a href="#Comments">More…</a></li>
</ul>
</CATEGORY>
<OVERVIEW>
<CATEGORY title="Important Note">
<STYLEPOINT title="Displaying Hidden Details in this Guide">
<SUMMARY>
This style guide contains many details that are initially
hidden from view. They are marked by the triangle icon, which you
see here on your left. Click it now.
You should see "Hooray" appear below.
</SUMMARY>
<BODY>
<p>
Hooray! Now you know you can expand points to get more
details. Alternatively, there's an "expand all" at the
top of this document.
</p>
</BODY>
</STYLEPOINT>
</CATEGORY>
<CATEGORY title="Automatic code styling">
<p>
This guide comes with a <a HREF="http://ufz.github.com/styleguide/uncrustify.cfg">
configuration file</a> for the <a HREF="http://uncrustify.sourceforge.net/">
uncrustify</a> automatic code styler. With this tool you can restyle your source
code according to this styleguide. The config file is not finished yet. For
creating the config file the <a HREF="http://universalindent.sourceforge.net/">
UniversalIndentGUI</a> was used. See
<a HREF="https://github.com/ufz/styleguide/blob/gh-pages/README.md">this link</a>
for instructions how to apply the formatting to your code.
</p>
</CATEGORY>
</OVERVIEW>
<CATEGORY title="Header Files">
<p>
In general, every <code>.cpp</code> file should have an associated
<code>.h</code> file. There are some common exceptions, such as
unittests and small <code>.cpp</code> files containing just a
<code>main()</code> function. There is only one class per header file.
</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>
<STYLEPOINT title="The #define Guard">
<SUMMARY>
All header files should have <code>#define</code> guards to
prevent multiple inclusion. The format of the symbol name
should be
<code><i><FILENAME_WITHOUT_ENDING></i>_H</code>.
</SUMMARY>
<BODY>
<p>
Every file in a project should be named unique so it is
sufficient to only use the filename. For example, the file
<code>Foo.h</code> should
have the following guard:
</p>
<CODE_SNIPPET>
#ifndef FOO_H
#define FOO_H
...
#endif // FOO_H
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Header File Dependencies">
<SUMMARY>
Don't use an <code>#include</code> when a forward declaration
would suffice.
</SUMMARY>
<BODY>
<p>
When you include a header file you introduce a dependency that
will cause your code to be recompiled whenever the header file
changes. If your header file includes other header files, any
change to those files will cause any code that includes your
header to be recompiled. Therefore, we prefer to minimize
includes, particularly includes of header files in other
header files.
</p>
<p>
You can significantly reduce the number of header files you
need to include in your own header files by using forward
declarations. For example, if your header file uses the
<code>MyClass</code> class in ways that do not require access to
the declaration of the <code>MyClass</code> class, your header
file can just forward declare <code>class MyClass;</code> instead
of having to <code>#include "MyClass.h"</code>. Note the special
notation of classes inside namespaces.
</p>
<CODE_SNIPPET>
class MyClass; // Forward declaration
namespace MyNamespace { class A; } // Forward declaration of MyNamespace::A
</CODE_SNIPPET>
<p>instead of</p>
<BAD_CODE_SNIPPET>
include "MyClass.h" // Bad include
include "A.h" // Bad include
</BAD_CODE_SNIPPET>
<p>
Never forward declare somethin the <code>std</code> namespace.
</p>
<p>
How can we use a class <code>Foo</code> in a header file
without access to its definition?
</p>
<ul>
<li> We can declare data members of type <code>Foo*</code> or
<code>Foo&</code>.
</li>
<li> We can declare (but not define) functions with arguments,
and/or return values, of type <code>Foo</code>. (One
exception is if an argument <code>Foo</code>
or <code>const Foo&</code> has a
non-<code>explicit</code>, one-argument constructor,
in which case we need the full definition to support
automatic type conversion.)
</li>
<li> We can declare static data members of type
<code>Foo</code>. This is because static data members
are defined outside the class definition.
</li>
</ul>
<p>
On the other hand, you must include the header file for
<code>Foo</code> if your class subclasses <code>Foo</code> or
has a data member of type <code>Foo</code>.
</p>
<p>
Of course, <code>.cpp</code> files typically do require the
definitions of the classes they use, and usually have to
include several header files.
</p>
<SUBSECTION title="Note:">
If you use a symbol <code>Foo</code> in your source file, you
should bring in a definition for <code>Foo</code> yourself,
either via an #include or via a forward declaration. Do not
depend on the symbol being brought in transitively via headers
not directly included.
</SUBSECTION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Inline Functions">
<SUMMARY>
Define functions inline only when they are small, say, 1-2 lines.
Trust the compiler in doing optimizations.
</SUMMARY>
<BODY>
<DEFINITION>
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.
</DEFINITION>
<PROS>
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.
</PROS>
<CONS>
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. Also modern compiler do a very good
job on optimizing code.
</CONS>
<DECISION>
<p>
Because of compiler doing optimizations you do not have to
care that much about inlining. The compiler often does this
for you when useful. Otherwise a decent rule of thumb is to
not inline a function if it is
more than 2 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>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Function Parameter Ordering">
<SUMMARY>
When defining a function, parameter order is: inputs,
then outputs.
</SUMMARY>
<BODY>
<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>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Names and Order of Includes">
<SUMMARY>
Use standard order for readability and to avoid hidden
dependencies: (class own header file), C library, C++ library,
other libraries' <code>.h</code>, your
project's
<code>.h</code>.
</SUMMARY>
<BODY>
<p>
All of a project's header files should be
listed as only the filename itself.
<code>Logging.h</code>
should be included as
</p>
<CODE_SNIPPET>
#include "Logging.h"
</CODE_SNIPPET>
<p>
In <code><var>Foo</var>.cpp</code> order your includes as
follows:
</p>
<ol>
<li> <code><var>Foo</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>
The preferred ordering reduces hidden dependencies. We want
every header file to be compilable on its own. The easiest
way to achieve this is to make sure that every one of them is
the first <code>.h</code> file <code>#include</code>d in some
<code>.cpp</code>.
</p>
<p>
Within each section it is nice to order the includes
alphabetically.
</p>
<p>
For example, the includes in
<code>Fooserver.cpp</code>
might look like this:
</p>
<CODE_SNIPPET>
#include "Fooserver.h"
#include <sys/types.h>
#include <unistd.h>
#include <hash_map>
#include <vector>
#include "Basictypes.h"
#include "CommandlineFlags.h"
#include "Bar.h"
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
</CATEGORY>
<CATEGORY title="Scoping">
<STYLEPOINT title="Namespaces">
<SUMMARY>
Choose the name of the namespace based on the project component
it belongs to.
Do not use a <SYNTAX>using-directive</SYNTAX> in header files.
</SUMMARY>
<BODY>
<DEFINITION>
Namespaces subdivide the global scope into distinct, named
scopes, and so are useful for preventing name collisions in
the global scope.
</DEFINITION>
<PROS>
<p>
Namespaces provide a (hierarchical) axis of naming, in
addition to the (also hierarchical) name axis provided by
classes.
</p>
</PROS>
<DECISION>
<p>
Use namespaces according to the policy described below.
</p>
<SUBSECTION title="Named Namespaces">
<p>
Named namespaces should be used as follows:
</p>
<ul>
<li> 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:
<CODE_SNIPPET>
// 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
</CODE_SNIPPET>
<CODE_SNIPPET>
// In the .cpp file
namespace MyNamespace
{
// Definition of functions is within scope of the namespace.
void MyClass::foo()
{
...
}
} // namespace MyNamespace
</CODE_SNIPPET>
</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> You may use a <SYNTAX>using-declaration</SYNTAX>
anywhere in a <code>.cpp</code> file, and in functions,
methods or classes in <code>.h</code> files.
<CODE_SNIPPET>
// OK in .cpp files.
using Foo;
</CODE_SNIPPET>
</li>
</ul>
</SUBSECTION>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Nonmember, Static Member, and Global Functions">
<SUMMARY>
Prefer nonmember functions within a namespace or static member
functions to global functions; never use completely global functions.
</SUMMARY>
<BODY>
<PROS>
Nonmember and static member functions can be useful in some
situations. Putting nonmember functions in a namespace avoids
polluting the global namespace.
</PROS>
<CONS>
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.
</CONS>
<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>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Local Variables">
<SUMMARY>
Place a function's variables in the narrowest scope possible,
and initialize variables in the declaration.
</SUMMARY>
<BODY>
<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>
<BAD_CODE_SNIPPET>
int i;
i = f(); // Bad -- initialization separate from declaration.
</BAD_CODE_SNIPPET>
<CODE_SNIPPET>
int j = g(); // Good -- declaration has initialization.
</CODE_SNIPPET>
<p>
Note that gcc implements <code>for (int i = 0; i
< 10; ++i)</code> correctly (the scope of <code>i</code> is
only the scope of the <code>for</code> loop), so you can then
reuse <code>i</code> in another <code>for</code> loop in the
same scope. It also correctly scopes declarations in
<code>if</code> and <code>while</code> statements, e.g.
</p>
<CODE_SNIPPET>
while (const char* p = strchr(str, '/')) str = p + 1;
</CODE_SNIPPET>
<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>
<BAD_CODE_SNIPPET>
// Inefficient implementation:
for (int i = 0; i < 1000000; ++i) {
Foo f; // My ctor and dtor get called 1000000 times each.
f.doSomething(i);
}
</BAD_CODE_SNIPPET>
<p>
It may be more efficient to declare such a variable used in a
loop outside that loop:
</p>
<CODE_SNIPPET>
Foo f; // My ctor and dtor get called once each.
for (int i = 0; i < 1000000; ++i)
f.doSomething(i);
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Global variables">
<SUMMARY>
NEVER use global variables! Period.
</SUMMARY>
<BODY>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Static Variables">
<SUMMARY>
Static variables of class type are forbidden: they cause
hard-to-find bugs due to indeterminate order of construction and
destruction.
</SUMMARY>
<BODY>
<p>
Objects with static storage duration, including
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.
</p>
<p>
Likewise, 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 'string'
variable might be run prior to the destructor for another variable that
contains a reference to that string.
</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 variable of a class type, consider
initializing a pointer (which will never be freed), from either your
main() function or from pthread_once().
</p>
</BODY>
</STYLEPOINT>
</CATEGORY>
<CATEGORY title="Classes">
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.
<STYLEPOINT title="Doing Work in Constructors">
<SUMMARY>
In general, constructors should merely set member variables to their
initial values. Any complex initialization should go in an explicit
<code>init()</code> method.
</SUMMARY>
<BODY>
<DEFINITION>
It is possible to perform initialization in the body of the
constructor.
</DEFINITION>
<PROS>
Convenience in typing. No need to worry about whether the
class has been initialized or not.
</PROS>
<CONS>
The problems with doing work in constructors are:
<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>
</CONS>
<DECISION>
If your object requires non-trivial initialization, consider
having an explicit <code>init()</code> method. In particular,
constructors should not call virtual functions, attempt to raise
errors, access potentially uninitialized global variables, etc.
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Default Constructors">
<SUMMARY>
You must define a default constructor if your class defines
member variables and has no other constructors. Otherwise the
compiler will do it for you, badly.
</SUMMARY>
<BODY>
<DEFINITION>
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).
</DEFINITION>
<PROS>
Initializing structures by default, to hold "impossible"
values, makes debugging much easier.
</PROS>
<CONS>
Extra work for you, the code writer.
</CONS>
<DECISION>
<p>
If your class defines member variables and has no other
constructors you must define a default constructor (one that
takes no arguments). It should preferably initialize the
object in such a way that its internal state is consistent
and valid.
</p>
<p>
The reason for this is that if you have no other
constructors and do not define a default constructor, the
compiler will generate one for you. This compiler
generated constructor may not initialize your object
sensibly.
</p>
<p>
If your class inherits from an existing class but you add no
new member variables, you are not required to have a default
constructor.
</p>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Explicit Constructors">
<SUMMARY>
Use the C++ keyword <code>explicit</code> for constructors with
one argument.
</SUMMARY>
<BODY>
<DEFINITION>
Normally, if a constructor takes one argument, it can be used
as a conversion. For instance, if you define
<code>Foo::Foo(string name)</code> and then pass a string to a
function that expects a <code>Foo</code>, the constructor will
be called to convert the string into a <code>Foo</code> and
will pass the <code>Foo</code> to your function for you. This
can be convenient but is also a source of trouble when things
get converted and new objects created without you meaning them
to. Declaring a constructor <code>explicit</code> prevents it
from being invoked implicitly as a conversion.
</DEFINITION>
<PROS>
Avoids undesirable conversions.
</PROS>
<CONS>
None.
</CONS>
<DECISION>
<p>
We require all single argument constructors to be
explicit. Always put <code>explicit</code> in front of
one-argument constructors in the class definition:
<code>explicit Foo(string name);</code>
</p>
<p>
The exception is copy constructors, which, in the rare
cases when we allow them, should probably not be
<code>explicit</code>.
Classes that are intended to be
transparent wrappers around other classes are also
exceptions.
Such exceptions should be clearly marked with comments.
</p>
<p>
Finally, constructors that take only an initializer_list may be
non-explicit. This is to permit construction of your type using the
assigment form for brace init lists (i.e. <code>MyType m = {1, 2}
</code>).
</p>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Copy Constructors">
<SUMMARY>
Provide a copy constructor and assignment operator only when necessary.
Otherwise, disable them with <code>DISALLOW_COPY_AND_ASSIGN</code>.
</SUMMARY>
<BODY>
<DEFINITION>
The copy constructor and assignment operator are used to create copies
of objects. The copy constructor is implicitly invoked by the
compiler in some situations, e.g. passing objects by value.
</DEFINITION>
<PROS>
Copy constructors make it easy to copy objects. STL
containers require that all contents be copyable and
assignable. Copy constructors can be more efficient than
<code>CopyFrom()</code>-style workarounds because they combine
construction with copying, the compiler can elide them in some
contexts, and they make it easier to avoid heap allocation.
</PROS>
<CONS>
Implicit copying of objects in C++ is a rich source of bugs
and of performance problems. It also reduces readability, as
it becomes hard to track which objects are being passed around
by value as opposed to by reference, and therefore where
changes to an object are reflected.
</CONS>
<DECISION>
<p>
Few classes need to be copyable. Most should have neither a
copy constructor nor an assignment operator. In many situations,
a pointer or reference will work just as well as a copied value,
with better performance. For example, you can pass function
parameters by reference or pointer instead of by value, and you can
store pointers rather than objects in an STL container.
</p>
<p>
If your class needs to be copyable, prefer providing a copy method,
such as <code>CopyFrom()</code> or <code>Clone()</code>, rather than
a copy constructor, because such methods cannot be invoked
implicitly. If a copy method is insufficient in your situation
(e.g. for performance reasons, or because your class needs to be
stored by value in an STL container), provide both a copy
constructor and assignment operator.
</p>
<p>
If your class does not need a copy constructor or assignment
operator, you must explicitly disable them.
To do so, add dummy declarations for the copy constructor and
assignment operator in the <code>private:</code> section of your
class, but do not provide any corresponding definition (so that
any attempt to use them results in a link error).
</p>
<p>
For convenience, a <code>DISALLOW_COPY_AND_ASSIGN</code> macro
can be used:
</p>
<CODE_SNIPPET>
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
</CODE_SNIPPET>
<p>
Then, in <code>class Foo</code>:
</p>
<CODE_SNIPPET>
class Foo
{
public:
Foo(int f);
~Foo();
private:
DISALLOW_COPY_AND_ASSIGN(Foo);
};
</CODE_SNIPPET>
<p>
</p>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Structs vs. Classes">
<SUMMARY>
Use a <code>struct</code> only for passive objects that carry data;
everything else is a <code>class</code>.
</SUMMARY>
<BODY>
<p>
The <code>struct</code> and <code>class</code> keywords behave
almost identically in C++. We add our own semantic meanings
to each keyword, so you should use the appropriate keyword for
the data-type you're defining.
</p>
<p>
<code>structs</code> should be used for passive objects that carry
data, and may have associated constants, but lack any functionality
other than access/setting the data members. The
accessing/setting of fields is done by directly accessing the
fields rather than through method invocations. Methods should
not provide behavior but should only be used to set up the
data members, e.g., constructor, destructor,
<code>Initialize()</code>, <code>Reset()</code>,
<code>Validate()</code>.
</p>
<p>
If more functionality is required, a <code>class</code> is more
appropriate. If in doubt, make it a <code>class</code>.
</p>
<p>
For consistency with STL, you can use <code>struct</code>
instead of <code>class</code> for functors and traits.
</p>
<p>
Note that member variables in structs and classes have
<a HREF="#Variable_Names">different naming rules</a>.
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Inheritance">
<SUMMARY>
Composition is often more appropriate than inheritance. When
using inheritance, make it <code>public</code>.
</SUMMARY>
<BODY>
<DEFINITION>
When a sub-class inherits from a base class, it includes the
definitions of all the data and operations that the parent
base class defines. In practice, inheritance is used in two
major ways in C++: implementation inheritance, in which
actual code is inherited by the child, and <A HREF="#Interfaces">interface inheritance</A>, in which only
method names are inherited.
</DEFINITION>
<PROS>
Implementation inheritance reduces code size by re-using the
base class code as it specializes an existing type. Because
inheritance is a compile-time declaration, you and the
compiler can understand the operation and detect errors.
Interface inheritance can be used to programmatically enforce
that a class expose a particular API. Again, the compiler
can detect errors, in this case, when a class does not define
a necessary method of the API.
</PROS>
<CONS>
For implementation inheritance, because the code implementing
a sub-class is spread between the base and the sub-class, it
can be more difficult to understand an implementation. The
sub-class cannot override functions that are not virtual, so
the sub-class cannot change implementation. The base class
may also define some data members, so that specifies physical
layout of the base class.
</CONS>
<DECISION>
<p>
All inheritance should be <code>public</code>.
</p>
<p>
Do not overuse implementation inheritance. Composition is
often more appropriate. Try to restrict use of inheritance
to the "is-a" case: <code>Bar</code> subclasses
<code>Foo</code> if it can reasonably be said that
<code>Bar</code> "is a kind of" <code>Foo</code>.
</p>
<p>
Make your destructor <code>virtual</code> if necessary. If
your class has virtual methods, its destructor
should be virtual.
</p>
<p>
Limit the use of <code>protected</code> to those member
functions that might need to be accessed from subclasses.
Note that <a href="#Access_Control">data members should
be private</a>.
</p>
<p>
When redefining an inherited virtual function, explicitly
declare it <code>virtual</code> in the declaration of the
derived class. Rationale: If <code>virtual</code> is
omitted, the reader has to check all ancestors of the
class in question to determine if the function is virtual
or not.
</p>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Multiple Inheritance">
<SUMMARY>
Only very rarely is multiple implementation inheritance actually
useful.
</SUMMARY>
<BODY>
<DEFINITION>
Multiple inheritance allows a sub-class to have more than one
base class. We distinguish between base classes that are
<em>pure interfaces</em> and those that have an
<em>implementation</em>.
</DEFINITION>
<PROS>
Multiple implementation inheritance may let you re-use even more code
than single inheritance (see <a HREF="#Inheritance">Inheritance</a>).
</PROS>
<CONS>
Only very rarely is multiple <em>implementation</em>
inheritance actually useful. When multiple implementation
inheritance seems like the solution, you can usually find a
different, more explicit, and cleaner solution.
</CONS>
<DECISION>
Multiple inheritance is allowed only when most of the superclasses
are <A HREF="#Interfaces">pure
interfaces</A>. In order to ensure that they remain pure interfaces,
they must end with the <code>Interface</code> suffix.
<SUBSECTION title="Note:">
There is an <a HREF="#Windows_Code">exception</a> to this
rule on Windows.
</SUBSECTION>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Abstract classes">
<SUMMARY>
Classes that have at least one pure virtual method should be prefixed by
<code>Abstract</code>.
</SUMMARY>
<BODY>
<DEFINITION>
<p>
A class that has at least one pure virtual method ("<code>= 0</code>")
is abstract, that is it cannot instantiated directly. It is used as a
base class for another class implementing that pure virtual method.
</p>
<p>
When all methods of a class are pure virtual it is considered a
<a HREF="#Interfaces">interface</a>.
</p>
</DEFINITION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Interfaces">
<SUMMARY>
Classes that satisfy certain conditions are allowed, but not required, to
start with an <code>I</code> prefix.
</SUMMARY>
<BODY>
<DEFINITION>
<p>
A class is a pure interface if it meets the following requirements:
</p>
<ul>
<li> It has only public pure virtual ("<code>= 0</code>") methods
and static methods (but see below for destructor).
</li>
<li> It may not have non-static data members.
</li>
<li> It need not have any constructors defined. If a constructor is
provided, it must take no arguments and it must be protected.
</li>
<li> If it is a subclass, it may only be derived from classes
that satisfy these conditions and are tagged with the
<code>Interface</code> suffix.
</li>