2
<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
3
<GUIDE title="Unity C++ Style Guide">
7
This document was based on the Google C++ Style Guide
11
Craig Silverstein<br/>
28
<CATEGORY title="Important Note">
29
<STYLEPOINT title="Displaying Hidden Details in this Guide">
31
This style guide contains many details that are initially hidden from
32
view. They are marked by the triangle icon, which you see here on your
33
left. Click it now. You should see "Hooray" appear below.
37
Hooray! Now you know you can expand points to get more
38
details. Alternatively, there's an "expand all" at the
44
<CATEGORY title="Background">
46
As every C++ programmer knows, the language has many powerful features,
47
but this power brings with it complexity, which in turn can make code more
48
bug-prone and harder to read and maintain.
51
The goal of this guide is to manage this complexity by describing in
52
detail the dos and don'ts of writing C++ code. These rules exist to keep
53
the code base manageable while still allowing coders to use C++ language
54
features productively.
57
<em>Style</em>, also known as readability, is what we call the conventions
58
that govern our C++ code. The term Style is a bit of a misnomer, since
59
these conventions cover far more than just source file formatting.
62
One way in which we keep the code base manageable is by enforcing
63
<em>consistency</em>. It is very important that any programmer be able to
64
look at another's code and quickly understand it. Maintaining a uniform
65
style and following conventions means that we can more easily use
66
"pattern-matching" to infer what various symbols are and what invariants
67
are true about them. Creating common, required idioms and patterns makes
68
code much easier to understand. In some cases there might be good
69
arguments for changing certain style rules, but we nonetheless keep things
70
as they are in order to preserve consistency.
73
Another issue this guide addresses is that of C++ feature bloat. C++ is a
74
huge language with many advanced features. In some cases we constrain, or
75
even ban, use of certain features. We do this to keep code simple and to
76
avoid the various common errors and problems that these features can
77
cause. This guide lists these features and explains why their use is
81
Note that this guide is not a C++ tutorial: we assume that the reader is
82
familiar with the language.
87
<CATEGORY title="Header Files">
89
In general, every <code>.cpp</code> file should have an associated
90
<code>.h</code> file. There are some common exceptions, such as
91
unittests and small <code>.cpp</code> files containing just a
92
<code>main()</code> function.
95
Correct use of header files can make a huge difference to the
96
readability, size and performance of your code.
99
The following rules will guide you through the various pitfalls of
103
<STYLEPOINT title="The #define Guard">
105
All header files should have <code>#define</code> guards to
106
prevent multiple inclusion. The format of the symbol name
108
<code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.
113
To guarantee uniqueness, they should be based on the full path
114
in a project's source tree. For example, the file
115
<code>foo/src/bar/baz.h</code> in project <code>foo</code> should
116
have the following guard:
119
#ifndef FOO_BAR_BAZ_H_
120
#define FOO_BAR_BAZ_H_
124
#endif // FOO_BAR_BAZ_H_
130
<STYLEPOINT title="Header File Dependencies">
132
Don't use an <code>#include</code> when a forward declaration
137
When you include a header file you introduce a dependency that
138
will cause your code to be recompiled whenever the header file
139
changes. If your header file includes other header files, any
140
change to those files will cause any code that includes your
141
header to be recompiled. Therefore, we prefer to minimize
142
includes, particularly includes of header files in other
146
You can significantly reduce the number of header files you
147
need to include in your own header files by using forward
148
declarations. For example, if your header file uses the
149
<code>File</code> class in ways that do not require access to
150
the declaration of the <code>File</code> class, your header
151
file can just forward declare <code>class File;</code> instead
152
of having to <code>#include "file/base/file.h"</code>.
155
How can we use a class <code>Foo</code> in a header file
156
without access to its definition?
159
<li> We can declare data members of type <code>Foo*</code> or
160
<code>Foo&</code>.
162
<li> We can declare (but not define) functions with arguments,
163
and/or return values, of type <code>Foo</code>. (One
164
exception is if an argument <code>Foo</code>
165
or <code>const Foo&</code> has a
166
non-<code>explicit</code>, one-argument constructor,
168
in which case we need the full definition to support
169
automatic type conversion.)
171
<li> We can declare static data members of type
172
<code>Foo</code>. This is because static data members
173
are defined outside the class definition.
177
On the other hand, you must include the header file for
178
<code>Foo</code> if your class subclasses <code>Foo</code> or
179
has a data member of type <code>Foo</code>.
182
Sometimes it makes sense to have pointer (or better,
183
<code>scoped_ptr</code>)
184
members instead of object members. However, this complicates code
185
readability and imposes a performance penalty, so avoid doing
186
this transformation if the only purpose is to minimize includes
190
Of course, <code>.cpp</code> files typically do require the
191
definitions of the classes they use, and usually have to
192
include several header files.
195
<SUBSECTION title="Note:">
196
If you use a symbol <code>Foo</code> in your source file, you
197
should bring in a definition for <code>Foo</code> yourself,
198
either via an #include or via a forward declaration. Do not
199
depend on the symbol being brought in transitively via headers
200
not directly included. One exception is if <code>Foo</code>
201
is used in <code>myfile.cpp</code>, it's ok to #include (or
202
forward-declare) <code>Foo</code> in <code>myfile.h</code>,
203
instead of <code>myfile.cpp</code>.
208
<STYLEPOINT title="Inline Functions">
210
Define functions inline only when they are small, say, 10 lines
215
You can declare functions in a way that allows the compiler to
216
expand them inline rather than calling them through the usual
217
function call mechanism.
220
Inlining a function can generate more efficient object code,
221
as long as the inlined function is small. Feel free to inline
222
accessors and mutators, and other short, performance-critical
226
Overuse of inlining can actually make programs slower.
227
Depending on a function's size, inlining it can cause the code
228
size to increase or decrease. Inlining a very small accessor
229
function will usually decrease code size while inlining a very
230
large function can dramatically increase code size. On modern
231
processors smaller code usually runs faster due to better use
232
of the instruction cache.
236
A decent rule of thumb is to not inline a function if it is
237
more than 10 lines long. Beware of destructors, which are
238
often longer than they appear because of implicit member-
239
and base-destructor calls!
242
Another useful rule of thumb: it's typically not cost
243
effective to inline functions with loops or switch
244
statements (unless, in the common case, the loop or switch
245
statement is never executed).
248
It is important to know that functions are not always
249
inlined even if they are declared as such; for example,
250
virtual and recursive functions are not normally inlined.
251
Usually recursive functions should not be inline. The main
252
reason for making a virtual function inline is to place its
253
definition in the class, either for convenience or to
254
document its behavior, e.g., for accessors and mutators.
260
<STYLEPOINT title="The -inl.h Files">
262
You may use file names with a <code>-inl.h</code> suffix to define
263
complex inline functions when needed.
267
The definition of an inline function needs to be in a header
268
file, so that the compiler has the definition available for
269
inlining at the call sites. However, implementation code
270
properly belongs in <code>.cpp</code> files, and we do not like
271
to have much actual code in <code>.h</code> files unless there
272
is a readability or performance advantage.
275
If an inline function definition is short, with very little,
276
if any, logic in it, you should put the code in your
277
<code>.h</code> file. For example, accessors and mutators
278
should certainly be inside a class definition. More complex
279
inline functions may also be put in a <code>.h</code> file for
280
the convenience of the implementer and callers, though if this
281
makes the <code>.h</code> file too unwieldy you can instead
282
put that code in a separate <code>-inl.h</code> file.
283
This separates the implementation from the class definition,
284
while still allowing the implementation to be included where
288
Another use of <code>-inl.h</code> files is for definitions of
289
function templates. This can be used to keep your template
290
definitions easy to read.
293
Do not forget that a <code>-inl.h</code> file requires a
294
<a href="#The__define_Guard"><code>#define</code> guard</a> just
295
like any other header file.
301
<STYLEPOINT title="Function Parameter Ordering">
303
When defining a function, parameter order is: inputs,
308
Parameters to C/C++ functions are either input to the
309
function, output from the function, or both. Input parameters
310
are usually values or <code>const</code> references, while output
311
and input/output parameters will be non-<code>const</code>
312
pointers. When ordering function parameters, put all input-only
313
parameters before any output parameters. In particular, do not add
314
new parameters to the end of the function just because they are
315
new; place new input-only parameters before the output
319
This is not a hard-and-fast rule. Parameters that are both
320
input and output (often classes/structs) muddy the waters,
321
and, as always, consistency with related functions may require
322
you to bend the rule.
327
<STYLEPOINT title="Names and Order of Includes">
329
Use standard order for readability and to avoid hidden
330
dependencies: C library, C++ library,
332
other libraries' <code>.h</code>, your
339
All of a project's header files should be
340
listed as descendants of the project's source directory
341
without use of UNIX directory shortcuts <code>.</code> (the current
342
directory) or <code>..</code> (the parent directory). For
345
<code>my-awesome-project/src/base/logging.h</code>
346
should be included as
349
#include "base/logging.h"
352
In <code><var>dir/foo</var>.cpp</code> or <code><var>dir/foo_test</var>.cpp</code>,
353
whose main purpose is to implement or test the stuff in
354
<code><var>dir2/foo2</var>.h</code>, order your includes as
358
<li> <code><var>dir2/foo2</var>.h</code> (preferred location
359
— see details below).</li>
360
<li> C system files.</li>
361
<li> C++ system files.</li>
362
<li> Other libraries' <code>.h</code> files.</li>
365
<code>.h</code> files.</li>
368
The preferred ordering reduces hidden dependencies. We want
369
every header file to be compilable on its own. The easiest
370
way to achieve this is to make sure that every one of them is
371
the first <code>.h</code> file <code>#include</code>d in some
375
<code><var>dir/foo</var>.cpp</code> and
376
<code><var>dir2/foo2</var>.h</code> are often in the same
377
directory (e.g. <code>base/basictypes_test.cpp</code> and
378
<code>base/basictypes.h</code>), but can be in different
383
Within each section it is nice to order the includes
387
For example, the includes in
389
<code>my-awesome-project/src/foo/internal/fooserver.cpp</code>
390
might look like this:
393
#include "foo/public/fooserver.h" // Preferred location.
395
#include <sys/types.h>
396
#include <unistd.h>
398
#include <hash_map>
399
#include <vector>
401
#include "base/basictypes.h"
402
#include "base/commandlineflags.h"
403
#include "foo/public/bar.h"
409
<CATEGORY title="Scoping">
410
<STYLEPOINT title="Namespaces">
412
Unnamed namespaces in <code>.cpp</code> files are encouraged. With
413
named namespaces, choose the name based on the
415
project, and possibly its path.
416
Do not use a <SYNTAX>using-directive</SYNTAX>.
420
Namespaces subdivide the global scope into distinct, named
421
scopes, and so are useful for preventing name collisions in
426
Namespaces provide a (hierarchical) axis of naming, in
427
addition to the (also hierarchical) name axis provided by
431
For example, if two different projects have a class
432
<code>Foo</code> in the global scope, these symbols may
433
collide at compile time or at runtime. If each project
434
places their code in a namespace, <code>project1::Foo</code>
435
and <code>project2::Foo</code> are now distinct symbols that
441
Namespaces can be confusing, because they provide an
442
additional (hierarchical) axis of naming, in addition to the
443
(also hierarchical) name axis provided by classes.
446
Use of unnamed spaces in header files can easily cause
447
violations of the C++ One Definition Rule (ODR).
452
Use namespaces according to the policy described below.
455
<SUBSECTION title="Unnamed Namespaces">
457
<li> Unnamed namespaces are allowed and even encouraged in
458
<code>.cpp</code> files, to avoid runtime naming
461
namespace { // This is in a .cpp file.
463
// The content of a namespace is not indented
464
enum { kUnused, kEOF, kError }; // Commonly used tokens.
465
bool AtEof() { return pos_ == kEOF; } // Uses our namespace's EOF.
471
However, file-scope declarations that are
472
associated with a particular class may be declared
473
in that class as types, static data members or
474
static member functions rather than as members of
475
an unnamed namespace. Terminate the unnamed
476
namespace as shown, with a comment <code>//
480
<li> Do not use unnamed namespaces in <code>.h</code>
486
<SUBSECTION title="Named Namespaces">
488
Named namespaces should be used as follows:
491
<li> Namespaces wrap the entire source file after includes, <a
492
href="http://google-gflags.googlecode.com/">gflags</a>
493
definitions/declarations, and forward declarations of classes from
497
namespace mynamespace {
499
// All declarations are within the namespace scope.
500
// Notice the lack of indentation.
507
} // namespace mynamespace
511
namespace mynamespace {
513
// Definition of functions is within scope of the namespace.
514
void MyClass::Foo() {
518
} // namespace mynamespace
521
The typical <code>.cpp</code> file might have more
522
complex detail, including the need to reference classes
528
DEFINE_bool(someflag, false, "dummy flag");
530
class C; // Forward declaration of class C in the global namespace.
531
namespace a { class A; } // Forward declaration of a::A.
535
...code for b... // Code goes against the left margin.
543
<li> Do not declare anything in namespace
544
<code>std</code>, not even forward declarations of
545
standard library classes. Declaring entities in
546
namespace <code>std</code> is undefined behavior,
547
i.e., not portable. To declare entities from the
548
standard library, include the appropriate header
552
<li> You may not use a <SYNTAX>using-directive</SYNTAX> to
553
make all names from a namespace available.
555
// Forbidden -- This pollutes the namespace.
560
<li> You may use a <SYNTAX>using-declaration</SYNTAX>
561
anywhere in a <code>.cpp</code> file, and in functions,
562
methods or classes in <code>.h</code> files.
565
// Must be in a function, method or class in .h files.
570
<li> Namespace aliases are allowed anywhere in a
571
<code>.cpp</code> file, anywhere inside the named
572
namespace that wraps an entire <code>.h</code> file,
573
and in functions and methods.
575
// Shorten access to some commonly used names in .cpp files.
576
namespace fbz = ::foo::bar::baz;
578
// Shorten access to some commonly used names (in a .h file).
579
namespace librarian {
580
// The following alias is available to all files including
581
// this header (in namespace librarian):
582
// alias names should therefore be chosen consistently
584
namespace pd_s = ::pipeline_diagnostics::sidetable;
586
inline void my_inline_function() {
587
// namespace alias local to a function (or method).
588
namespace fbz = ::foo::bar::baz;
591
} // namespace librarian
594
Note that an alias in a .h file is visible to everyone
595
#including that file, so public headers (those available
596
outside a project) and headers transitively #included by them,
597
should avoid defining aliases, as part of the general
598
goal of keeping public APIs as small as possible.
613
<STYLEPOINT title="Nested Classes">
615
Although you may use public nested classes when they are part of
616
an interface, consider a <a HREF="#Namespaces">namespace</a> to
617
keep declarations out of the global scope.
621
A class can define another class within it; this is also
622
called a <SYNTAX>member class</SYNTAX>.
627
// Bar is a member class, nested within Foo.
636
This is useful when the nested (or member) class is only used
637
by the enclosing class; making it a member puts it in the
638
enclosing class scope rather than polluting the outer scope
639
with the class name. Nested classes can be forward declared
640
within the enclosing class and then defined in the
641
<code>.cpp</code> file to avoid including the nested class
642
definition in the enclosing class declaration, since the
643
nested class definition is usually only relevant to the
647
Nested classes can be forward-declared only within the
648
definition of the enclosing class. Thus, any header file
649
manipulating a <code>Foo::Bar*</code> pointer will have to
650
include the full class declaration for <code>Foo</code>.
653
Do not make nested classes public unless they are actually
654
part of the interface, e.g., a class that holds a set of
655
options for some method.
661
<STYLEPOINT title="Nonmember, Static Member, and Global Functions">
663
Prefer nonmember functions within a namespace or static member
664
functions to global functions; use completely global functions
669
Nonmember and static member functions can be useful in some
670
situations. Putting nonmember functions in a namespace avoids
671
polluting the global namespace.
674
Nonmember and static member functions may make more sense as
675
members of a new class, especially if they access external
676
resources or have significant dependencies.
680
Sometimes it is useful, or even necessary, to define a
681
function not bound to a class instance. Such a function can
682
be either a static member or a nonmember function.
683
Nonmember functions should not depend on external variables,
684
and should nearly always exist in a namespace. Rather than
685
creating classes only to group static member functions which
686
do not share static data, use
687
<a href="#Namespaces">namespaces</a> instead.
690
Functions defined in the same compilation unit as production
691
classes may introduce unnecessary coupling and link-time
692
dependencies when directly called from other compilation
693
units; static member functions are particularly susceptible
694
to this. Consider extracting a new class, or placing the
695
functions in a namespace possibly in a separate library.
698
If you must define a nonmember function and it is only
699
needed in its <code>.cpp</code> file, use an unnamed
700
<a HREF="#Namespaces">namespace</a> or <code>static</code>
701
linkage (eg <code>static int Foo() {...}</code>) to limit
708
<STYLEPOINT title="Local Variables">
710
Place a function's variables in the narrowest scope possible,
711
and initialize variables in the declaration.
715
C++ allows you to declare variables anywhere in a function.
716
We encourage you to declare them in as local a scope as
717
possible, and as close to the first use as possible. This
718
makes it easier for the reader to find the declaration and see
719
what type the variable is and what it was initialized to. In
720
particular, initialization should be used instead of
721
declaration and assignment, e.g.
725
i = f(); // Bad -- initialization separate from declaration.
728
int j = g(); // Good -- declaration has initialization.
731
Note that gcc implements <code>for (int i = 0; i
732
< 10; ++i)</code> correctly (the scope of <code>i</code> is
733
only the scope of the <code>for</code> loop), so you can then
734
reuse <code>i</code> in another <code>for</code> loop in the
735
same scope. It also correctly scopes declarations in
736
<code>if</code> and <code>while</code> statements, e.g.
739
while (const char* p = strchr(str, '/')) str = p + 1;
742
There is one caveat: if the variable is an object, its
743
constructor is invoked every time it enters scope and is
744
created, and its destructor is invoked every time it goes
748
// Inefficient implementation:
749
for (int i = 0; i < 1000000; ++i) {
750
Foo f; // My ctor and dtor get called 1000000 times each.
755
It may be more efficient to declare such a variable used in a
756
loop outside that loop:
759
Foo f; // My ctor and dtor get called once each.
760
for (int i = 0; i < 1000000; ++i) {
767
<STYLEPOINT title="Static and Global Variables">
769
Static or global variables of class type are forbidden: they cause
770
hard-to-find bugs due to indeterminate order of construction and
775
Objects with static storage duration, including global variables,
776
static variables, static class member variables, and function static
777
variables, must be Plain Old Data (POD): only ints, chars, floats, or
778
pointers, or arrays/structs of POD.
781
The order in which class constructors and initializers for
782
static variables are called is only partially specified in C++ and can
783
even change from build to build, which can cause bugs that are difficult
784
to find. Therefore in addition to banning globals of class type, we do
785
not allow static POD variables to be initialized with the result of a
786
function, unless that function (such as getenv(), or getpid()) does not
787
itself depend on any other globals.
790
Likewise, the order in which destructors are called is defined to be the
791
reverse of the order in which the constructors were called. Since
792
constructor order is indeterminate, so is destructor order.
793
For example, at program-end time a static variable might have
794
been destroyed, but code still running -- perhaps in another thread --
795
tries to access it and fails. Or the destructor for a static 'string'
796
variable might be run prior to the destructor for another variable that
797
contains a reference to that string.
800
As a result we only allow static variables to contain POD data. This
801
rule completely disallows <code>vector</code> (use C arrays instead), or
802
<code>string</code> (use <code>const char []</code>).
806
If you need a static or global variable of a class type, consider
807
initializing a pointer (which will never be freed), from either your
808
main() function or from pthread_once(). Note that this must be a raw
809
pointer, not a "smart" pointer, since the smart pointer's destructor
810
will have the order-of-destructor issue that we are trying to avoid.
818
<CATEGORY title="Classes">
819
Classes are the fundamental unit of code in C++. Naturally, we use
820
them extensively. This section lists the main dos and don'ts you
821
should follow when writing a class.
823
<STYLEPOINT title="Doing Work in Constructors">
825
In general, constructors should merely set member variables to their
826
initial values. Any complex initialization should go in an explicit
827
<code>Init()</code> method.
831
It is possible to perform initialization in the body of the
835
Convenience in typing. No need to worry about whether the
836
class has been initialized or not.
839
The problems with doing work in constructors are:
841
<li> There is no easy way for constructors to signal errors,
842
short of using exceptions (which are
843
<a HREF="#Exceptions">forbidden</a>).
845
<li> If the work fails, we now have an object whose
846
initialization code failed, so it may be an
849
<li> If the work calls virtual functions, these calls will
850
not get dispatched to the subclass implementations.
851
Future modification to your class can quietly introduce
852
this problem even if your class is not currently
853
subclassed, causing much confusion.
855
<li> If someone creates a global variable of this type
856
(which is against the rules, but still), the
857
constructor code will be called before
858
<code>main()</code>, possibly breaking some implicit
859
assumptions in the constructor code. For instance,
861
<a href="http://google-gflags.googlecode.com/">gflags</a>
862
will not yet have been initialized.
867
If your object requires non-trivial initialization, consider
868
having an explicit <code>Init()</code> method. In particular,
869
constructors should not call virtual functions, attempt to raise
870
errors, access potentially uninitialized global variables, etc.
875
<STYLEPOINT title="Default Constructors">
877
You must define a default constructor if your class defines
878
member variables and has no other constructors. Otherwise the
879
compiler will do it for you, badly.
883
The default constructor is called when we <code>new</code> a
884
class object with no arguments. It is always called when
885
calling <code>new[]</code> (for arrays).
888
Initializing structures by default, to hold "impossible"
889
values, makes debugging much easier.
892
Extra work for you, the code writer.
896
If your class defines member variables and has no other
897
constructors you must define a default constructor (one that
898
takes no arguments). It should preferably initialize the
899
object in such a way that its internal state is consistent
903
The reason for this is that if you have no other
904
constructors and do not define a default constructor, the
905
compiler will generate one for you. This compiler
906
generated constructor may not initialize your object
910
If your class inherits from an existing class but you add no
911
new member variables, you are not required to have a default
919
<STYLEPOINT title="Explicit Constructors">
921
Use the C++ keyword <code>explicit</code> for constructors with
926
Normally, if a constructor takes one argument, it can be used
927
as a conversion. For instance, if you define
928
<code>Foo::Foo(string name)</code> and then pass a string to a
929
function that expects a <code>Foo</code>, the constructor will
930
be called to convert the string into a <code>Foo</code> and
931
will pass the <code>Foo</code> to your function for you. This
932
can be convenient but is also a source of trouble when things
933
get converted and new objects created without you meaning them
934
to. Declaring a constructor <code>explicit</code> prevents it
935
from being invoked implicitly as a conversion.
938
Avoids undesirable conversions.
945
We require all single argument constructors to be
946
explicit. Always put <code>explicit</code> in front of
947
one-argument constructors in the class definition:
948
<code>explicit Foo(string name);</code>
951
The exception is copy constructors, which, in the rare
952
cases when we allow them, should probably not be
953
<code>explicit</code>.
955
Classes that are intended to be
956
transparent wrappers around other classes are also
958
Such exceptions should be clearly marked with comments.
964
<STYLEPOINT title="Copy Constructors">
966
Provide a copy constructor and assignment operator only when necessary.
967
Otherwise, disable them with <code>DISALLOW_COPY_AND_ASSIGN</code>.
971
The copy constructor and assignment operator are used to create copies
972
of objects. The copy constructor is implicitly invoked by the
973
compiler in some situations, e.g. passing objects by value.
976
Copy constructors make it easy to copy objects. STL
977
containers require that all contents be copyable and
978
assignable. Copy constructors can be more efficient than
979
<code>CopyFrom()</code>-style workarounds because they combine
980
construction with copying, the compiler can elide them in some
981
contexts, and they make it easier to avoid heap allocation.
984
Implicit copying of objects in C++ is a rich source of bugs
985
and of performance problems. It also reduces readability, as
986
it becomes hard to track which objects are being passed around
987
by value as opposed to by reference, and therefore where
988
changes to an object are reflected.
992
Few classes need to be copyable. Most should have neither a
993
copy constructor nor an assignment operator. In many situations,
994
a pointer or reference will work just as well as a copied value,
995
with better performance. For example, you can pass function
996
parameters by reference or pointer instead of by value, and you can
997
store pointers rather than objects in an STL container.
1000
If your class needs to be copyable, prefer providing a copy method,
1001
such as <code>CopyFrom()</code> or <code>Clone()</code>, rather than
1002
a copy constructor, because such methods cannot be invoked
1003
implicitly. If a copy method is insufficient in your situation
1004
(e.g. for performance reasons, or because your class needs to be
1005
stored by value in an STL container), provide both a copy
1006
constructor and assignment operator.
1009
If your class does not need a copy constructor or assignment
1010
operator, you must explicitly disable them.
1013
To do so, add dummy declarations for the copy constructor and
1014
assignment operator in the <code>private:</code> section of your
1015
class, but do not provide any corresponding definition (so that
1016
any attempt to use them results in a link error).
1019
For convenience, a <code>DISALLOW_COPY_AND_ASSIGN</code> macro
1023
// A macro to disallow the copy constructor and operator= functions
1024
// This should be used in the private: declarations for a class
1025
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
1026
TypeName(const TypeName&); \
1027
void operator=(const TypeName&)
1030
Then, in <code>class Foo</code>:
1039
DISALLOW_COPY_AND_ASSIGN(Foo);
1049
<STYLEPOINT title="Structs vs. Classes">
1051
Use a <code>struct</code> only for passive objects that carry data;
1052
everything else is a <code>class</code>.
1056
The <code>struct</code> and <code>class</code> keywords behave
1057
almost identically in C++. We add our own semantic meanings
1058
to each keyword, so you should use the appropriate keyword for
1059
the data-type you're defining.
1062
<code>structs</code> should be used for passive objects that carry
1063
data, and may have associated constants, but lack any functionality
1064
other than access/setting the data members. The
1065
accessing/setting of fields is done by directly accessing the
1066
fields rather than through method invocations. Methods should
1067
not provide behavior but should only be used to set up the
1068
data members, e.g., constructor, destructor,
1069
<code>Initialize()</code>, <code>Reset()</code>,
1070
<code>Validate()</code>.
1073
If more functionality is required, a <code>class</code> is more
1074
appropriate. If in doubt, make it a <code>class</code>.
1077
For consistency with STL, you can use <code>struct</code>
1078
instead of <code>class</code> for functors and traits.
1081
Note that member variables in structs and classes have
1082
<a HREF="#Variable_Names">different naming rules</a>.
1087
<STYLEPOINT title="Inheritance">
1089
Composition is often more appropriate than inheritance. When
1090
using inheritance, make it <code>public</code>.
1094
When a sub-class inherits from a base class, it includes the
1095
definitions of all the data and operations that the parent
1096
base class defines. In practice, inheritance is used in two
1097
major ways in C++: implementation inheritance, in which
1098
actual code is inherited by the child, and <A HREF="#Interfaces">interface inheritance</A>, in which only
1099
method names are inherited.
1102
Implementation inheritance reduces code size by re-using the
1103
base class code as it specializes an existing type. Because
1104
inheritance is a compile-time declaration, you and the
1105
compiler can understand the operation and detect errors.
1106
Interface inheritance can be used to programmatically enforce
1107
that a class expose a particular API. Again, the compiler
1108
can detect errors, in this case, when a class does not define
1109
a necessary method of the API.
1112
For implementation inheritance, because the code implementing
1113
a sub-class is spread between the base and the sub-class, it
1114
can be more difficult to understand an implementation. The
1115
sub-class cannot override functions that are not virtual, so
1116
the sub-class cannot change implementation. The base class
1117
may also define some data members, so that specifies physical
1118
layout of the base class.
1122
All inheritance should be <code>public</code>. If you want to
1123
do private inheritance, you should be including an instance of
1124
the base class as a member instead.
1127
Do not overuse implementation inheritance. Composition is
1128
often more appropriate. Try to restrict use of inheritance
1129
to the "is-a" case: <code>Bar</code> subclasses
1130
<code>Foo</code> if it can reasonably be said that
1131
<code>Bar</code> "is a kind of" <code>Foo</code>.
1134
Make your destructor <code>virtual</code> if necessary. If
1135
your class has virtual methods, its destructor
1140
Limit the use of <code>protected</code> to those member
1141
functions that might need to be accessed from subclasses.
1142
Note that <a href="#Access_Control">data members should
1146
When redefining an inherited virtual function, explicitly
1147
declare it <code>virtual</code> in the declaration of the
1148
derived class. Rationale: If <code>virtual</code> is
1149
omitted, the reader has to check all ancestors of the
1150
class in question to determine if the function is virtual
1157
<STYLEPOINT title="Multiple Inheritance">
1159
Only very rarely is multiple implementation inheritance actually
1160
useful. We allow multiple inheritance only when at most one of
1161
the base classes has an implementation; all other base classes
1162
must be <A HREF="#Interfaces">pure interface</A> classes tagged
1163
with the <code>Interface</code> suffix.
1167
Multiple inheritance allows a sub-class to have more than one
1168
base class. We distinguish between base classes that are
1169
<em>pure interfaces</em> and those that have an
1170
<em>implementation</em>.
1173
Multiple implementation inheritance may let you re-use even more code
1174
than single inheritance (see <a HREF="#Inheritance">Inheritance</a>).
1177
Only very rarely is multiple <em>implementation</em>
1178
inheritance actually useful. When multiple implementation
1179
inheritance seems like the solution, you can usually find a
1180
different, more explicit, and cleaner solution.
1183
Multiple inheritance is allowed only when all superclasses, with the
1184
possible exception of the first one, are <A HREF="#Interfaces">pure
1185
interfaces</A>. In order to ensure that they remain pure interfaces,
1186
they must end with the <code>Interface</code> suffix.
1187
<SUBSECTION title="Note:">
1188
There is an <a HREF="#Windows_Code">exception</a> to this
1195
<STYLEPOINT title="Interfaces">
1197
Classes that satisfy certain conditions are allowed, but not required, to
1198
end with an <code>Interface</code> suffix.
1203
A class is a pure interface if it meets the following requirements:
1206
<li> It has only public pure virtual ("<code>= 0</code>") methods
1207
and static methods (but see below for destructor).
1209
<li> It may not have non-static data members.
1211
<li> It need not have any constructors defined. If a constructor is
1212
provided, it must take no arguments and it must be protected.
1214
<li> If it is a subclass, it may only be derived from classes
1215
that satisfy these conditions and are tagged with the
1216
<code>Interface</code> suffix.
1220
An interface class can never be directly instantiated
1221
because of the pure virtual method(s) it declares. To make
1222
sure all implementations of the interface can be destroyed
1223
correctly, they must also declare a virtual destructor (in
1224
an exception to the first rule, this should not be pure). See
1225
Stroustrup, <cite>The C++ Programming Language</cite>, 3rd
1226
edition, section 12.4 for details.
1230
Tagging a class with the <code>Interface</code> suffix lets
1231
others know that they must not add implemented methods or non
1232
static data members. This is particularly important in the case of
1233
<A HREF="#Multiple_Inheritance">multiple inheritance</A>.
1234
Additionally, the interface concept is already well-understood by
1238
The <code>Interface</code> suffix lengthens the class name, which
1239
can make it harder to read and understand. Also, the interface
1240
property may be considered an implementation detail that shouldn't
1241
be exposed to clients.
1244
A class may end with <code>Interface</code> only if it meets the
1245
above requirements. We do not require the converse, however:
1246
classes that meet the above requirements are not required to end
1247
with <code>Interface</code>.
1252
<STYLEPOINT title="Operator Overloading">
1254
Do not overload operators except in rare, special circumstances.
1258
A class can define that operators such as <code>+</code> and
1259
<code>/</code> operate on the class as if it were a built-in
1263
Can make code appear more intuitive because a class will
1264
behave in the same way as built-in types (such as
1265
<code>int</code>). Overloaded operators are more playful
1266
names for functions that are less-colorfully named, such as
1267
<code>Equals()</code> or <code>Add()</code>. For some
1268
template functions to work correctly, you may need to define
1272
While operator overloading can make code more intuitive, it
1273
has several drawbacks:
1275
<li> It can fool our intuition into thinking that expensive
1276
operations are cheap, built-in operations.
1278
<li> It is much harder to find the call sites for overloaded
1279
operators. Searching for <code>Equals()</code> is much
1280
easier than searching for relevant invocations of
1283
<li> Some operators work on pointers too, making it easy to
1284
introduce bugs. <code>Foo + 4</code> may do one thing,
1285
while <code>&Foo + 4</code> does something totally
1286
different. The compiler does not complain for either of
1287
these, making this very hard to debug.
1290
Overloading also has surprising ramifications. For instance,
1291
if a class overloads unary <code>operator&</code>, it
1292
cannot safely be forward-declared.
1296
In general, do not overload operators. The assignment operator
1297
(<code>operator=</code>), in particular, is insidious and
1298
should be avoided. You can define functions like
1299
<code>Equals()</code> and <code>CopyFrom()</code> if you
1300
need them. Likewise, avoid the dangerous
1301
unary <code>operator&</code> at all costs, if there's
1302
any possibility the class might be forward-declared.
1305
However, there may be rare cases where you need to overload
1306
an operator to interoperate with templates or "standard" C++
1307
classes (such as <code>operator<<(ostream&, const
1308
T&)</code> for logging). These are acceptable if fully
1309
justified, but you should try to avoid these whenever
1310
possible. In particular, do not overload <code>operator==</code>
1311
or <code>operator<</code> just so that your class can be
1312
used as a key in an STL container; instead, you should
1313
create equality and comparison functor types when declaring
1317
Some of the STL algorithms do require you to overload
1318
<code>operator==</code>, and you may do so in these cases,
1319
provided you document why.
1322
See also <a HREF="#Copy_Constructors">Copy Constructors</a>
1323
and <a HREF="#Function_Overloading">Function
1330
<STYLEPOINT title="Access Control">
1332
Make data members <code>private</code>, and provide
1333
access to them through accessor functions as needed (for
1334
technical reasons, we allow data members of a test fixture class
1335
to be <code>protected</code> when using
1337
<A HREF="http://code.google.com/p/googletest/">
1338
Google Test</A>). Typically a variable would be
1339
called <code>foo_</code> and the accessor function
1340
<code>foo()</code>. You may also want a mutator function
1341
<code>set_foo()</code>.
1342
Exception: <code>static const</code> data members (typically
1343
called <code>kFoo</code>) need not be <code>private</code>.
1347
The definitions of accessors are usually inlined in the header
1351
See also <a HREF="#Inheritance">Inheritance</a> and <a HREF="#Function_Names">Function Names</a>.
1356
<STYLEPOINT title="Declaration Order">
1358
Use the specified order of declarations within a class:
1359
<code>public:</code> before <code>private:</code>, methods
1360
before data members (variables), etc.
1364
Your class definition should start with its <code>public:</code>
1365
section, followed by its <code>protected:</code> section and
1366
then its <code>private:</code> section. If any of these sections
1367
are empty, omit them.
1370
Within each section, the declarations generally should be in
1371
the following order:
1374
<li> Typedefs and Enums</li>
1375
<li> Constants (<code>static const</code> data members)</li>
1376
<li> Constructors</li>
1377
<li> Destructor</li>
1378
<li> Methods, including static methods</li>
1379
<li> Data Members (except <code>static const</code> data members)</li>
1382
Friend declarations should always be in the private section, and
1383
the <code>DISALLOW_COPY_AND_ASSIGN</code> macro invocation
1384
should be at the end of the <code>private:</code> section. It
1385
should be the last thing in the class. See <a HREF="#Copy_Constructors">Copy Constructors</a>.
1388
Method definitions in the corresponding <code>.cpp</code> file
1389
should be the same as the declaration order, as much as possible.
1392
Do not put large method definitions inline in the class
1393
definition. Usually, only trivial or performance-critical,
1394
and very short, methods may be defined inline. See <a HREF="#Inline_Functions">Inline Functions</a> for more
1400
<STYLEPOINT title="Write Short Functions">
1402
Prefer small and focused functions.
1406
We recognize that long functions are sometimes appropriate, so
1407
no hard limit is placed on functions length. If a function
1408
exceeds about 40 lines, think about whether it can be broken
1409
up without harming the structure of the program.
1412
Even if your long function works perfectly now, someone
1413
modifying it in a few months may add new behavior. This could
1414
result in bugs that are hard to find. Keeping your functions
1415
short and simple makes it easier for other people to read and
1419
You could find long and complicated functions when working
1423
code. Do not be intimidated by modifying existing
1424
code: if working with such a function proves to be difficult,
1425
you find that errors are hard to debug, or you want to use a
1426
piece of it in several different contexts, consider breaking
1427
up the function into smaller and more manageable pieces.
1433
<CATEGORY title="Google-Specific Magic">
1436
There are various tricks and utilities that we use to make C++
1437
code more robust, and various ways we use C++ that may differ from
1438
what you see elsewhere.
1443
<STYLEPOINT title="Smart Pointers">
1446
If you actually need pointer semantics, <code>scoped_ptr</code>
1447
is great. You should only use <code>std::tr1::shared_ptr</code>
1448
with a non-const referent when it is truly necessary to share ownership
1449
of an object (e.g. inside an STL container). You should never use
1450
<code>auto_ptr</code>.
1454
"Smart" pointers are objects that act like pointers, but automate
1455
management of the underlying memory.
1458
Smart pointers are extremely useful for preventing memory leaks, and
1459
are essential for writing exception-safe code. They also formalize
1460
and document the ownership of dynamically allocated memory.
1463
We prefer designs in which objects have single, fixed owners. Smart
1464
pointers which enable sharing or transfer of ownership can act as a
1465
tempting alternative to a careful design of ownership semantics,
1466
leading to confusing code and even bugs in which memory is never
1467
deleted. The semantics of smart pointers (especially
1468
<code>auto_ptr</code>) can be nonobvious and confusing. The
1469
exception-safety benefits of smart pointers are not decisive, since
1470
we do not allow exceptions.
1474
<dt><code>scoped_ptr</code></dt>
1475
<dd>Straightforward and risk-free. Use wherever appropriate.</dd>
1476
<dt><code>auto_ptr</code></dt>
1477
<dd>Confusing and bug-prone ownership-transfer semantics. Do not use.
1479
<dt><code>shared_ptr</code></dt>
1481
Safe with const referents (i.e. <code>shared_ptr<const
1482
T></code>). Reference-counted pointers with non-const referents
1483
can occasionally be the best design, but try to rewrite with single
1484
owners where possible.
1491
<STYLEPOINT title="cpplint">
1494
<code>cpplint.py</code>
1495
to detect style errors.
1499
<code>cpplint.py</code>
1500
is a tool that reads a source file and
1501
identifies many style errors. It is not perfect, and has both false
1502
positives and false negatives, but it is still a valuable tool. False
1503
positives can be ignored by putting <code>// NOLINT</code> at
1504
the end of the line.
1508
Some projects have instructions on how to run <code>cpplint.py</code>
1509
from their project tools. If the project you are contributing to does
1510
not, you can download <A HREF="http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py"><code>cpplint.py</code></A> separately.
1518
<CATEGORY title="Other C++ Features">
1519
<STYLEPOINT title="Reference Arguments">
1521
All parameters passed by reference must be labeled
1526
In C, if a function needs to modify a variable, the
1527
parameter must use a pointer, eg <code>int foo(int
1528
*pval)</code>. In C++, the function can alternatively
1529
declare a reference parameter: <code>int foo(int
1533
Defining a parameter as reference avoids ugly code like
1534
<code>(*pval)++</code>. Necessary for some applications like
1535
copy constructors. Makes it clear, unlike with pointers, that
1536
<code>NULL</code> is not a possible value.
1539
References can be confusing, as they have value syntax but
1544
Within function parameter lists all references must be
1548
void Foo(const string &in, string *out);
1551
In fact it is a very strong convention in Unity code that input
1552
arguments are values or <code>const</code> references while
1553
output arguments are pointers. Input parameters may be
1554
<code>const</code> pointers, but we never allow
1555
non-<code>const</code> reference parameters.
1558
One case when you might want an input parameter to be a
1559
<code>const</code> pointer is if you want to emphasize that the
1560
argument is not copied, so it must exist for the lifetime of the
1561
object; it is usually best to document this in comments as
1562
well. STL adapters such as <code>bind2nd</code> and
1563
<code>mem_fun</code> do not permit reference parameters, so
1564
you must declare functions with pointer parameters in these
1571
<STYLEPOINT title="Function Overloading">
1573
Use overloaded functions (including constructors) only if a
1574
reader looking at a call site can get a good idea of what is
1575
happening without having to first figure out exactly which
1576
overload is being called.
1581
You may write a function that takes a
1582
<code>const string&</code> and overload it with another that
1583
takes <code>const char*</code>.
1588
void Analyze(const string &text);
1589
void Analyze(const char *text, size_t textlen);
1594
Overloading can make code more intuitive by allowing an
1595
identically-named function to take different arguments. It
1596
may be necessary for templatized code, and it can be
1597
convenient for Visitors.
1600
If a function is overloaded by the argument types alone, a
1601
reader may have to understand C++'s complex matching rules in
1602
order to tell what's going on. Also many people are confused
1603
by the semantics of inheritance if a derived class overrides
1604
only some of the variants of a function.
1607
If you want to overload a function, consider qualifying the
1608
name with some information about the arguments, e.g.,
1609
<code>AppendString()</code>, <code>AppendInt()</code> rather
1610
than just <code>Append()</code>.
1616
<STYLEPOINT title="Default Arguments">
1618
We do not allow default function parameters, except in
1619
a few uncommon situations explained below.
1623
Often you have a function that uses lots of default values,
1624
but occasionally you want to override the defaults. Default
1625
parameters allow an easy way to do this without having to
1626
define many functions for the rare exceptions.
1629
People often figure out how to use an
1630
API by looking at existing code that uses it.
1631
Default parameters are more difficult to maintain because
1632
copy-and-paste from previous code may not reveal all the
1633
parameters. Copy-and-pasting of code segments can cause major
1634
problems when the default arguments are not appropriate for
1639
Except as described below, we require all arguments to be
1640
explicitly specified, to force programmers to consider the API
1641
and the values they are passing for each argument rather than
1642
silently accepting defaults they may not be aware of.
1645
One specific exception is when default arguments are used to
1646
simulate variable-length argument lists.
1649
// Support up to 4 params by using a default empty AlphaNum.
1650
string StrCat(const AlphaNum &a,
1651
const AlphaNum &b = gEmptyAlphaNum,
1652
const AlphaNum &c = gEmptyAlphaNum,
1653
const AlphaNum &d = gEmptyAlphaNum);
1659
<STYLEPOINT title="Variable-Length Arrays and alloca()">
1661
We do not allow variable-length arrays or <code>alloca()</code>.
1665
Variable-length arrays have natural-looking syntax. Both
1666
variable-length arrays and <code>alloca()</code> are very
1670
Variable-length arrays and alloca are not part of Standard
1671
C++. More importantly, they allocate a data-dependent amount
1672
of stack space that can trigger difficult-to-find memory
1673
overwriting bugs: "It ran fine on my machine, but dies
1674
mysteriously in production".
1678
Use a safe allocator instead, such as
1679
<code>scoped_ptr</code>/<code>scoped_array</code>.
1684
<STYLEPOINT title="Friends">
1686
We allow use of <code>friend</code> classes and functions,
1691
Friends should usually be defined in the same file so that the
1692
reader does not have to look in another file to find uses of
1693
the private members of a class. A common use of
1694
<code>friend</code> is to have a <code>FooBuilder</code> class
1695
be a friend of <code>Foo</code> so that it can construct the
1696
inner state of <code>Foo</code> correctly, without exposing
1697
this state to the world. In some cases it may be useful to
1698
make a unittest class a friend of the class it tests.
1701
Friends extend, but do not break, the encapsulation
1702
boundary of a class. In some cases this is better than making
1703
a member public when you want to give only one other class
1704
access to it. However, most classes should interact with
1705
other classes solely through their public members.
1710
<STYLEPOINT title="Exceptions">
1712
We do not use C++ exceptions.
1717
<li>Exceptions allow higher levels of an application to
1718
decide how to handle "can't happen" failures in deeply
1719
nested functions, without the obscuring and error-prone
1720
bookkeeping of error codes.</li>
1724
<li>Exceptions are used by most other modern
1725
languages. Using them in C++ would make it more consistent with
1726
Python, Java, and the C++ that others are familiar with.</li>
1728
<li>Some third-party C++ libraries use exceptions, and turning
1729
them off internally makes it harder to integrate with those
1732
<li>Exceptions are the only way for a constructor to fail.
1733
We can simulate this with a factory function or an
1734
<code>Init()</code> method, but these require heap
1735
allocation or a new "invalid" state, respectively.</li>
1737
<li>Exceptions are really handy in testing frameworks.</li>
1742
<li>When you add a <code>throw</code> statement to an existing
1743
function, you must examine all of its transitive callers. Either
1744
they must make at least the basic exception safety guarantee, or
1745
they must never catch the exception and be happy with the
1746
program terminating as a result. For instance, if
1747
<code>f()</code> calls <code>g()</code> calls
1748
<code>h()</code>, and <code>h</code> throws an exception
1749
that <code>f</code> catches, <code>g</code> has to be
1750
careful or it may not clean up properly.</li>
1752
<li>More generally, exceptions make the control flow of
1753
programs difficult to evaluate by looking at code: functions
1754
may return in places you don't expect. This causes
1755
maintainability and debugging difficulties. You can minimize
1756
this cost via some rules on how and where exceptions can be
1757
used, but at the cost of more that a developer needs to know
1758
and understand.</li>
1760
<li>Exception safety requires both RAII and different coding
1761
practices. Lots of supporting machinery is needed to make
1762
writing correct exception-safe code easy. Further, to avoid
1763
requiring readers to understand the entire call graph,
1764
exception-safe code must isolate logic that writes to
1765
persistent state into a "commit" phase. This will have both
1766
benefits and costs (perhaps where you're forced to obfuscate
1767
code to isolate the commit). Allowing exceptions would force
1768
us to always pay those costs even when they're not worth
1771
<li>Turning on exceptions adds data to each binary produced,
1772
increasing compile time (probably slightly) and possibly
1773
increasing address space pressure.
1776
<li>The availability of exceptions may encourage developers
1777
to throw them when they are not appropriate or recover from
1778
them when it's not safe to do so. For example, invalid user
1779
input should not cause exceptions to be thrown. We would
1780
need to make the style guide even longer to document these
1786
On their face, the benefits of using exceptions outweigh the
1787
costs, especially in new projects. However, for existing code,
1788
the introduction of exceptions has implications on all dependent
1789
code. If exceptions can be propagated beyond a new project, it
1790
also becomes problematic to integrate the new project into
1791
existing exception-free code. Because most existing C++ code at
1792
Google is not prepared to deal with exceptions, it is
1793
comparatively difficult to adopt new code that generates
1797
Given that Google's existing code is not exception-tolerant, the
1798
costs of using exceptions are somewhat greater than the costs in
1799
a new project. The conversion process would be slow and
1800
error-prone. We don't believe that the available alternatives to
1801
exceptions, such as error codes and assertions, introduce a
1806
Our advice against using exceptions is not predicated on
1807
philosophical or moral grounds, but practical ones.
1809
Because we'd like to use our open-source
1810
projects at Google and it's difficult to do so if those projects
1811
use exceptions, we need to advise against exceptions in Google
1812
open-source projects as well.
1813
Things would probably be different if we had to do it all over
1817
There is an <a HREF="#Windows_Code">exception</a> to this
1818
rule (no pun intended) for Windows code.
1824
<STYLEPOINT title="Run-Time Type Information (RTTI)">
1826
We do not use Run Time Type Information (RTTI).
1830
RTTI allows a programmer to query the C++ class of an
1835
It is useful in some unittests. For example, it is useful in
1836
tests of factory classes where the test has to verify that a
1837
newly created object has the expected dynamic type.
1840
In rare circumstances, it is useful even outside of
1845
A query of type during run-time typically means a
1846
design problem. If you need to know the type of an
1847
object at runtime, that is often an indication that
1848
you should reconsider the design of your class.
1852
Do not use RTTI, except in unittests. If you find yourself
1853
in need of writing code that behaves differently based on
1854
the class of an object, consider one of the alternatives to
1858
Virtual methods are the preferred way of executing different
1859
code paths depending on a specific subclass type. This puts
1860
the work within the object itself.
1863
If the work belongs outside the object and instead in some
1864
processing code, consider a double-dispatch solution, such
1865
as the Visitor design pattern. This allows a facility
1866
outside the object itself to determine the type of class
1867
using the built-in type system.
1870
If you think you truly cannot use those ideas,
1872
you may use RTTI. But think twice
1873
about it. :-) Then think twice again.
1874
Do not hand-implement an RTTI-like workaround. The arguments
1875
against RTTI apply just as much to workarounds like class
1876
hierarchies with type tags.
1882
<STYLEPOINT title="Casting">
1884
Use C++ casts like <code>static_cast<>()</code>. Do not use
1885
other cast formats like <code>int y = (int)x;</code> or
1886
<code>int y = int(x);</code>.
1890
C++ introduced a different cast system from C that
1891
distinguishes the types of cast operations.
1894
The problem with C casts is the ambiguity of the operation;
1895
sometimes you are doing a <em>conversion</em> (e.g.,
1896
<code>(int)3.5</code>) and sometimes you are doing a
1897
<em>cast</em> (e.g., <code>(int)"hello"</code>); C++ casts
1898
avoid this. Additionally C++ casts are more visible when
1902
The syntax is nasty.
1906
Do not use C-style casts. Instead, use these C++-style
1912
<li> Use <code>static_cast</code> as the equivalent of a
1913
C-style cast that does value conversion, or when you need to explicitly up-cast
1914
a pointer from a class to its superclass.
1916
<li> Use <code>const_cast</code> to remove the <code>const</code>
1917
qualifier (see <a HREF="#Use_of_const">const</a>).
1921
<li> Use <code>reinterpret_cast</code> to do unsafe
1922
conversions of pointer types to and from integer and
1923
other pointer types. Use this only if you know what you are
1924
doing and you understand the aliasing issues.
1927
<li> Do not use <code>dynamic_cast</code> except in test code.
1928
If you need to know type information at runtime in this way
1929
outside of a unittest, you probably have a <A HREF="#Run-Time_Type_Information__RTTI_">design
1937
<STYLEPOINT title="Streams">
1939
Use streams only for logging.
1943
Streams are a replacement for <code>printf()</code> and
1944
<code>scanf()</code>.
1947
With streams, you do not need to know the type of the object
1948
you are printing. You do not have problems with format
1949
strings not matching the argument list. (Though with gcc, you
1950
do not have that problem with <code>printf</code> either.) Streams
1951
have automatic constructors and destructors that open and close the
1955
Streams make it difficult to do functionality like
1956
<code>pread()</code>. Some formatting (particularly the common
1957
format string idiom <code>%.*s</code>) is difficult if not
1958
impossible to do efficiently using streams without using
1959
<code>printf</code>-like hacks. Streams do not support operator
1960
reordering (the <code>%1s</code> directive), which is helpful for
1961
internationalization.
1966
Do not use streams, except where required by a logging interface.
1967
Use <code>printf</code>-like routines instead.
1970
There are various pros and cons to using streams, but in
1971
this case, as in many other cases, consistency trumps the
1972
debate. Do not use streams in your code.
1975
<SUBSECTION title="Extended Discussion">
1977
There has been debate on this issue, so this explains the
1978
reasoning in greater depth. Recall the Only One Way
1979
guiding principle: we want to make sure that whenever we
1980
do a certain type of I/O, the code looks the same in all
1981
those places. Because of this, we do not want to allow
1982
users to decide between using streams or using
1983
<code>printf</code> plus Read/Write/etc. Instead, we should
1984
settle on one or the other. We made an exception for logging
1985
because it is a pretty specialized application, and for
1989
Proponents of streams have argued that streams are the obvious
1990
choice of the two, but the issue is not actually so clear. For
1991
every advantage of streams they point out, there is an
1992
equivalent disadvantage. The biggest advantage is that
1993
you do not need to know the type of the object to be
1994
printing. This is a fair point. But, there is a
1995
downside: you can easily use the wrong type, and the
1996
compiler will not warn you. It is easy to make this
1997
kind of mistake without knowing when using streams.
2000
cout << this; // Prints the address
2001
cout << *this; // Prints the contents
2004
The compiler does not generate an error because
2005
<code><<</code> has been overloaded. We discourage
2006
overloading for just this reason.
2009
Some say <code>printf</code> formatting is ugly and hard to
2010
read, but streams are often no better. Consider the following
2011
two fragments, both with the same typo. Which is easier to
2015
cerr << "Error connecting to '" << foo->bar()->hostname.first
2016
<< ":" << foo->bar()->hostname.second << ": " << strerror(errno);
2018
fprintf(stderr, "Error connecting to '%s:%u: %s",
2019
foo->bar()->hostname.first, foo->bar()->hostname.second,
2023
And so on and so forth for any issue you might bring up.
2024
(You could argue, "Things would be better with the right
2025
wrappers," but if it is true for one scheme, is it not
2026
also true for the other? Also, remember the goal is to
2027
make the language smaller, not add yet more machinery that
2028
someone has to learn.)
2031
Either path would yield different advantages and
2032
disadvantages, and there is not a clearly superior
2033
solution. The simplicity doctrine mandates we settle on
2034
one of them though, and the majority decision was on
2035
<code>printf</code> + <code>read</code>/<code>write</code>.
2042
<STYLEPOINT title="Preincrement and Predecrement">
2044
Use prefix form (<code>++i</code>) of the increment and
2045
decrement operators with iterators and other template objects.
2049
When a variable is incremented (<code>++i</code> or
2050
<code>i++</code>) or decremented (<code>--i</code> or
2051
<code>i--</code>) and the value of the expression is not used,
2052
one must decide whether to preincrement (decrement) or
2053
postincrement (decrement).
2056
When the return value is ignored, the "pre" form
2057
(<code>++i</code>) is never less efficient than the "post"
2058
form (<code>i++</code>), and is often more efficient. This is
2059
because post-increment (or decrement) requires a copy of
2060
<code>i</code> to be made, which is the value of the
2061
expression. If <code>i</code> is an iterator or other
2062
non-scalar type, copying <code>i</code> could be expensive.
2063
Since the two types of increment behave the same when the
2064
value is ignored, why not just always pre-increment?
2067
The tradition developed, in C, of using post-increment when
2068
the expression value is not used, especially in <code>for</code>
2069
loops. Some find post-increment easier to read, since the
2070
"subject" (<code>i</code>) precedes the "verb" (<code>++</code>),
2071
just like in English.
2074
For simple scalar (non-object) values there is no reason to
2075
prefer one form and we allow either. For iterators and other
2076
template types, use pre-increment.
2081
<STYLEPOINT title="Use of const">
2083
We strongly recommend that you use <code>const</code> whenever
2084
it makes sense to do so.
2088
Declared variables and parameters can be preceded by the
2089
keyword <code>const</code> to indicate the variables are not
2090
changed (e.g., <code>const int foo</code>). Class functions
2091
can have the <code>const</code> qualifier to indicate the
2092
function does not change the state of the class member
2093
variables (e.g., <code>class Foo { int Bar(char c) const;
2097
Easier for people to understand how variables are being used.
2098
Allows the compiler to do better type checking, and,
2099
conceivably, generate better code. Helps people convince
2100
themselves of program correctness because they know the
2101
functions they call are limited in how they can modify your
2102
variables. Helps people know what functions are safe to use
2103
without locks in multi-threaded programs.
2106
<code>const</code> is viral: if you pass a <code>const</code>
2107
variable to a function, that function must have <code>const</code>
2108
in its prototype (or the variable will need a
2109
<code>const_cast</code>). This can be a particular problem
2110
when calling library functions.
2114
<code>const</code> variables, data members, methods and
2115
arguments add a level of compile-time type checking; it
2116
is better to detect errors as soon as possible.
2117
Therefore we strongly recommend that you use
2118
<code>const</code> whenever it makes sense to do so:
2121
<li> If a function does not modify an argument passed by
2122
reference or by pointer, that argument should be
2125
<li> Declare methods to be <code>const</code> whenever
2126
possible. Accessors should almost always be
2127
<code>const</code>. Other methods should be const if they do
2128
not modify any data members, do not call any
2129
non-<code>const</code> methods, and do not return a
2130
non-<code>const</code> pointer or non-<code>const</code>
2131
reference to a data member.
2133
<li> Consider making data members <code>const</code>
2134
whenever they do not need to be modified after
2139
However, do not go crazy with <code>const</code>. Something like
2140
<code>const int * const * const x;</code> is likely
2141
overkill, even if it accurately describes how const x is.
2142
Focus on what's really useful to know: in this case,
2143
<code>const int** x</code> is probably sufficient.
2146
The <code>mutable</code> keyword is allowed but is unsafe
2147
when used with threads, so thread safety should be carefully
2151
<SUBSECTION title="Where to put the const">
2153
Some people favor the form <code>int const *foo</code> to
2154
<code>const int* foo</code>. They argue that this is more
2155
readable because it's more consistent: it keeps the rule
2156
that <code>const</code> always follows the object it's
2157
describing. However, this consistency argument doesn't
2158
apply in this case, because the "don't go crazy" dictum
2159
eliminates most of the uses you'd have to be consistent with.
2161
Putting the <code>const</code> first is arguably more readable,
2162
since it follows English in putting the "adjective"
2163
(<code>const</code>) before the "noun" (<code>int</code>).
2166
That said, while we encourage putting <code>const</code> first,
2167
we do not require it. But be consistent with the code around
2174
<STYLEPOINT title="Integer Types">
2176
Of the built-in C++ integer types, the only one used
2178
is <code>int</code>. If a program needs a variable of a different
2181
a precise-width integer type from
2182
<code><stdint.h></code>, such as <code>int16_t</code>.
2186
C++ does not specify the sizes of its integer types. Typically
2187
people assume that <code>short</code> is 16 bits,
2188
<code>int</code> is 32 bits, <code>long</code> is 32 bits and
2189
<code>long long</code> is 64 bits.
2192
Uniformity of declaration.
2195
The sizes of integral types in C++ can vary based on compiler
2201
<code><stdint.h></code> defines
2202
types like <code>int16_t</code>, <code>uint32_t</code>,
2203
<code>int64_t</code>, etc.
2204
You should always use those in preference to
2205
<code>short</code>, <code>unsigned long long</code> and the
2206
like, when you need a guarantee on the size of an integer.
2207
Of the C integer types, only <code>int</code> should be
2208
used. When appropriate, you are welcome to use standard
2209
types like <code>size_t</code> and <code>ptrdiff_t</code>.
2212
We use <code>int</code> very often, for integers we know are not
2213
going to be too big, e.g., loop counters. Use plain old
2214
<code>int</code> for such things. You should assume that an
2218
but don't assume that it has more than 32 bits.
2219
If you need a 64-bit integer type, use
2220
<code>int64_t</code> or
2221
<code>uint64_t</code>.
2224
For integers we know can be "big",
2226
<code>int64_t</code>.
2230
You should not use the unsigned integer types such as
2231
<code>uint32_t</code>,
2232
unless the quantity you are representing is really a bit pattern
2233
rather than a number, or unless you need defined
2234
twos-complement overflow. In particular, do not use unsigned
2235
types to say a number will never be negative. Instead, use
2237
assertions for this.
2242
<SUBSECTION title="On Unsigned Integers">
2244
Some people, including some textbook authors, recommend
2245
using unsigned types to represent numbers that are never
2246
negative. This is intended as a form of self-documentation.
2247
However, in C, the advantages of such documentation are
2248
outweighed by the real bugs it can introduce. Consider:
2251
for (unsigned int i = foo.Length()-1; i >= 0; --i) ...
2254
This code will never terminate! Sometimes gcc will notice
2255
this bug and warn you, but often it will not. Equally bad
2256
bugs can occur when comparing signed and unsigned
2257
variables. Basically, C's type-promotion scheme causes
2258
unsigned types to behave differently than one might expect.
2261
So, document that a variable is non-negative using
2263
Don't use an unsigned type.
2269
<STYLEPOINT title="64-bit Portability">
2271
Code should be 64-bit and 32-bit friendly. Bear in mind problems of
2272
printing, comparisons, and structure alignment.
2278
<code>printf()</code> specifiers for some types are
2279
not cleanly portable between 32-bit and 64-bit
2280
systems. C99 defines some portable format
2281
specifiers. Unfortunately, MSVC 7.1 does not
2282
understand some of these specifiers and the
2283
standard is missing a few, so we have to define our
2284
own ugly versions in some cases (in the style of the
2285
standard include file <code>inttypes.h</code>):
2288
// printf macros for size_t, in the style of inttypes.h
2290
#define __PRIS_PREFIX "z"
2292
#define __PRIS_PREFIX
2295
// Use these macros after a % in a printf format string
2296
// to get correct 32/64 bit behavior, like this:
2297
// size_t size = records.size();
2298
// printf("%"PRIuS"\n", size);
2300
#define PRIdS __PRIS_PREFIX "d"
2301
#define PRIxS __PRIS_PREFIX "x"
2302
#define PRIuS __PRIS_PREFIX "u"
2303
#define PRIXS __PRIS_PREFIX "X"
2304
#define PRIoS __PRIS_PREFIX "o"
2306
<table border="1" summary="portable printf specifiers">
2315
<td><code>void *</code> (or any pointer)</td>
2316
<td><code>%lx</code></td>
2317
<td><code>%p</code></td>
2322
<td><code>int64_t</code></td>
2323
<td><code>%qd</code>,
2324
<code>%lld</code></td>
2325
<td><code>%"PRId64"</code></td>
2330
<td><code>uint64_t</code></td>
2331
<td><code>%qu</code>,
2333
<code>%llx</code></td>
2334
<td><code>%"PRIu64"</code>,
2335
<code>%"PRIx64"</code></td>
2340
<td><code>size_t</code></td>
2341
<td><code>%u</code></td>
2342
<td><code>%"PRIuS"</code>,
2343
<code>%"PRIxS"</code></td>
2344
<td>C99 specifies <code>%zu</code></td>
2347
<td><code>ptrdiff_t</code></td>
2348
<td><code>%d</code></td>
2349
<td><code>%"PRIdS"</code></td>
2350
<td>C99 specifies <code>%zd</code></td>
2356
Note that the <code>PRI*</code> macros expand to independent
2357
strings which are concatenated by the compiler. Hence
2358
if you are using a non-constant format string, you
2359
need to insert the value of the macro into the format,
2360
rather than the name. It is still possible, as usual,
2361
to include length specifiers, etc., after the
2362
<code>%</code> when using the <code>PRI*</code>
2363
macros. So, e.g. <code>printf("x = %30"PRIuS"\n",
2364
x)</code> would expand on 32-bit Linux to
2365
<code>printf("x = %30" "u" "\n", x)</code>, which the
2366
compiler will treat as <code>printf("x = %30u\n",
2372
<li> Remember that <code>sizeof(void *)</code> !=
2373
<code>sizeof(int)</code>. Use <code>intptr_t</code> if
2374
you want a pointer-sized integer.
2377
<li> You may need to be careful with structure alignments,
2378
particularly for structures being stored on disk. Any
2379
class/structure with a
2381
<code>int64_t</code>/<code>uint64_t</code>
2382
member will by default end up being 8-byte aligned on a 64-bit
2383
system. If you have such structures being shared on disk
2384
between 32-bit and 64-bit code, you will need to ensure
2385
that they are packed the same on both architectures.
2387
Most compilers offer a way to alter
2388
structure alignment. For gcc, you can use
2389
<code>__attribute__((packed))</code>. MSVC offers
2390
<code>#pragma pack()</code> and
2391
<code>__declspec(align())</code>.
2396
Use the <code>LL</code> or <code>ULL</code> suffixes as
2397
needed to create 64-bit constants. For example:
2400
int64_t my_value = 0x123456789LL;
2401
uint64_t my_mask = 3ULL << 48;
2405
<li> If you really need different code on 32-bit and 64-bit
2406
systems, use <code>#ifdef _LP64</code> to choose between
2407
the code variants. (But please avoid this if
2408
possible, and keep any such changes localized.)
2414
<STYLEPOINT title="Preprocessor Macros">
2416
Be very cautious with macros. Prefer inline functions, enums,
2417
and <code>const</code> variables to macros.
2421
Macros mean that the code you see is not the same as the code
2422
the compiler sees. This can introduce unexpected behavior,
2423
especially since macros have global scope.
2426
Luckily, macros are not nearly as necessary in C++ as they are
2427
in C. Instead of using a macro to inline performance-critical
2428
code, use an inline function. Instead of using a macro to
2429
store a constant, use a <code>const</code> variable. Instead of
2430
using a macro to "abbreviate" a long variable name, use a
2431
reference. Instead of using a macro to conditionally compile code
2432
... well, don't do that at all (except, of course, for the
2433
<code>#define</code> guards to prevent double inclusion of
2434
header files). It makes testing much more difficult.
2437
Macros can do things these other techniques cannot, and you do
2438
see them in the codebase, especially in the lower-level
2439
libraries. And some of their special features (like
2440
stringifying, concatenation, and so forth) are not available
2441
through the language proper. But before using a macro,
2442
consider carefully whether there's a non-macro way to achieve
2446
The following usage pattern will avoid many problems with
2447
macros; if you use macros, follow it whenever possible:
2450
<li> Don't define macros in a <code>.h</code> file.
2452
<li> <code>#define</code> macros right before you use them,
2453
and <code>#undef</code> them right after.
2455
<li> Do not just <code>#undef</code> an existing macro before
2456
replacing it with your own; instead, pick a name that's
2457
likely to be unique.
2459
<li> Try not to use macros that expand to unbalanced C++
2460
constructs, or at least document that behavior well.
2462
<li> Prefer not using <code>##</code> to generate function/class/variable
2469
<STYLEPOINT title="0 and NULL">
2471
Use <code>0</code> for integers, <code>0.0</code> for reals,
2472
<code>NULL</code> for pointers, and <code>'\0'</code> for chars.
2476
Use <code>0</code> for integers and <code>0.0</code> for reals.
2477
This is not controversial.
2480
For pointers (address values), there is a choice between <code>0</code>
2481
and <code>NULL</code>. Bjarne Stroustrup prefers an unadorned
2482
<code>0</code>. We prefer <code>NULL</code> because it looks like a
2483
pointer. In fact, some C++ compilers, such as gcc 4.1.0, provide special
2484
definitions of <code>NULL</code> which enable them to give useful
2485
warnings, particularly in situations where <code>sizeof(NULL)</code>
2486
is not equal to <code>sizeof(0)</code>.
2489
Use <code>'\0'</code> for chars.
2490
This is the correct type and also makes code more readable.
2495
<STYLEPOINT title="sizeof">
2497
Use <code>sizeof(<var>varname</var>)</code> instead of
2498
<code>sizeof(<var>type</var>)</code> whenever possible.
2502
Use <code>sizeof(<var>varname</var>)</code> because it will update
2503
appropriately if the type of the variable changes.
2504
<code>sizeof(<var>type</var>)</code> may make sense in some cases,
2505
but should generally be avoided because it can fall out of sync if
2506
the variable's type changes.
2511
memset(&data, 0, sizeof(data));
2514
memset(&data, 0, sizeof(Struct));
2520
<STYLEPOINT title="Boost">
2522
Use only approved libraries from the Boost library collection.
2526
The <a href="http://www.boost.org/">Boost library collection</a> is
2527
a popular collection of peer-reviewed, free, open-source C++ libraries.
2530
Boost code is generally very high-quality, is widely portable, and fills
2531
many important gaps in the C++ standard library, such as type traits,
2532
better binders, and better smart pointers. It also provides an
2533
implementation of the TR1 extension to the standard library.
2536
Some Boost libraries encourage coding practices which can hamper
2537
readability, such as metaprogramming and other advanced template
2538
techniques, and an excessively "functional" style of programming.
2545
In order to maintain a high level of readability for all contributors
2546
who might read and maintain code, we only allow an approved subset of
2547
Boost features. Currently, the following libraries are permitted:
2549
<li> <a href="http://www.boost.org/libs/utility/call_traits.htm">
2550
Call Traits</a> from <code>boost/call_traits.hpp</code>
2552
<li> <a href="http://www.boost.org/libs/utility/compressed_pair.htm">
2553
Compressed Pair</a> from <code>boost/compressed_pair.hpp</code>
2555
<li> <a href="http://www.boost.org/libs/ptr_container/">
2556
Pointer Container</a> from <code>boost/ptr_container</code> except
2557
serialization and wrappers for containers not in the C++03
2558
standard (<code>ptr_circular_buffer.hpp</code> and
2559
<code>ptr_unordered*</code>)
2561
<li> <a href="http://www.boost.org/libs/array/">
2562
Array</a> from <code>boost/array.hpp</code>
2564
<li> <a href="http://www.boost.org/libs/graph/">
2565
The Boost Graph Library (BGL)</a> from <code>boost/graph</code>,
2566
except serialization (<code>adj_list_serialize.hpp</code>) and
2567
parallel/distributed algorithms and data structures
2568
(<code>boost/graph/parallel/*</code> and
2569
<code>boost/graph/distributed/*</code>).
2571
<li> <a href="http://www.boost.org/libs/property_map/">
2572
Property Map</a> from <code>boost/property_map</code>, except
2573
parallel/distributed property maps
2574
(<code>boost/property_map/parallel/*</code>).
2577
<a href="http://www.boost.org/libs/iterator/">
2578
Iterator</a> that deals with defining iterators:
2579
<code>boost/iterator/iterator_adaptor.hpp</code>,
2580
<code>boost/iterator/iterator_facade.hpp</code>, and
2581
<code>boost/function_output_iterator.hpp</code></li>
2583
We are actively considering adding other Boost features to the list, so
2584
this rule may be relaxed in the future.
2590
<STYLEPOINT title="C++0x">
2592
Use only approved libraries and language extensions from C++0x.
2593
Currently, none are approved.
2597
C++0x is the next ISO C++ standard, currently in
2598
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf">final
2599
committee draft</a> form. It contains
2600
<a href="http://en.wikipedia.org/wiki/C%2B%2B0x">significant
2601
changes</a> both to the language and libraries.
2604
We expect that C++0x will become the next standard, and eventually will
2605
be supported by most C++ compilers. It standardizes some common C++
2606
extensions that we use already, allows shorthands for some operations,
2607
and has some safety improvements.
2611
The C++0x standard is substantialy more complex than its predecessor
2612
(1,300 pages versus 800 pages), and is
2613
unfamilar to many developers. The long-term effects of some
2614
features on code readability and maintenance are unknown. We cannot
2615
predict when its various features will be implemented uniformly by
2616
tools that may be of interest (gcc, icc, clang, Eclipse, etc.).
2619
As with <a href="#Boost">Boost</a>, some C++0x extensions encourage
2620
coding practices that hamper readability—for example by removing
2621
checked redundancy (such as type names) that may be helpful to readers,
2622
or by encouraging template metaprogramming. Other extensions
2623
duplicate functionality available through existing
2624
mechanisms, which may lead to
2625
confusion and conversion costs.
2629
Use only C++0x libraries and language features that have been approved
2630
for use. Currently, no such features are approved.
2631
Features will be approved individually as appropriate.
2638
<CATEGORY title="Naming">
2640
The most important consistency rules are those that govern
2641
naming. The style of a name immediately informs us what sort of
2642
thing the named entity is: a type, a variable, a function, a
2643
constant, a macro, etc., without requiring us to search for the
2644
declaration of that entity. The pattern-matching engine in our
2645
brains relies a great deal on these naming rules.
2649
Naming rules are pretty arbitrary, but
2651
we feel that consistency is more important than individual preferences
2652
in this area, so regardless of whether you find them sensible or not,
2653
the rules are the rules.
2656
<STYLEPOINT title="General Naming Rules">
2658
Function names, variable names, and filenames should be
2659
descriptive; eschew abbreviation. Types and variables should be
2660
nouns, while functions should be "command" verbs.
2663
<SUBSECTION title="How to Name">
2665
Give as descriptive a name as possible, within reason. Do
2666
not worry about saving horizontal space as it is far more
2667
important to make your code immediately understandable by a
2668
new reader. Examples of well-chosen names:
2671
int num_errors; // Good.
2672
int num_completed_connections; // Good.
2675
Poorly-chosen names use ambiguous abbreviations or arbitrary
2676
characters that do not convey meaning:
2679
int n; // Bad - meaningless.
2680
int nerr; // Bad - ambiguous abbreviation.
2681
int n_comp_conns; // Bad - ambiguous abbreviation.
2684
Type and variable names should typically be nouns: e.g.,
2685
<code>FileOpener</code>,
2687
<code>num_errors</code>.
2690
Function names should typically be imperative (that is they
2691
should be commands): e.g., <code>OpenFile()</code>,
2692
<code>set_num_errors()</code>. There is an exception for
2693
accessors, which, described more completely in <a HREF="#Function_Names">Function Names</a>, should be named
2694
the same as the variable they access.
2698
<SUBSECTION title="Abbreviations">
2700
Do not use abbreviations unless they are extremely well
2701
known outside your project. For example:
2705
// These show proper names with no abbreviations.
2706
int num_dns_connections; // Most people know what "DNS" stands for.
2707
int price_count_reader; // OK, price count. Makes sense.
2711
// Abbreviations can be confusing or ambiguous outside a small group.
2712
int wgc_connections; // Only your group knows what this stands for.
2713
int pc_reader; // Lots of things can be abbreviated "pc".
2716
Never abbreviate by leaving out letters:
2719
int error_count; // Good.
2722
int error_cnt; // Bad.
2728
<STYLEPOINT title="File Names">
2730
Filenames should be all lowercase and can include underscores
2731
(<code>_</code>) or dashes (<code>-</code>). Follow the
2732
convention that your
2735
uses. If there is no consistent local pattern to follow, prefer "_".
2739
Examples of acceptable file names:
2743
my_useful_class.cpp<br/>
2744
my-useful-class.cpp<br/>
2745
myusefulclass.cpp<br/>
2746
myusefulclass_test.cpp // _unittest and _regtest are deprecated.<br/>
2750
C++ files should end in <code>.cpp</code> and header files
2751
should end in <code>.h</code>.
2754
Do not use filenames that already exist
2755
in <code>/usr/include</code>, such as <code>db.h</code>.
2758
In general, make your filenames very specific. For example,
2759
use <code>http_server_logs.h</code> rather
2760
than <code>logs.h</code>. A very common case is to have a
2761
pair of files called, e.g., <code>foo_bar.h</code>
2762
and <code>foo_bar.cpp</code>, defining a class
2763
called <code>FooBar</code>.
2766
Inline functions must be in a <code>.h</code> file. If your
2767
inline functions are very short, they should go directly into your
2768
<code>.h</code> file. However, if your inline functions
2769
include a lot of code, they may go into a third file that
2770
ends in <code>-inl.h</code>. In a class with a lot of inline
2771
code, your class could have three files:
2774
url_table.h // The class declaration.
2775
url_table.cpp // The class definition.
2776
url_table-inl.h // Inline functions that include lots of code.
2779
See also the section <a href="#The_-inl.h_Files">-inl.h Files</a>
2784
<STYLEPOINT title="Type Names">
2786
Type names start with a capital letter and have a capital
2787
letter for each new word, with no underscores:
2788
<code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.
2792
The names of all types — classes, structs, typedefs, and enums
2793
— have the same naming convention. Type names should start
2794
with a capital letter and have a capital letter for each new
2795
word. No underscores. For example:
2798
// classes and structs
2799
class UrlTable { ...
2800
class UrlTableTester { ...
2801
struct UrlTableProperties { ...
2804
typedef hash_map<UrlTableProperties *, string> PropertiesMap;
2807
enum UrlTableErrors { ...
2812
<STYLEPOINT title="Variable Names">
2814
Variable names are all lowercase, with underscores between
2815
words. Class member variables have trailing underscores. For
2816
instance: <code>my_exciting_local_variable</code>,
2817
<code>my_exciting_member_variable_</code>.
2820
<SUBSECTION title="Common Variable names">
2825
string table_name; // OK - uses underscore.
2826
string tablename; // OK - all lowercase.
2829
string tableName; // Bad - mixed case.
2833
<SUBSECTION title="Class Data Members">
2835
Data members (also called instance variables or member
2836
variables) are lowercase with optional underscores like
2837
regular variable names, but always end with a trailing
2841
string table_name_; // OK - underscore at end.
2842
string tablename_; // OK.
2846
<SUBSECTION title="Struct Variables">
2848
Data members in structs should be named like regular
2849
variables without the trailing underscores that data members
2853
struct UrlTableProperties {
2859
See <a HREF="#Structs_vs._Classes">Structs vs. Classes</a> for a
2860
discussion of when to use a struct versus a class.
2864
<SUBSECTION title="Global Variables">
2866
There are no special requirements for global variables,
2867
which should be rare in any case, but if you use one,
2868
consider prefixing it with <code>g_</code> or some other
2869
marker to easily distinguish it from local variables.
2875
<STYLEPOINT title="Constant Names">
2877
Use upper-case with underscores between words:
2878
<code>DAYS_IN_A_WEEK</code>.
2882
All compile-time constants, whether they are declared locally,
2883
globally, or as part of a class, follow a slightly different naming
2884
convention from other variables. Use upper-case with underscores.
2887
const int DAYS_IN_A_WEEK = 7;
2892
<STYLEPOINT title="Function Names">
2894
Regular functions have mixed case; accessors and mutators match
2895
the name of the variable: <code>MyExcitingFunction()</code>,
2896
<code>MyExcitingMethod()</code>,
2897
<code>my_exciting_member_variable()</code>,
2898
<code>set_my_exciting_member_variable()</code>.
2901
<SUBSECTION title="Regular Functions">
2903
Functions should start with a capital letter and have a
2904
capital letter for each new word. No underscores.
2907
If your function crashes upon an error, you should append OrDie to
2908
the function name. This only applies to functions which could be
2909
used by production code and to errors that are reasonably
2910
likely to occur during normal operation.
2919
<SUBSECTION title="Accessors and Mutators">
2921
Accessors and mutators (get and set functions) should match
2922
the name of the variable they are getting and setting. This
2923
shows an excerpt of a class whose instance variable is
2924
<code>num_entries_</code>.
2930
int num_entries() const { return num_entries_; }
2931
void set_num_entries(int num_entries) { num_entries_ = num_entries; }
2938
You may also use lowercase letters for other very short
2939
inlined functions. For example if a function were so cheap
2940
you would not cache the value if you were calling it in a
2941
loop, then lowercase naming would be acceptable.
2947
<STYLEPOINT title="Namespace Names">
2950
Namespace names are all lower-case, and based on project names and
2951
possibly their directory structure:
2952
<code>my_awesome_project</code>.
2956
See <a HREF="#Namespaces">Namespaces</a> for a discussion of
2957
namespaces and how to name them.
2962
<STYLEPOINT title="Enumerator Names">
2964
Enumerators should be named <i>either</i> like
2965
<A HREF="#Constant_Names">constants</A> and
2966
<A HREF="#Macro_Names">macros</A>: <code>ENUM_NAME</code>.
2970
Preferably, the individual enumerators should be named like
2971
<A HREF="#Constant_Names">constants</A>. The enumeration name,
2972
<code>UrlTableErrors</code>, is a type, and
2973
therefore mixed case.
2976
enum UrlTableErrors {
2985
<STYLEPOINT title="Macro Names">
2987
You're not really going to <A HREF="#Preprocessor_Macros">define
2988
a macro</A>, are you? If you do, they're like this:
2989
<code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.
2993
Please see the <a href="#Preprocessor_Macros">description of
2994
macros</a>; in general macros should <em>not</em> be used.
2995
However, if they are absolutely needed, then they should be
2996
named with all capitals and underscores.
2999
#define ROUND(x) ...
3000
#define PI_ROUNDED 3.0
3005
<STYLEPOINT title="Exceptions to Naming Rules">
3007
If you are naming something that is analogous to an existing C
3008
or C++ entity then you can follow the existing naming convention
3014
<dt> <code>bigopen()</code> </dt>
3015
<dd> function name, follows form of <code>open()</code> </dd>
3016
<dt> <code>uint</code> </dt>
3017
<dd> <code>typedef</code> </dd>
3018
<dt> <code>bigpos</code> </dt>
3019
<dd> <code>struct</code> or <code>class</code>, follows form of
3020
<code>pos</code> </dd>
3021
<dt> <code>sparse_hash_map</code> </dt>
3022
<dd> STL-like entity; follows STL naming conventions </dd>
3023
<dt> <code>LONGLONG_MAX</code> </dt>
3024
<dd> a constant, as in <code>INT_MAX</code> </dd>
3031
<CATEGORY title="Comments">
3033
Though a pain to write, comments are absolutely vital to keeping our
3034
code readable. The following rules describe what you should
3035
comment and where. But remember: while comments are very
3036
important, the best code is self-documenting. Giving sensible
3037
names to types and variables is much better than using obscure
3038
names that you must then explain through comments.
3041
When writing your comments, write for your audience: the next contributor
3042
who will need to understand your code. Be generous — the next one
3046
<STYLEPOINT title="Comment Style">
3048
Use either the <code>//</code> or <code>/* */</code> syntax, as long
3049
as you are consistent.
3053
You can use either the <code>//</code> or the <code>/* */</code>
3054
syntax; however, <code>//</code> is <em>much</em> more common.
3055
Be consistent with how you comment and what style you use where.
3060
<STYLEPOINT title="File Comments">
3062
Start each file with a copyright notice, followed by a
3063
description of the contents of the file.
3066
<SUBSECTION title="Legal Notice and Author Line">
3068
Every file should contain the following items, in order:
3070
<li>a optional mode line,
3071
<code>// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-</code></li>
3072
<li>a copyright statement (for example,
3073
<code>Copyright (C) 2011 Canonical Ltd</code>)</li>
3074
<li>the license boilerplate.</li>
3075
<li>an author line to identify the original author of the
3080
If you make significant changes to a file that someone else
3081
originally wrote, add yourself to the author line. This can be very
3082
helpful when another contributor has questions about the file and
3083
needs to know whom to contact about it.
3087
<SUBSECTION title="File Contents">
3089
Every file should have a comment at the top, below the copyright
3090
notice and author line, that describes the contents of the file.
3093
Generally a <code>.h</code> file will describe the classes
3094
that are declared in the file with an overview of what they
3095
are for and how they are used. A <code>.cpp</code> file
3096
should contain more information about implementation details
3097
or discussions of tricky algorithms. If you feel the
3098
implementation details or a discussion of the algorithms
3099
would be useful for someone reading the <code>.h</code>,
3100
feel free to put it there instead, but mention in the
3101
<code>.cpp</code> that the documentation is in the
3102
<code>.h</code> file.
3105
Do not duplicate comments in both the <code>.h</code> and
3106
the <code>.cpp</code>. Duplicated comments diverge.
3112
<STYLEPOINT title="Class Comments">
3114
Every class definition should have an accompanying comment that
3115
describes what it is for and how it should be used.
3119
// Iterates over the contents of a GargantuanTable. Sample usage:
3120
// GargantuanTableIterator* iter = table->NewIterator();
3121
// for (iter->Seek("foo"); !iter->done(); iter->Next()) {
3122
// process(iter->key(), iter->value());
3125
class GargantuanTableIterator {
3130
If you have already described a class in detail in the
3131
comments at the top of your file feel free to simply state
3132
"See comment at top of file for a complete description", but
3133
be sure to have some sort of comment.
3136
Document the synchronization assumptions the class makes, if
3137
any. If an instance of the class can be accessed by multiple
3138
threads, take extra care to document the rules and invariants
3139
surrounding multithreaded use.
3144
<STYLEPOINT title="Function Comments">
3146
Declaration comments describe use of the function; comments at
3147
the definition of a function describe operation.
3150
<SUBSECTION title="Function Declarations">
3152
Every function declaration should have comments immediately
3153
preceding it that describe what the function does and how to
3154
use it. These comments should be descriptive ("Opens the
3155
file") rather than imperative ("Open the file"); the comment
3156
describes the function, it does not tell the function what
3157
to do. In general, these comments do not describe how the
3158
function performs its task. Instead, that should be left to
3159
comments in the function definition.
3162
Types of things to mention in comments at the function
3166
<li> What the inputs and outputs are.
3168
<li> For class member functions: whether the object
3169
remembers reference arguments beyond the
3170
duration of the method call, and whether it will
3173
<li> If the function allocates memory that the caller
3176
<li> Whether any of the arguments can be <code>NULL</code>.
3178
<li> If there are any performance implications of how a
3181
<li> If the function is re-entrant. What are its
3182
synchronization assumptions?
3189
// Returns an iterator for this table. It is the client's
3190
// responsibility to delete the iterator when it is done with it,
3191
// and it must not use the iterator once the GargantuanTable object
3192
// on which the iterator was created has been deleted.
3194
// The iterator is initially positioned at the beginning of the table.
3196
// This method is equivalent to:
3197
// Iterator* iter = table->NewIterator();
3198
// iter->Seek("");
3200
// If you are going to immediately seek to another place in the
3201
// returned iterator, it will be faster to use NewIterator()
3202
// and avoid the extra seek.
3203
Iterator* GetIterator() const;
3206
However, do not be unnecessarily verbose or state the
3207
completely obvious. Notice below that it is not necessary
3208
to say "returns false otherwise" because this is implied.
3211
// Returns true if the table cannot hold any more entries.
3215
When commenting constructors and destructors, remember that
3216
the person reading your code knows what constructors and
3217
destructors are for, so comments that just say something like
3218
"destroys this object" are not useful. Document what
3219
constructors do with their arguments (for example, if they
3220
take ownership of pointers), and what cleanup the destructor
3221
does. If this is trivial, just skip the comment. It is
3222
quite common for destructors not to have a header comment.
3226
<SUBSECTION title="Function Definitions">
3228
Each function definition should have a comment describing
3229
what the function does if there's anything tricky about how it does
3230
its job. For example, in the definition comment you might
3231
describe any coding tricks you use, give an overview of the
3232
steps you go through, or explain why you chose to implement
3233
the function in the way you did rather than using a viable
3234
alternative. For instance, you might mention why it must
3235
acquire a lock for the first half of the function but why it
3236
is not needed for the second half.
3239
Note you should <em>not</em> just repeat the comments given
3240
with the function declaration, in the <code>.h</code> file or
3241
wherever. It's okay to recapitulate briefly what the function
3242
does, but the focus of the comments should be on how it does it.
3248
<STYLEPOINT title="Variable Comments">
3250
In general the actual name of the variable should be descriptive
3251
enough to give a good idea of what the variable is used for. In
3252
certain cases, more comments are required.
3255
<SUBSECTION title="Class Data Members">
3257
Each class data member (also called an instance variable or
3258
member variable) should have a comment describing what it is
3259
used for. If the variable can take sentinel values with
3260
special meanings, such as <code>NULL</code> or -1, document this.
3265
// Keeps track of the total number of entries in the table.
3266
// Used to ensure we do not go over the limit. -1 means
3267
// that we don't yet know how many entries the table has.
3268
int num_total_entries_;
3272
<SUBSECTION title="Global Variables">
3274
As with data members, all global variables should have a
3275
comment describing what they are and what they are used for.
3279
// The total number of tests cases that we run through in this regression test.
3280
const int kNumTestCases = 6;
3286
<STYLEPOINT title="Implementation Comments">
3288
In your implementation you should have comments in tricky,
3289
non-obvious, interesting, or important parts of your code.
3292
<SUBSECTION title="Class Data Members">
3294
Tricky or complicated code blocks should have comments
3295
before them. Example:
3298
// Divide result by two, taking into account that x
3299
// contains the carry from the add.
3300
for (int i = 0; i < result->size(); i++) {
3301
x = (x << 8) + (*result)[i];
3302
(*result)[i] = x >> 1;
3307
<SUBSECTION title="Line Comments">
3309
Also, lines that are non-obvious should get a comment at the
3310
end of the line. These end-of-line comments should be
3311
separated from the code by 2 spaces. Example:
3314
// If we have enough memory, mmap the data portion too.
3315
mmap_budget = max<int64>(0, mmap_budget - index_->length());
3316
if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock))
3317
return; // Error already logged.
3320
Note that there are both comments that describe what the
3321
code is doing, and comments that mention that an error has
3322
already been logged when the function returns.
3325
If you have several comments on subsequent lines, it can
3326
often be more readable to line them up:
3329
DoSomething(); // Comment here so the comments line up.
3330
DoSomethingElseThatIsLonger(); // Comment here so there are two spaces between
3331
// the code and the comment.
3332
{ // One space before comment when opening a new scope is allowed,
3333
// thus the comment lines up with the following comments and code.
3334
DoSomethingElse(); // Two spaces before line comments normally.
3338
<SUBSECTION title="NULL, true/false, 1, 2, 3...">
3340
When you pass in <code>NULL</code>, boolean, or literal integer
3341
values to functions, you should consider adding a comment about
3342
what they are, or make your code self-documenting by using
3343
constants. For example, compare:
3346
bool success = CalculateSomething(interesting_value,
3349
NULL); // What are these arguments??
3355
bool success = CalculateSomething(interesting_value,
3356
10, // Default base value.
3357
false, // Not the first time we're calling this.
3358
NULL); // No callback.
3361
Or alternatively, constants or self-describing variables:
3364
const int kDefaultBaseValue = 10;
3365
const bool kFirstTimeCalling = false;
3366
Callback *null_callback = NULL;
3367
bool success = CalculateSomething(interesting_value,
3374
<SUBSECTION title="Don'ts">
3376
Note that you should <em>never</em> describe the code
3377
itself. Assume that the person reading the code knows C++
3378
better than you do, even though he or she does not know what
3379
you are trying to do:
3382
// Now go through the b array and make sure that if i occurs,
3383
// the next element is i+1.
3384
... // Geez. What a useless comment.
3390
<STYLEPOINT title="Punctuation, Spelling and Grammar">
3392
Pay attention to punctuation, spelling, and grammar; it is
3393
easier to read well-written comments than badly written ones.
3397
Comments should usually be written as complete
3398
sentences with proper capitalization and periods at the end.
3399
Shorter comments, such as comments at the end of a line of
3400
code, can sometimes be less formal, but you should be
3401
consistent with your style. Complete sentences are more
3402
readable, and they provide some assurance that the comment is
3403
complete and not an unfinished thought.
3406
Although it can be frustrating to have a code reviewer point
3407
out that you are using a comma when you should be using a
3408
semicolon, it is very important that source code maintain a
3409
high level of clarity and readability. Proper punctuation,
3410
spelling, and grammar help with that goal.
3415
<STYLEPOINT title="TODO Comments">
3417
Use <code>TODO</code> comments for code that is temporary, a
3418
short-term solution, or good-enough but not perfect.
3422
<code>TODO</code>s should include the string <code>TODO</code> in
3423
all caps, followed by the
3425
name, e-mail address, or other
3427
of the person who can best provide context about the problem
3428
referenced by the <code>TODO</code>. A colon is optional. The main
3429
purpose is to have a consistent <code>TODO</code> format that can be
3430
searched to find the person who can provide more details upon request.
3431
A <code>TODO</code> is not a commitment that the person referenced
3432
will fix the problem. Thus when you create a <code>TODO</code>, it is
3440
// TODO(kl@gmail.com): Use a "*" here for concatenation operator.
3441
// TODO(Zeke) change this to use relations.
3444
If your <code>TODO</code> is of the form "At a future date do
3445
something" make sure that you either include a very specific
3446
date ("Fix by November 2005") or a very specific event
3447
("Remove this code when all clients can handle XML responses.").
3452
<STYLEPOINT title="Deprecation Comments">
3454
Mark deprecated interface points with <code>DEPRECATED</code> comments.
3458
You can mark an interface as deprecated by writing a comment containing
3459
the word <code>DEPRECATED</code> in all caps. The comment goes either
3460
before the declaration of the interface or on the same line as the
3465
After the word <code>DEPRECATED</code>, write your name, e-mail address,
3466
or other identifier in parentheses.
3469
A deprecation comment must include simple, clear directions for people to
3470
fix their callsites. In C++, you can implement a deprecated function as
3471
an inline function that calls the new interface point.
3474
Marking an interface point <code>DEPRECATED</code> will not magically
3475
cause any callsites to change. If you want people to actually stop using
3476
the deprecated facility, you will have to fix the callsites yourself or
3477
recruit a crew to help you.
3480
New code should not contain calls to deprecated interface points. Use
3481
the new interface point instead. If you cannot understand the
3482
directions, find the person who created the deprecation and ask them for
3483
help using the new interface point.
3491
<CATEGORY title="Formatting">
3493
Coding style and formatting are pretty arbitrary, but a
3496
is much easier to follow if everyone uses the same style. Individuals
3497
may not agree with every aspect of the formatting rules, and some of
3498
the rules may take some getting used to, but it is important that all
3500
project contributors
3501
follow the style rules so that
3504
can all read and understand everyone's code easily.
3508
To help you format code correctly, we've created a <A HREF="http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el">settings
3512
<STYLEPOINT title="Line Length">
3514
Each line of text in your code should be at most 80 characters
3520
We recognize that this rule is controversial, but so much existing
3521
code already adheres to it, and we feel that consistency is
3528
that it is rude to force them to resize their windows and there
3529
is no need for anything longer. Some folks are used to having
3530
several code windows side-by-side, and thus don't have room to
3531
widen their windows in any case. People set up their work
3532
environment assuming a particular maximum window width, and 80
3533
columns has been the traditional standard. Why change it?
3536
Proponents of change argue that a wider line can make code
3537
more readable. The 80-column limit is an hidebound
3538
throwback to 1960s mainframes;
3540
modern equipment has
3541
wide screens that can easily show longer lines.
3546
80 characters is the maximum.
3549
Exception: if a comment line contains an example command or
3550
a literal URL longer than 80 characters, that line may be
3551
longer than 80 characters for ease of cut and paste.
3554
Exception: an <code>#include</code> statement with a long
3555
path may exceed 80 columns. Try to avoid situations where this
3559
Exception: you needn't be concerned about
3560
<a href="#The__define_Guard">header guards</a>
3561
that exceed the maximum length.
3568
<STYLEPOINT title="Non-ASCII Characters">
3570
Non-ASCII characters should be rare, and must use UTF-8 formatting.
3574
You shouldn't hard-code user-facing text in source, even English,
3575
so use of non-ASCII characters should be rare. However, in certain
3576
cases it is appropriate to include such words in your code. For
3577
example, if your code parses data files from foreign sources,
3578
it may be appropriate to hard-code the non-ASCII string(s) used in
3579
those data files as delimiters. More commonly, unittest code
3582
need to be localized) might contain non-ASCII strings. In such
3583
cases, you should use UTF-8, since that is
3585
an encoding understood by most tools able
3586
to handle more than just ASCII.
3587
Hex encoding is also OK, and encouraged where it enhances
3588
readability — for example, <code>"\xEF\xBB\xBF"</code> is the
3589
Unicode zero-width no-break space character, which would be
3590
invisible if included in the source as straight UTF-8.
3595
<STYLEPOINT title="Spaces vs. Tabs">
3597
Use only spaces, and indent 2 spaces at a time.
3601
We use spaces for indentation. Do not use tabs in your code.
3602
You should set your editor to emit spaces when you hit the tab
3608
<STYLEPOINT title="Function Declarations and Definitions">
3610
Return type on the same line as function name, parameters on the
3611
same line if they fit.
3615
Functions look like this:
3618
ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
3624
If you have too much text to fit on one line:
3627
ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,
3634
or if you cannot fit even the first parameter:
3637
ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
3638
Type par_name1, // 4 space indent
3641
DoSomething(); // 2 space indent
3646
Some points to note:
3649
<li> The return type is always on the same line as the
3652
<li> The open parenthesis is always on the same line as the
3655
<li> There is never a space between the function name and the
3658
<li> There is never a space between the parentheses and the
3661
<li> The open curly brace is always at the end of the same
3662
line as the last parameter.
3664
<li> The close curly brace is either on the last line by itself
3665
or (if other style rules permit) on the same line as the
3668
<li> There should be a space between the close parenthesis and
3669
the open curly brace.
3671
<li> All parameters should be named, with identical names in the
3672
declaration and implementation.
3674
<li> All parameters should be aligned if possible.
3676
<li> Default indentation is 2 spaces.
3678
<li> Wrapped parameters have a 4 space indent.
3682
If your function is <code>const</code>, the <code>const</code>
3683
keyword should be on the same line as the last parameter:
3686
// Everything in this function signature fits on a single line
3687
ReturnType FunctionName(Type par) const {
3691
// This function signature requires multiple lines, but
3692
// the const keyword is on the line with the last parameter.
3693
ReturnType ReallyLongFunctionName(Type par1,
3699
If some parameters are unused, comment out the variable name in the
3700
function definition:
3703
// Always have named parameters in interfaces.
3706
virtual void Rotate(double radians) = 0;
3709
// Always have named parameters in the declaration.
3710
class Circle : public Shape {
3712
virtual void Rotate(double radians);
3715
// Comment out unused named parameters in definitions.
3716
void Circle::Rotate(double /*radians*/) {}
3719
// Bad - if someone wants to implement later, it's not clear what the
3721
void Circle::Rotate(double) {}
3726
<STYLEPOINT title="Function Calls">
3728
On one line if it fits; otherwise, wrap arguments at the
3733
Function calls have the following format:
3736
bool retval = DoSomething(argument1, argument2, argument3);
3739
If the arguments do not all fit on one line, they should be
3740
broken up onto multiple lines, with each subsequent line
3741
aligned with the first argument. Do not add spaces after the
3742
open paren or before the close paren:
3745
bool retval = DoSomething(averyveryveryverylongargument1,
3746
argument2, argument3);
3749
If the function has many arguments, consider having one per
3750
line if this makes the code more readable:
3753
bool retval = DoSomething(argument1,
3759
If the function signature is so long that it cannot fit within
3760
the maximum <a href="#Line_Length">line length</a>, you may
3761
place all arguments on subsequent lines:
3768
DoSomethingThatRequiresALongFunctionName(
3769
very_long_argument1, // 4 space indent
3778
<STYLEPOINT title="Conditionals">
3780
Prefer no spaces inside parentheses. The <code>else</code>
3781
keyword belongs on a new line.
3785
There are two acceptable formats for a basic conditional
3786
statement. One includes spaces between the parentheses and the
3787
condition, and one does not.
3790
The most common form is without spaces. Either is fine, but
3791
<em>be consistent</em>. If you are modifying a file, use the
3792
format that is already present. If you are writing new code,
3793
use the format that the other files in that directory or
3794
project use. If in doubt and you have no personal preference,
3795
do not add the spaces.
3798
if (condition) { // no spaces inside parentheses
3799
... // 2 space indent.
3800
} else { // The else goes on the same line as the closing brace.
3805
If you prefer you may add spaces inside the
3809
if ( condition ) { // spaces inside parentheses - rare
3810
... // 2 space indent.
3811
} else { // The else goes on the same line as the closing brace.
3816
Note that in all cases you must have a space between the
3817
<code>if</code> and the open parenthesis. You must also have
3818
a space between the close parenthesis and the curly brace, if
3822
if(condition) // Bad - space missing after IF.
3823
if (condition){ // Bad - space missing before {.
3824
if(condition){ // Doubly bad.
3827
if (condition) { // Good - proper space after IF and before {.
3830
Short conditional statements may be written on one line if
3831
this enhances readability. You may use this only when the
3832
line is brief and the statement does not use the
3833
<code>else</code> clause.
3836
if (x == kFoo) return new Foo();
3837
if (x == kBar) return new Bar();
3840
This is not allowed when the if statement has an
3844
// Not allowed - IF statement on one line when there is an ELSE clause
3849
In general, curly braces are not required for single-line
3850
statements, but they are allowed if you like them;
3851
conditional or loop statements with complex conditions or
3852
statements may be more readable with curly braces. Some
3855
require that an <CODE>if</CODE> must always always have an
3860
DoSomething(); // 2 space indent.
3863
DoSomething(); // 2 space indent.
3867
However, if one part of an <code>if</code>-<code>else</code>
3868
statement uses curly braces, the other part must too:
3871
// Not allowed - curly on IF but not ELSE
3877
// Not allowed - curly on ELSE but not IF
3885
// Curly braces around both IF and ELSE required because
3886
// one of the clauses used braces.
3896
<STYLEPOINT title="Loops and Switch Statements">
3898
Switch statements may use braces for blocks. Empty loop bodies should use
3899
<code>{}</code> or <code>continue</code>.
3903
<code>case</code> blocks in <code>switch</code> statements can have
3904
curly braces or not, depending on your preference. If you do
3905
include curly braces they should be placed as shown below.
3908
If not conditional on an enumerated value, switch statements
3909
should always have a <code>default</code> case (in the case of
3910
an enumerated value, the compiler will warn you if any values
3911
are not handled). If the default case should never execute,
3913
<code>assert</code>:
3918
case 0: { // 2 space indent
3919
... // 4 space indent
3932
Empty loop bodies should use <code>{}</code> or
3933
<code>continue</code>, but not a single semicolon.
3937
// Repeat test until it returns false.
3939
for (int i = 0; i < kSomeNumber; ++i) {} // Good - empty body.
3940
while (condition) continue; // Good - continue indicates no logic.
3943
while (condition); // Bad - looks like part of do/while loop.
3948
<STYLEPOINT title="Pointer and Reference Expressions">
3950
No spaces around period or arrow. Pointer operators do not have
3955
The following are examples of correctly-formatted pointer and
3956
reference expressions:
3968
<li> There are no spaces around the period or arrow when
3971
<li> Pointer operators have no space after the <code>*</code> or
3976
When declaring a pointer variable or argument, you may place
3977
the asterisk adjacent to either the type or to the variable
3981
// These are fine, space preceding.
3983
const string &str;
3985
// These are fine, space following.
3986
char* c; // but remember to do "char* c, *d, *e, ...;"!
3987
const string& str;
3990
char * c; // Bad - spaces on both sides of *
3991
const string & str; // Bad - spaces on both sides of &
3994
You should do this consistently within a single
3996
so, when modifying an existing file, use the style in that
4002
<STYLEPOINT title="Boolean Expressions">
4004
When you have a boolean expression that is longer than the <a href="#Line_Length">standard line length</a>, be consistent in
4005
how you break up the lines.
4009
In this example, the logical AND operator is always at the end
4013
if (this_one_thing > this_other_thing &&
4014
a_third_thing == a_fourth_thing &&
4015
yet_another && last_one) {
4020
Note that when the code wraps in this example, both of
4021
the <code>&&</code> logical AND operators are at the
4022
end of the line. Feel free to insert extra parentheses judiciously,
4023
because they can be very helpful in increasing readability
4024
when used appropriately. Also note that you should always use the
4025
punctuation operators, such as <code>&&</code> and
4026
<code>~</code>, rather than the word operators, such as <code>and</code>
4027
and <code>compl</code>.
4032
<STYLEPOINT title="Return Values">
4034
Do not needlessly surround the <code>return</code> expression with
4039
Use parentheses in <code>return expr;</code> only where you would use
4040
them in <code>x = expr;</code>.
4043
return result; // No parentheses in the simple case.
4044
return (some_long_condition && // Parentheses ok to make a complex
4045
another_condition); // expression more readable.
4048
return (value); // You wouldn't write var = (value);
4049
return(result); // return is not a function!
4056
<STYLEPOINT title="Variable and Array Initialization">
4058
Your choice of <code>=</code> or <code>()</code>.
4062
You may choose between <code>=</code> and <code>()</code>; the
4063
following are all correct:
4068
string name("Some Name");
4069
string name = "Some Name";
4074
<STYLEPOINT title="Preprocessor Directives">
4076
The hash mark that starts a preprocessor directive should
4077
always be at the beginning of the line.
4081
Even when preprocessor directives are within the body of
4082
indented code, the directives should start at the beginning of
4086
// Good - directives at beginning of line
4087
if (lopsided_score) {
4088
#if DISASTER_PENDING // Correct -- Starts at beginning of line
4090
# if NOTIFY // OK but not required -- Spaces after #
4098
// Bad - indented directives
4099
if (lopsided_score) {
4100
#if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line
4102
#endif // Wrong! Do not indent "#endif"
4109
<STYLEPOINT title="Class Format">
4111
Sections in <code>public</code>, <code>protected</code> and
4112
<code>private</code> order, each indented one space.
4116
The basic format for a class declaration (lacking the
4117
comments, see <a HREF="#Class_Comments">Class Comments</a> for
4118
a discussion of what comments are needed) is:
4121
class MyClass : public OtherClass {
4122
public: // Note the 1 space indent!
4123
MyClass(); // Regular 2 space indent.
4124
explicit MyClass(int var);
4127
void SomeFunction();
4128
void SomeFunctionThatDoesNothing() {
4131
void set_some_var(int var) { some_var_ = var; }
4132
int some_var() const { return some_var_; }
4135
bool SomeInternalFunction();
4138
int some_other_var_;
4139
DISALLOW_COPY_AND_ASSIGN(MyClass);
4146
<li> Any base class name should be on the same line as the
4147
subclass name, subject to the 80-column limit.
4149
<li> The <code>public:</code>, <code>protected:</code>, and
4150
<code>private:</code> keywords should be indented one
4153
<li> Except for the first instance, these keywords should be preceded
4154
by a blank line. This rule is optional in small classes.
4156
<li> Do not leave a blank line after these keywords.
4158
<li> The <code>public</code> section should be first, followed by
4159
the <code>protected</code> and finally the
4160
<code>private</code> section.
4162
<li> See <a HREF="#Declaration_Order">Declaration Order</a> for
4163
rules on ordering declarations within each of these sections.
4169
<STYLEPOINT title="Constructor Initializer Lists">
4171
Constructor initializer lists can be all on one line or with
4172
subsequent lines indented four spaces.
4176
There are two acceptable formats for initializer lists:
4179
// When it all fits on one line:
4180
MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {}
4186
// When it requires multiple lines, indent 4 spaces, putting the colon on
4187
// the first initializer line:
4188
MyClass::MyClass(int var)
4189
: some_var_(var), // 4 space indent
4190
some_other_var_(var + 1) { // lined up
4199
<STYLEPOINT title="Namespace Formatting">
4201
The contents of namespaces are not indented.
4205
<a href="#Namespaces">Namespaces</a> do not add an extra level of
4206
indentation. For example, use:
4211
void foo() { // Correct. No extra indentation within namespace.
4218
Do not indent within a namespace:
4223
// Wrong. Indented when it should not be.
4231
When declaring nested namespaces, put each namespace on its own line.
4240
<STYLEPOINT title="Horizontal Whitespace">
4242
Use of horizontal whitespace depends on location. Never put trailing
4243
whitespace at the end of a line.
4246
<SUBSECTION title="General">
4248
void f(bool b) { // Open braces should always have a space before them.
4250
int i = 0; // Semicolons usually have no space before them.
4251
int x[] = { 0 }; // Spaces inside braces for array initialization are
4252
int x[] = {0}; // optional. If you use them, put them on both sides!
4253
// Spaces around the colon in inheritance and initializer lists.
4254
class Foo : public Bar {
4256
// For inline function implementations, put spaces between the braces
4257
// and the implementation itself.
4258
Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces.
4259
void Reset() { baz_ = 0; } // Spaces separating braces from implementation.
4263
Adding trailing whitespace can cause extra work for others editing
4264
the same file, when they merge, as can removing existing trailing
4265
whitespace. So: Don't introduce trailing whitespace. Remove it
4266
if you're already changing that line, or do it in a separate
4269
operation (preferably when no-one else
4270
is working on the file).
4273
<SUBSECTION title="Loops and Conditionals">
4275
if (b) { // Space after the keyword in conditions and loops.
4276
} else { // Spaces around else.
4278
while (test) {} // There is usually no space inside parentheses.
4280
for (int i = 0; i < 5; ++i) {
4281
switch ( i ) { // Loops and conditions may have spaces inside
4282
if ( test ) { // parentheses, but this is rare. Be consistent.
4283
for ( int i = 0; i < 5; ++i ) {
4284
for ( ; i < 5 ; ++i) { // For loops always have a space after the
4285
... // semicolon, and may have a space before the
4288
case 1: // No space before colon in a switch case.
4290
case 2: break; // Use a space after a colon if there's code after it.
4293
<SUBSECTION title="Operators">
4295
x = 0; // Assignment operators always have spaces around
4297
x = -5; // No spaces separating unary operators and their
4299
if (x && !y)
4301
v = w * x + y / z; // Binary operators usually have spaces around them,
4302
v = w*x + y/z; // but it's okay to remove spaces around factors.
4303
v = w * (x + z); // Parentheses should have no spaces inside them.
4306
<SUBSECTION title="Templates and Casts">
4308
vector<string> x; // No spaces inside the angle
4309
y = static_cast<char*>(x); // brackets (< and >), before
4310
// <, or between >( in a cast.
4311
vector<char *> x; // Spaces between type and pointer are
4312
// okay, but be consistent.
4313
set<list<string> > x; // C++ requires a space in > >.
4314
set< list<string> > x; // You may optionally use
4315
// symmetric spacing in < <.
4322
<STYLEPOINT title="Vertical Whitespace">
4324
Minimize use of vertical whitespace.
4328
This is more a principle than a rule: don't use blank lines
4329
when you don't have to. In particular, don't put more than
4330
one or two blank lines between functions, resist starting
4331
functions with a blank line, don't end functions with a blank
4332
line, and be discriminating with your use of blank lines
4336
The basic principle is: The more code that fits on one screen,
4337
the easier it is to follow and understand the control flow of
4338
the program. Of course, readability can suffer from code
4339
being too dense as well as too spread out, so use your
4340
judgement. But in general, minimize use of vertical
4344
Some rules of thumb to help when blank lines may be useful:
4347
<li> Blank lines at the beginning or end of a function very
4348
rarely help readability.
4350
<li> Blank lines inside a chain of if-else blocks may well
4358
<CATEGORY title="Exceptions to the Rules">
4360
The coding conventions described above are mandatory. However,
4361
like all good rules, these sometimes have exceptions, which we
4367
<STYLEPOINT title="Existing Non-conformant Code">
4369
You may diverge from the rules when dealing with code that does not
4370
conform to this style guide.
4374
If you find yourself modifying code that was written to
4375
specifications other than those presented by this guide, you may
4376
have to diverge from these rules in order to stay consistent with
4377
the local conventions in that code. If you are in doubt about
4378
how to do this, ask the original author or the person currently
4379
responsible for the code. Remember that <em>consistency</em>
4380
includes local consistency, too.
4389
Use common sense and <em>BE CONSISTENT</em>.
4392
If you are editing code, take a few minutes to look at the
4393
code around you and determine its style. If they use spaces
4394
around their <code>if</code> clauses, you should, too. If
4395
their comments have little boxes of stars around them, make
4396
your comments have little boxes of stars around them too.
4399
The point of having style guidelines is to have a common
4400
vocabulary of coding so people can concentrate on what you are
4401
saying, rather than on how you are saying it. We present
4402
global style rules here so people know the vocabulary. But
4403
local style is also important. If code you add to a file
4404
looks drastically different from the existing code around it,
4405
the discontinuity throws readers out of their rhythm when they
4406
go to read it. Try to avoid this.
4410
OK, enough writing about writing code; the code itself is much
4411
more interesting. Have fun!