2
<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
3
<GUIDE title="Google C++ Style Guide">
14
Craig Silverstein<br/>
21
<CATEGORY title="Important Note">
22
<STYLEPOINT title="Displaying Hidden Details in this Guide">
24
This style guide contains many details that are initially
25
hidden from view. They are marked by the triangle icon, which you
26
see here on your left. Click it now.
27
You should see "Hooray" appear below.
31
Hooray! Now you know you can expand points to get more
32
details. Alternatively, there's an "expand all" at the
38
<CATEGORY title="Background">
40
C++ is the main development language
42
used by many of Google's open-source
44
As every C++ programmer knows, the language has many powerful features,
45
but this power brings with it complexity, which in turn can make code
46
more bug-prone and harder to read and maintain.
49
The goal of this guide is to manage this complexity by describing
50
in detail the dos and don'ts of writing C++
51
code. These rules exist to
55
code base manageable while still allowing coders to use C++ language
56
features productively.
59
<em>Style</em>, also known as readability, is what we call the
60
conventions that govern our C++ code. The term Style is a bit of a
61
misnomer, since these conventions cover far more than just source
65
One way in which we keep the code base manageable is by enforcing
68
It is very important that any
71
be able to look at another's code and quickly understand it.
72
Maintaining a uniform style and following conventions means that we can
73
more easily use "pattern-matching" to infer what various symbols are
74
and what invariants are true about them. Creating common, required
75
idioms and patterns makes code much easier to understand. In some
76
cases there might be good arguments for changing certain style
77
rules, but we nonetheless keep things as they are in order to
81
Another issue this guide addresses is that of C++ feature bloat.
82
C++ is a huge language with many advanced features. In some cases
83
we constrain, or even ban, use of certain features. We do this to
84
keep code simple and to avoid the various common errors and
85
problems that these features can cause. This guide lists these
86
features and explains why their use is restricted.
90
Open-source projects developed by Google
91
conform to the requirements in this guide.
95
Note that this guide is not a C++ tutorial: we assume that the
96
reader is familiar with the language.
103
<CATEGORY title="Header Files">
105
In general, every <code>.cc</code> file should have an associated
106
<code>.h</code> file. There are some common exceptions, such as
109
and small <code>.cc</code> files containing just a <code>main()</code>
113
Correct use of header files can make a huge difference to the
114
readability, size and performance of your code.
117
The following rules will guide you through the various pitfalls of
121
<STYLEPOINT title="The #define Guard">
123
All header files should have <code>#define</code> guards to
124
prevent multiple inclusion. The format of the symbol name
126
<code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.
131
To guarantee uniqueness, they should be based on the full path
132
in a project's source tree. For example, the file
133
<code>foo/src/bar/baz.h</code> in project <code>foo</code> should
134
have the following guard:
137
#ifndef FOO_BAR_BAZ_H_
138
#define FOO_BAR_BAZ_H_
142
#endif // FOO_BAR_BAZ_H_
148
<STYLEPOINT title="Header File Dependencies">
150
Don't use an <code>#include</code> when a forward declaration
155
When you include a header file you introduce a dependency that
156
will cause your code to be recompiled whenever the header file
157
changes. If your header file includes other header files, any
158
change to those files will cause any code that includes your
159
header to be recompiled. Therefore, we prefer to minimize
160
includes, particularly includes of header files in other
164
You can significantly reduce the number of header files you
165
need to include in your own header files by using forward
166
declarations. For example, if your header file uses the
167
<code>File</code> class in ways that do not require access to
168
the declaration of the <code>File</code> class, your header
169
file can just forward declare <code>class File;</code> instead
170
of having to <code>#include "file/base/file.h"</code>.
173
How can we use a class <code>Foo</code> in a header file
174
without access to its definition?
177
<li> We can declare data members of type <code>Foo*</code> or
178
<code>Foo&</code>.
180
<li> We can declare (but not define) functions with arguments,
181
and/or return values, of type <code>Foo</code>. (One
182
exception is if an argument <code>Foo</code>
183
or <code>const Foo&</code> has a
184
non-<code>explicit</code>, one-argument constructor,
186
in which case we need the full definition to support
187
automatic type conversion.)
189
<li> We can declare static data members of type
190
<code>Foo</code>. This is because static data members
191
are defined outside the class definition.
195
On the other hand, you must include the header file for
196
<code>Foo</code> if your class subclasses <code>Foo</code> or
197
has a data member of type <code>Foo</code>.
200
Sometimes it makes sense to have pointer (or better,
201
<code>scoped_ptr</code>)
202
members instead of object members. However, this complicates code
203
readability and imposes a performance penalty, so avoid doing
204
this transformation if the only purpose is to minimize includes
208
Of course, <code>.cc</code> files typically do require the
209
definitions of the classes they use, and usually have to
210
include several header files.
213
<SUBSECTION title="Note:">
214
If you use a symbol <code>Foo</code> in your source file, you
215
should bring in a definition for <code>Foo</code> yourself,
216
either via an #include or via a forward declaration. Do not
217
depend on the symbol being brought in transitively via headers
218
not directly included. One exception is if <code>Foo</code>
219
is used in <code>myfile.cc</code>, it's ok to #include (or
220
forward-declare) <code>Foo</code> in <code>myfile.h</code>,
221
instead of <code>myfile.cc</code>.
226
<STYLEPOINT title="Inline Functions">
228
Define functions inline only when they are small, say, 10 lines
233
You can declare functions in a way that allows the compiler to
234
expand them inline rather than calling them through the usual
235
function call mechanism.
238
Inlining a function can generate more efficient object code,
239
as long as the inlined function is small. Feel free to inline
240
accessors and mutators, and other short, performance-critical
244
Overuse of inlining can actually make programs slower.
245
Depending on a function's size, inlining it can cause the code
246
size to increase or decrease. Inlining a very small accessor
247
function will usually decrease code size while inlining a very
248
large function can dramatically increase code size. On modern
249
processors smaller code usually runs faster due to better use
250
of the instruction cache.
254
A decent rule of thumb is to not inline a function if it is
255
more than 10 lines long. Beware of destructors, which are
256
often longer than they appear because of implicit member-
257
and base-destructor calls!
260
Another useful rule of thumb: it's typically not cost
261
effective to inline functions with loops or switch
262
statements (unless, in the common case, the loop or switch
263
statement is never executed).
266
It is important to know that functions are not always
267
inlined even if they are declared as such; for example,
268
virtual and recursive functions are not normally inlined.
269
Usually recursive functions should not be inline. The main
270
reason for making a virtual function inline is to place its
271
definition in the class, either for convenience or to
272
document its behavior, e.g., for accessors and mutators.
278
<STYLEPOINT title="The -inl.h Files">
280
You may use file names with a <code>-inl.h</code> suffix to define
281
complex inline functions when needed.
285
The definition of an inline function needs to be in a header
286
file, so that the compiler has the definition available for
287
inlining at the call sites. However, implementation code
288
properly belongs in <code>.cc</code> files, and we do not like
289
to have much actual code in <code>.h</code> files unless there
290
is a readability or performance advantage.
293
If an inline function definition is short, with very little,
294
if any, logic in it, you should put the code in your
295
<code>.h</code> file. For example, accessors and mutators
296
should certainly be inside a class definition. More complex
297
inline functions may also be put in a <code>.h</code> file for
298
the convenience of the implementer and callers, though if this
299
makes the <code>.h</code> file too unwieldy you can instead
300
put that code in a separate <code>-inl.h</code> file.
301
This separates the implementation from the class definition,
302
while still allowing the implementation to be included where
306
Another use of <code>-inl.h</code> files is for definitions of
307
function templates. This can be used to keep your template
308
definitions easy to read.
311
Do not forget that a <code>-inl.h</code> file requires a
312
<a href="#The__define_Guard"><code>#define</code> guard</a> just
313
like any other header file.
319
<STYLEPOINT title="Function Parameter Ordering">
321
When defining a function, parameter order is: inputs,
326
Parameters to C/C++ functions are either input to the
327
function, output from the function, or both. Input parameters
328
are usually values or <code>const</code> references, while output
329
and input/output parameters will be non-<code>const</code>
330
pointers. When ordering function parameters, put all input-only
331
parameters before any output parameters. In particular, do not add
332
new parameters to the end of the function just because they are
333
new; place new input-only parameters before the output
337
This is not a hard-and-fast rule. Parameters that are both
338
input and output (often classes/structs) muddy the waters,
339
and, as always, consistency with related functions may require
340
you to bend the rule.
345
<STYLEPOINT title="Names and Order of Includes">
347
Use standard order for readability and to avoid hidden
348
dependencies: C library, C++ library,
350
other libraries' <code>.h</code>, your
357
All of a project's header files should be
358
listed as descendants of the project's source directory
359
without use of UNIX directory shortcuts <code>.</code> (the current
360
directory) or <code>..</code> (the parent directory). For
363
<code>google-awesome-project/src/base/logging.h</code>
364
should be included as
367
#include "base/logging.h"
370
In <code><var>dir/foo</var>.cc</code> or <code><var>dir/foo_test</var>.cc</code>,
371
whose main purpose is to implement or test the stuff in
372
<code><var>dir2/foo2</var>.h</code>, order your includes as
376
<li> <code><var>dir2/foo2</var>.h</code> (preferred location
377
— see details below).</li>
378
<li> C system files.</li>
379
<li> C++ system files.</li>
380
<li> Other libraries' <code>.h</code> files.</li>
383
<code>.h</code> files.</li>
386
The preferred ordering reduces hidden dependencies. We want
387
every header file to be compilable on its own. The easiest
388
way to achieve this is to make sure that every one of them is
389
the first <code>.h</code> file <code>#include</code>d in some
393
<code><var>dir/foo</var>.cc</code> and
394
<code><var>dir2/foo2</var>.h</code> are often in the same
395
directory (e.g. <code>base/basictypes_test.cc</code> and
396
<code>base/basictypes.h</code>), but can be in different
401
Within each section it is nice to order the includes
405
For example, the includes in
407
<code>google-awesome-project/src/foo/internal/fooserver.cc</code>
408
might look like this:
411
#include "foo/public/fooserver.h" // Preferred location.
413
#include <sys/types.h>
414
#include <unistd.h>
416
#include <hash_map>
417
#include <vector>
419
#include "base/basictypes.h"
420
#include "base/commandlineflags.h"
421
#include "foo/public/bar.h"
427
<CATEGORY title="Scoping">
428
<STYLEPOINT title="Namespaces">
430
Unnamed namespaces in <code>.cc</code> files are encouraged. With
431
named namespaces, choose the name based on the
433
project, and possibly its path.
434
Do not use a <SYNTAX>using-directive</SYNTAX>.
438
Namespaces subdivide the global scope into distinct, named
439
scopes, and so are useful for preventing name collisions in
444
Namespaces provide a (hierarchical) axis of naming, in
445
addition to the (also hierarchical) name axis provided by
449
For example, if two different projects have a class
450
<code>Foo</code> in the global scope, these symbols may
451
collide at compile time or at runtime. If each project
452
places their code in a namespace, <code>project1::Foo</code>
453
and <code>project2::Foo</code> are now distinct symbols that
459
Namespaces can be confusing, because they provide an
460
additional (hierarchical) axis of naming, in addition to the
461
(also hierarchical) name axis provided by classes.
464
Use of unnamed spaces in header files can easily cause
465
violations of the C++ One Definition Rule (ODR).
470
Use namespaces according to the policy described below.
473
<SUBSECTION title="Unnamed Namespaces">
475
<li> Unnamed namespaces are allowed and even encouraged in
476
<code>.cc</code> files, to avoid runtime naming
479
namespace { // This is in a .cc file.
481
// The content of a namespace is not indented
482
enum { kUnused, kEOF, kError }; // Commonly used tokens.
483
bool AtEof() { return pos_ == kEOF; } // Uses our namespace's EOF.
489
However, file-scope declarations that are
490
associated with a particular class may be declared
491
in that class as types, static data members or
492
static member functions rather than as members of
493
an unnamed namespace. Terminate the unnamed
494
namespace as shown, with a comment <code>//
498
<li> Do not use unnamed namespaces in <code>.h</code>
504
<SUBSECTION title="Named Namespaces">
506
Named namespaces should be used as follows:
509
<li> Namespaces wrap the entire source file after includes,
511
<a href="http://google-gflags.googlecode.com/">gflags</a>
512
definitions/declarations, and forward declarations of classes
513
from other namespaces:
516
namespace mynamespace {
518
// All declarations are within the namespace scope.
519
// Notice the lack of indentation.
526
} // namespace mynamespace
530
namespace mynamespace {
532
// Definition of functions is within scope of the namespace.
533
void MyClass::Foo() {
537
} // namespace mynamespace
540
The typical <code>.cc</code> file might have more
541
complex detail, including the need to reference classes
547
DEFINE_bool(someflag, false, "dummy flag");
549
class C; // Forward declaration of class C in the global namespace.
550
namespace a { class A; } // Forward declaration of a::A.
554
...code for b... // Code goes against the left margin.
562
<li> Do not declare anything in namespace
563
<code>std</code>, not even forward declarations of
564
standard library classes. Declaring entities in
565
namespace <code>std</code> is undefined behavior,
566
i.e., not portable. To declare entities from the
567
standard library, include the appropriate header
571
<li> You may not use a <SYNTAX>using-directive</SYNTAX> to
572
make all names from a namespace available.
574
// Forbidden -- This pollutes the namespace.
579
<li> You may use a <SYNTAX>using-declaration</SYNTAX>
580
anywhere in a <code>.cc</code> file, and in functions,
581
methods or classes in <code>.h</code> files.
584
// Must be in a function, method or class in .h files.
589
<li> Namespace aliases are allowed anywhere in a
590
<code>.cc</code> file, anywhere inside the named
591
namespace that wraps an entire <code>.h</code> file,
592
and in functions and methods.
594
// Shorten access to some commonly used names in .cc files.
595
namespace fbz = ::foo::bar::baz;
597
// Shorten access to some commonly used names (in a .h file).
598
namespace librarian {
599
// The following alias is available to all files including
600
// this header (in namespace librarian):
601
// alias names should therefore be chosen consistently
603
namespace pd_s = ::pipeline_diagnostics::sidetable;
605
inline void my_inline_function() {
606
// namespace alias local to a function (or method).
607
namespace fbz = ::foo::bar::baz;
610
} // namespace librarian
613
Note that an alias in a .h file is visible to everyone
614
#including that file, so public headers (those available
615
outside a project) and headers transitively #included by them,
616
should avoid defining aliases, as part of the general
617
goal of keeping public APIs as small as possible.
632
<STYLEPOINT title="Nested Classes">
634
Although you may use public nested classes when they are part of
635
an interface, consider a <a HREF="#Namespaces">namespace</a> to
636
keep declarations out of the global scope.
640
A class can define another class within it; this is also
641
called a <SYNTAX>member class</SYNTAX>.
646
// Bar is a member class, nested within Foo.
655
This is useful when the nested (or member) class is only used
656
by the enclosing class; making it a member puts it in the
657
enclosing class scope rather than polluting the outer scope
658
with the class name. Nested classes can be forward declared
659
within the enclosing class and then defined in the
660
<code>.cc</code> file to avoid including the nested class
661
definition in the enclosing class declaration, since the
662
nested class definition is usually only relevant to the
666
Nested classes can be forward-declared only within the
667
definition of the enclosing class. Thus, any header file
668
manipulating a <code>Foo::Bar*</code> pointer will have to
669
include the full class declaration for <code>Foo</code>.
672
Do not make nested classes public unless they are actually
673
part of the interface, e.g., a class that holds a set of
674
options for some method.
680
<STYLEPOINT title="Nonmember, Static Member, and Global Functions">
682
Prefer nonmember functions within a namespace or static member
683
functions to global functions; use completely global functions
688
Nonmember and static member functions can be useful in some
689
situations. Putting nonmember functions in a namespace avoids
690
polluting the global namespace.
693
Nonmember and static member functions may make more sense as
694
members of a new class, especially if they access external
695
resources or have significant dependencies.
699
Sometimes it is useful, or even necessary, to define a
700
function not bound to a class instance. Such a function can
701
be either a static member or a nonmember function.
702
Nonmember functions should not depend on external variables,
703
and should nearly always exist in a namespace. Rather than
704
creating classes only to group static member functions which
705
do not share static data, use
706
<a href="#Namespaces">namespaces</a> instead.
709
Functions defined in the same compilation unit as production
710
classes may introduce unnecessary coupling and link-time
711
dependencies when directly called from other compilation
712
units; static member functions are particularly susceptible
713
to this. Consider extracting a new class, or placing the
714
functions in a namespace possibly in a separate library.
717
If you must define a nonmember function and it is only
718
needed in its <code>.cc</code> file, use an unnamed
719
<a HREF="#Namespaces">namespace</a> or <code>static</code>
720
linkage (eg <code>static int Foo() {...}</code>) to limit
727
<STYLEPOINT title="Local Variables">
729
Place a function's variables in the narrowest scope possible,
730
and initialize variables in the declaration.
734
C++ allows you to declare variables anywhere in a function.
735
We encourage you to declare them in as local a scope as
736
possible, and as close to the first use as possible. This
737
makes it easier for the reader to find the declaration and see
738
what type the variable is and what it was initialized to. In
739
particular, initialization should be used instead of
740
declaration and assignment, e.g.
744
i = f(); // Bad -- initialization separate from declaration.
747
int j = g(); // Good -- declaration has initialization.
750
Note that gcc implements <code>for (int i = 0; i
751
< 10; ++i)</code> correctly (the scope of <code>i</code> is
752
only the scope of the <code>for</code> loop), so you can then
753
reuse <code>i</code> in another <code>for</code> loop in the
754
same scope. It also correctly scopes declarations in
755
<code>if</code> and <code>while</code> statements, e.g.
758
while (const char* p = strchr(str, '/')) str = p + 1;
761
There is one caveat: if the variable is an object, its
762
constructor is invoked every time it enters scope and is
763
created, and its destructor is invoked every time it goes
767
// Inefficient implementation:
768
for (int i = 0; i < 1000000; ++i) {
769
Foo f; // My ctor and dtor get called 1000000 times each.
774
It may be more efficient to declare such a variable used in a
775
loop outside that loop:
778
Foo f; // My ctor and dtor get called once each.
779
for (int i = 0; i < 1000000; ++i) {
786
<STYLEPOINT title="Static and Global Variables">
788
Static or global variables of class type are forbidden: they cause
789
hard-to-find bugs due to indeterminate order of construction and
794
Objects with static storage duration, including global variables,
795
static variables, static class member variables, and function static
796
variables, must be Plain Old Data (POD): only ints, chars, floats, or
797
pointers, or arrays/structs of POD.
800
The order in which class constructors and initializers for
801
static variables are called is only partially specified in C++ and can
802
even change from build to build, which can cause bugs that are difficult
803
to find. Therefore in addition to banning globals of class type, we do
804
not allow static POD variables to be initialized with the result of a
805
function, unless that function (such as getenv(), or getpid()) does not
806
itself depend on any other globals.
809
Likewise, the order in which destructors are called is defined to be the
810
reverse of the order in which the constructors were called. Since
811
constructor order is indeterminate, so is destructor order.
812
For example, at program-end time a static variable might have
813
been destroyed, but code still running -- perhaps in another thread --
814
tries to access it and fails. Or the destructor for a static 'string'
815
variable might be run prior to the destructor for another variable that
816
contains a reference to that string.
819
As a result we only allow static variables to contain POD data. This
820
rule completely disallows <code>vector</code> (use C arrays instead), or
821
<code>string</code> (use <code>const char []</code>).
825
If you need a static or global variable of a class type, consider
826
initializing a pointer (which will never be freed), from either your
827
main() function or from pthread_once(). Note that this must be a raw
828
pointer, not a "smart" pointer, since the smart pointer's destructor
829
will have the order-of-destructor issue that we are trying to avoid.
837
<CATEGORY title="Classes">
838
Classes are the fundamental unit of code in C++. Naturally, we use
839
them extensively. This section lists the main dos and don'ts you
840
should follow when writing a class.
842
<STYLEPOINT title="Doing Work in Constructors">
844
In general, constructors should merely set member variables to their
845
initial values. Any complex initialization should go in an explicit
846
<code>Init()</code> method.
850
It is possible to perform initialization in the body of the
854
Convenience in typing. No need to worry about whether the
855
class has been initialized or not.
858
The problems with doing work in constructors are:
860
<li> There is no easy way for constructors to signal errors,
861
short of using exceptions (which are
862
<a HREF="#Exceptions">forbidden</a>).
864
<li> If the work fails, we now have an object whose
865
initialization code failed, so it may be an
868
<li> If the work calls virtual functions, these calls will
869
not get dispatched to the subclass implementations.
870
Future modification to your class can quietly introduce
871
this problem even if your class is not currently
872
subclassed, causing much confusion.
874
<li> If someone creates a global variable of this type
875
(which is against the rules, but still), the
876
constructor code will be called before
877
<code>main()</code>, possibly breaking some implicit
878
assumptions in the constructor code. For instance,
880
<a href="http://google-gflags.googlecode.com/">gflags</a>
881
will not yet have been initialized.
886
If your object requires non-trivial initialization, consider
887
having an explicit <code>Init()</code> method. In particular,
888
constructors should not call virtual functions, attempt to raise
889
errors, access potentially uninitialized global variables, etc.
894
<STYLEPOINT title="Default Constructors">
896
You must define a default constructor if your class defines
897
member variables and has no other constructors. Otherwise the
898
compiler will do it for you, badly.
902
The default constructor is called when we <code>new</code> a
903
class object with no arguments. It is always called when
904
calling <code>new[]</code> (for arrays).
907
Initializing structures by default, to hold "impossible"
908
values, makes debugging much easier.
911
Extra work for you, the code writer.
915
If your class defines member variables and has no other
916
constructors you must define a default constructor (one that
917
takes no arguments). It should preferably initialize the
918
object in such a way that its internal state is consistent
922
The reason for this is that if you have no other
923
constructors and do not define a default constructor, the
924
compiler will generate one for you. This compiler
925
generated constructor may not initialize your object
929
If your class inherits from an existing class but you add no
930
new member variables, you are not required to have a default
938
<STYLEPOINT title="Explicit Constructors">
940
Use the C++ keyword <code>explicit</code> for constructors with
945
Normally, if a constructor takes one argument, it can be used
946
as a conversion. For instance, if you define
947
<code>Foo::Foo(string name)</code> and then pass a string to a
948
function that expects a <code>Foo</code>, the constructor will
949
be called to convert the string into a <code>Foo</code> and
950
will pass the <code>Foo</code> to your function for you. This
951
can be convenient but is also a source of trouble when things
952
get converted and new objects created without you meaning them
953
to. Declaring a constructor <code>explicit</code> prevents it
954
from being invoked implicitly as a conversion.
957
Avoids undesirable conversions.
964
We require all single argument constructors to be
965
explicit. Always put <code>explicit</code> in front of
966
one-argument constructors in the class definition:
967
<code>explicit Foo(string name);</code>
970
The exception is copy constructors, which, in the rare
971
cases when we allow them, should probably not be
972
<code>explicit</code>.
974
Classes that are intended to be
975
transparent wrappers around other classes are also
977
Such exceptions should be clearly marked with comments.
983
<STYLEPOINT title="Copy Constructors">
985
Provide a copy constructor and assignment operator only when necessary.
986
Otherwise, disable them with <code>DISALLOW_COPY_AND_ASSIGN</code>.
990
The copy constructor and assignment operator are used to create copies
991
of objects. The copy constructor is implicitly invoked by the
992
compiler in some situations, e.g. passing objects by value.
995
Copy constructors make it easy to copy objects. STL
996
containers require that all contents be copyable and
997
assignable. Copy constructors can be more efficient than
998
<code>CopyFrom()</code>-style workarounds because they combine
999
construction with copying, the compiler can elide them in some
1000
contexts, and they make it easier to avoid heap allocation.
1003
Implicit copying of objects in C++ is a rich source of bugs
1004
and of performance problems. It also reduces readability, as
1005
it becomes hard to track which objects are being passed around
1006
by value as opposed to by reference, and therefore where
1007
changes to an object are reflected.
1011
Few classes need to be copyable. Most should have neither a
1012
copy constructor nor an assignment operator. In many situations,
1013
a pointer or reference will work just as well as a copied value,
1014
with better performance. For example, you can pass function
1015
parameters by reference or pointer instead of by value, and you can
1016
store pointers rather than objects in an STL container.
1019
If your class needs to be copyable, prefer providing a copy method,
1020
such as <code>CopyFrom()</code> or <code>Clone()</code>, rather than
1021
a copy constructor, because such methods cannot be invoked
1022
implicitly. If a copy method is insufficient in your situation
1023
(e.g. for performance reasons, or because your class needs to be
1024
stored by value in an STL container), provide both a copy
1025
constructor and assignment operator.
1028
If your class does not need a copy constructor or assignment
1029
operator, you must explicitly disable them.
1032
To do so, add dummy declarations for the copy constructor and
1033
assignment operator in the <code>private:</code> section of your
1034
class, but do not provide any corresponding definition (so that
1035
any attempt to use them results in a link error).
1038
For convenience, a <code>DISALLOW_COPY_AND_ASSIGN</code> macro
1042
// A macro to disallow the copy constructor and operator= functions
1043
// This should be used in the private: declarations for a class
1044
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
1045
TypeName(const TypeName&); \
1046
void operator=(const TypeName&)
1049
Then, in <code>class Foo</code>:
1058
DISALLOW_COPY_AND_ASSIGN(Foo);
1068
<STYLEPOINT title="Structs vs. Classes">
1070
Use a <code>struct</code> only for passive objects that carry data;
1071
everything else is a <code>class</code>.
1075
The <code>struct</code> and <code>class</code> keywords behave
1076
almost identically in C++. We add our own semantic meanings
1077
to each keyword, so you should use the appropriate keyword for
1078
the data-type you're defining.
1081
<code>structs</code> should be used for passive objects that carry
1082
data, and may have associated constants, but lack any functionality
1083
other than access/setting the data members. The
1084
accessing/setting of fields is done by directly accessing the
1085
fields rather than through method invocations. Methods should
1086
not provide behavior but should only be used to set up the
1087
data members, e.g., constructor, destructor,
1088
<code>Initialize()</code>, <code>Reset()</code>,
1089
<code>Validate()</code>.
1092
If more functionality is required, a <code>class</code> is more
1093
appropriate. If in doubt, make it a <code>class</code>.
1096
For consistency with STL, you can use <code>struct</code>
1097
instead of <code>class</code> for functors and traits.
1100
Note that member variables in structs and classes have
1101
<a HREF="#Variable_Names">different naming rules</a>.
1106
<STYLEPOINT title="Inheritance">
1108
Composition is often more appropriate than inheritance. When
1109
using inheritance, make it <code>public</code>.
1113
When a sub-class inherits from a base class, it includes the
1114
definitions of all the data and operations that the parent
1115
base class defines. In practice, inheritance is used in two
1116
major ways in C++: implementation inheritance, in which
1117
actual code is inherited by the child, and <A HREF="#Interfaces">interface inheritance</A>, in which only
1118
method names are inherited.
1121
Implementation inheritance reduces code size by re-using the
1122
base class code as it specializes an existing type. Because
1123
inheritance is a compile-time declaration, you and the
1124
compiler can understand the operation and detect errors.
1125
Interface inheritance can be used to programmatically enforce
1126
that a class expose a particular API. Again, the compiler
1127
can detect errors, in this case, when a class does not define
1128
a necessary method of the API.
1131
For implementation inheritance, because the code implementing
1132
a sub-class is spread between the base and the sub-class, it
1133
can be more difficult to understand an implementation. The
1134
sub-class cannot override functions that are not virtual, so
1135
the sub-class cannot change implementation. The base class
1136
may also define some data members, so that specifies physical
1137
layout of the base class.
1141
All inheritance should be <code>public</code>. If you want to
1142
do private inheritance, you should be including an instance of
1143
the base class as a member instead.
1146
Do not overuse implementation inheritance. Composition is
1147
often more appropriate. Try to restrict use of inheritance
1148
to the "is-a" case: <code>Bar</code> subclasses
1149
<code>Foo</code> if it can reasonably be said that
1150
<code>Bar</code> "is a kind of" <code>Foo</code>.
1153
Make your destructor <code>virtual</code> if necessary. If
1154
your class has virtual methods, its destructor
1159
Limit the use of <code>protected</code> to those member
1160
functions that might need to be accessed from subclasses.
1161
Note that <a href="#Access_Control">data members should
1165
When redefining an inherited virtual function, explicitly
1166
declare it <code>virtual</code> in the declaration of the
1167
derived class. Rationale: If <code>virtual</code> is
1168
omitted, the reader has to check all ancestors of the
1169
class in question to determine if the function is virtual
1176
<STYLEPOINT title="Multiple Inheritance">
1178
Only very rarely is multiple implementation inheritance actually
1179
useful. We allow multiple inheritance only when at most one of
1180
the base classes has an implementation; all other base classes
1181
must be <A HREF="#Interfaces">pure interface</A> classes tagged
1182
with the <code>Interface</code> suffix.
1186
Multiple inheritance allows a sub-class to have more than one
1187
base class. We distinguish between base classes that are
1188
<em>pure interfaces</em> and those that have an
1189
<em>implementation</em>.
1192
Multiple implementation inheritance may let you re-use even more code
1193
than single inheritance (see <a HREF="#Inheritance">Inheritance</a>).
1196
Only very rarely is multiple <em>implementation</em>
1197
inheritance actually useful. When multiple implementation
1198
inheritance seems like the solution, you can usually find a
1199
different, more explicit, and cleaner solution.
1202
Multiple inheritance is allowed only when all superclasses, with the
1203
possible exception of the first one, are <A HREF="#Interfaces">pure
1204
interfaces</A>. In order to ensure that they remain pure interfaces,
1205
they must end with the <code>Interface</code> suffix.
1206
<SUBSECTION title="Note:">
1207
There is an <a HREF="#Windows_Code">exception</a> to this
1214
<STYLEPOINT title="Interfaces">
1216
Classes that satisfy certain conditions are allowed, but not required, to
1217
end with an <code>Interface</code> suffix.
1222
A class is a pure interface if it meets the following requirements:
1225
<li> It has only public pure virtual ("<code>= 0</code>") methods
1226
and static methods (but see below for destructor).
1228
<li> It may not have non-static data members.
1230
<li> It need not have any constructors defined. If a constructor is
1231
provided, it must take no arguments and it must be protected.
1233
<li> If it is a subclass, it may only be derived from classes
1234
that satisfy these conditions and are tagged with the
1235
<code>Interface</code> suffix.
1239
An interface class can never be directly instantiated
1240
because of the pure virtual method(s) it declares. To make
1241
sure all implementations of the interface can be destroyed
1242
correctly, they must also declare a virtual destructor (in
1243
an exception to the first rule, this should not be pure). See
1244
Stroustrup, <cite>The C++ Programming Language</cite>, 3rd
1245
edition, section 12.4 for details.
1249
Tagging a class with the <code>Interface</code> suffix lets
1250
others know that they must not add implemented methods or non
1251
static data members. This is particularly important in the case of
1252
<A HREF="#Multiple_Inheritance">multiple inheritance</A>.
1253
Additionally, the interface concept is already well-understood by
1257
The <code>Interface</code> suffix lengthens the class name, which
1258
can make it harder to read and understand. Also, the interface
1259
property may be considered an implementation detail that shouldn't
1260
be exposed to clients.
1263
A class may end with <code>Interface</code> only if it meets the
1264
above requirements. We do not require the converse, however:
1265
classes that meet the above requirements are not required to end
1266
with <code>Interface</code>.
1271
<STYLEPOINT title="Operator Overloading">
1273
Do not overload operators except in rare, special circumstances.
1277
A class can define that operators such as <code>+</code> and
1278
<code>/</code> operate on the class as if it were a built-in
1282
Can make code appear more intuitive because a class will
1283
behave in the same way as built-in types (such as
1284
<code>int</code>). Overloaded operators are more playful
1285
names for functions that are less-colorfully named, such as
1286
<code>Equals()</code> or <code>Add()</code>. For some
1287
template functions to work correctly, you may need to define
1291
While operator overloading can make code more intuitive, it
1292
has several drawbacks:
1294
<li> It can fool our intuition into thinking that expensive
1295
operations are cheap, built-in operations.
1297
<li> It is much harder to find the call sites for overloaded
1298
operators. Searching for <code>Equals()</code> is much
1299
easier than searching for relevant invocations of
1302
<li> Some operators work on pointers too, making it easy to
1303
introduce bugs. <code>Foo + 4</code> may do one thing,
1304
while <code>&Foo + 4</code> does something totally
1305
different. The compiler does not complain for either of
1306
these, making this very hard to debug.
1309
Overloading also has surprising ramifications. For instance,
1310
if a class overloads unary <code>operator&</code>, it
1311
cannot safely be forward-declared.
1315
In general, do not overload operators. The assignment operator
1316
(<code>operator=</code>), in particular, is insidious and
1317
should be avoided. You can define functions like
1318
<code>Equals()</code> and <code>CopyFrom()</code> if you
1319
need them. Likewise, avoid the dangerous
1320
unary <code>operator&</code> at all costs, if there's
1321
any possibility the class might be forward-declared.
1324
However, there may be rare cases where you need to overload
1325
an operator to interoperate with templates or "standard" C++
1326
classes (such as <code>operator<<(ostream&, const
1327
T&)</code> for logging). These are acceptable if fully
1328
justified, but you should try to avoid these whenever
1329
possible. In particular, do not overload <code>operator==</code>
1330
or <code>operator<</code> just so that your class can be
1331
used as a key in an STL container; instead, you should
1332
create equality and comparison functor types when declaring
1336
Some of the STL algorithms do require you to overload
1337
<code>operator==</code>, and you may do so in these cases,
1338
provided you document why.
1341
See also <a HREF="#Copy_Constructors">Copy Constructors</a>
1342
and <a HREF="#Function_Overloading">Function
1349
<STYLEPOINT title="Access Control">
1351
Make data members <code>private</code>, and provide
1352
access to them through accessor functions as needed (for
1353
technical reasons, we allow data members of a test fixture class
1354
to be <code>protected</code> when using
1356
<A HREF="http://code.google.com/p/googletest/">
1357
Google Test</A>). Typically a variable would be
1358
called <code>foo_</code> and the accessor function
1359
<code>foo()</code>. You may also want a mutator function
1360
<code>set_foo()</code>.
1361
Exception: <code>static const</code> data members (typically
1362
called <code>kFoo</code>) need not be <code>private</code>.
1366
The definitions of accessors are usually inlined in the header
1370
See also <a HREF="#Inheritance">Inheritance</a> and <a HREF="#Function_Names">Function Names</a>.
1375
<STYLEPOINT title="Declaration Order">
1377
Use the specified order of declarations within a class:
1378
<code>public:</code> before <code>private:</code>, methods
1379
before data members (variables), etc.
1383
Your class definition should start with its <code>public:</code>
1384
section, followed by its <code>protected:</code> section and
1385
then its <code>private:</code> section. If any of these sections
1386
are empty, omit them.
1389
Within each section, the declarations generally should be in
1390
the following order:
1393
<li> Typedefs and Enums</li>
1394
<li> Constants (<code>static const</code> data members)</li>
1395
<li> Constructors</li>
1396
<li> Destructor</li>
1397
<li> Methods, including static methods</li>
1398
<li> Data Members (except <code>static const</code> data members)</li>
1401
Friend declarations should always be in the private section, and
1402
the <code>DISALLOW_COPY_AND_ASSIGN</code> macro invocation
1403
should be at the end of the <code>private:</code> section. It
1404
should be the last thing in the class. See <a HREF="#Copy_Constructors">Copy Constructors</a>.
1407
Method definitions in the corresponding <code>.cc</code> file
1408
should be the same as the declaration order, as much as possible.
1411
Do not put large method definitions inline in the class
1412
definition. Usually, only trivial or performance-critical,
1413
and very short, methods may be defined inline. See <a HREF="#Inline_Functions">Inline Functions</a> for more
1419
<STYLEPOINT title="Write Short Functions">
1421
Prefer small and focused functions.
1425
We recognize that long functions are sometimes appropriate, so
1426
no hard limit is placed on functions length. If a function
1427
exceeds about 40 lines, think about whether it can be broken
1428
up without harming the structure of the program.
1431
Even if your long function works perfectly now, someone
1432
modifying it in a few months may add new behavior. This could
1433
result in bugs that are hard to find. Keeping your functions
1434
short and simple makes it easier for other people to read and
1438
You could find long and complicated functions when working
1442
code. Do not be intimidated by modifying existing
1443
code: if working with such a function proves to be difficult,
1444
you find that errors are hard to debug, or you want to use a
1445
piece of it in several different contexts, consider breaking
1446
up the function into smaller and more manageable pieces.
1452
<CATEGORY title="Google-Specific Magic">
1455
There are various tricks and utilities that we use to make C++
1456
code more robust, and various ways we use C++ that may differ from
1457
what you see elsewhere.
1462
<STYLEPOINT title="Smart Pointers">
1465
If you actually need pointer semantics, <code>scoped_ptr</code>
1466
is great. You should only use <code>std::tr1::shared_ptr</code>
1467
with a non-const referent when it is truly necessary to share ownership
1468
of an object (e.g. inside an STL container). You should never use
1469
<code>auto_ptr</code>.
1473
"Smart" pointers are objects that act like pointers, but automate
1474
management of the underlying memory.
1477
Smart pointers are extremely useful for preventing memory leaks, and
1478
are essential for writing exception-safe code. They also formalize
1479
and document the ownership of dynamically allocated memory.
1482
We prefer designs in which objects have single, fixed owners. Smart
1483
pointers which enable sharing or transfer of ownership can act as a
1484
tempting alternative to a careful design of ownership semantics,
1485
leading to confusing code and even bugs in which memory is never
1486
deleted. The semantics of smart pointers (especially
1487
<code>auto_ptr</code>) can be nonobvious and confusing. The
1488
exception-safety benefits of smart pointers are not decisive, since
1489
we do not allow exceptions.
1493
<dt><code>scoped_ptr</code></dt>
1494
<dd>Straightforward and risk-free. Use wherever appropriate.</dd>
1495
<dt><code>auto_ptr</code></dt>
1496
<dd>Confusing and bug-prone ownership-transfer semantics. Do not use.
1498
<dt><code>shared_ptr</code></dt>
1500
Safe with const referents (i.e. <code>shared_ptr<const
1501
T></code>). Reference-counted pointers with non-const referents
1502
can occasionally be the best design, but try to rewrite with single
1503
owners where possible.
1510
<STYLEPOINT title="cpplint">
1513
<code>cpplint.py</code>
1514
to detect style errors.
1518
<code>cpplint.py</code>
1519
is a tool that reads a source file and
1520
identifies many style errors. It is not perfect, and has both false
1521
positives and false negatives, but it is still a valuable tool. False
1522
positives can be ignored by putting <code>// NOLINT</code> at
1523
the end of the line.
1527
Some projects have instructions on how to run <code>cpplint.py</code>
1528
from their project tools. If the project you are contributing to does
1529
not, you can download <A HREF="http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py"><code>cpplint.py</code></A> separately.
1537
<CATEGORY title="Other C++ Features">
1538
<STYLEPOINT title="Reference Arguments">
1540
All parameters passed by reference must be labeled
1545
In C, if a function needs to modify a variable, the
1546
parameter must use a pointer, eg <code>int foo(int
1547
*pval)</code>. In C++, the function can alternatively
1548
declare a reference parameter: <code>int foo(int
1552
Defining a parameter as reference avoids ugly code like
1553
<code>(*pval)++</code>. Necessary for some applications like
1554
copy constructors. Makes it clear, unlike with pointers, that
1555
<code>NULL</code> is not a possible value.
1558
References can be confusing, as they have value syntax but
1563
Within function parameter lists all references must be
1567
void Foo(const string &in, string *out);
1570
In fact it is a very strong convention in Google code that input
1571
arguments are values or <code>const</code> references while
1572
output arguments are pointers. Input parameters may be
1573
<code>const</code> pointers, but we never allow
1574
non-<code>const</code> reference parameters.
1577
One case when you might want an input parameter to be a
1578
<code>const</code> pointer is if you want to emphasize that the
1579
argument is not copied, so it must exist for the lifetime of the
1580
object; it is usually best to document this in comments as
1581
well. STL adapters such as <code>bind2nd</code> and
1582
<code>mem_fun</code> do not permit reference parameters, so
1583
you must declare functions with pointer parameters in these
1590
<STYLEPOINT title="Function Overloading">
1592
Use overloaded functions (including constructors) only if a
1593
reader looking at a call site can get a good idea of what is
1594
happening without having to first figure out exactly which
1595
overload is being called.
1600
You may write a function that takes a
1601
<code>const string&</code> and overload it with another that
1602
takes <code>const char*</code>.
1607
void Analyze(const string &text);
1608
void Analyze(const char *text, size_t textlen);
1613
Overloading can make code more intuitive by allowing an
1614
identically-named function to take different arguments. It
1615
may be necessary for templatized code, and it can be
1616
convenient for Visitors.
1619
If a function is overloaded by the argument types alone, a
1620
reader may have to understand C++'s complex matching rules in
1621
order to tell what's going on. Also many people are confused
1622
by the semantics of inheritance if a derived class overrides
1623
only some of the variants of a function.
1626
If you want to overload a function, consider qualifying the
1627
name with some information about the arguments, e.g.,
1628
<code>AppendString()</code>, <code>AppendInt()</code> rather
1629
than just <code>Append()</code>.
1635
<STYLEPOINT title="Default Arguments">
1637
We do not allow default function parameters, except in
1638
a few uncommon situations explained below.
1642
Often you have a function that uses lots of default values,
1643
but occasionally you want to override the defaults. Default
1644
parameters allow an easy way to do this without having to
1645
define many functions for the rare exceptions.
1648
People often figure out how to use an
1649
API by looking at existing code that uses it.
1650
Default parameters are more difficult to maintain because
1651
copy-and-paste from previous code may not reveal all the
1652
parameters. Copy-and-pasting of code segments can cause major
1653
problems when the default arguments are not appropriate for
1658
Except as described below, we require all arguments to be
1659
explicitly specified, to force programmers to consider the API
1660
and the values they are passing for each argument rather than
1661
silently accepting defaults they may not be aware of.
1664
One specific exception is when default arguments are used to
1665
simulate variable-length argument lists.
1668
// Support up to 4 params by using a default empty AlphaNum.
1669
string StrCat(const AlphaNum &a,
1670
const AlphaNum &b = gEmptyAlphaNum,
1671
const AlphaNum &c = gEmptyAlphaNum,
1672
const AlphaNum &d = gEmptyAlphaNum);
1678
<STYLEPOINT title="Variable-Length Arrays and alloca()">
1680
We do not allow variable-length arrays or <code>alloca()</code>.
1684
Variable-length arrays have natural-looking syntax. Both
1685
variable-length arrays and <code>alloca()</code> are very
1689
Variable-length arrays and alloca are not part of Standard
1690
C++. More importantly, they allocate a data-dependent amount
1691
of stack space that can trigger difficult-to-find memory
1692
overwriting bugs: "It ran fine on my machine, but dies
1693
mysteriously in production".
1697
Use a safe allocator instead, such as
1698
<code>scoped_ptr</code>/<code>scoped_array</code>.
1703
<STYLEPOINT title="Friends">
1705
We allow use of <code>friend</code> classes and functions,
1710
Friends should usually be defined in the same file so that the
1711
reader does not have to look in another file to find uses of
1712
the private members of a class. A common use of
1713
<code>friend</code> is to have a <code>FooBuilder</code> class
1714
be a friend of <code>Foo</code> so that it can construct the
1715
inner state of <code>Foo</code> correctly, without exposing
1716
this state to the world. In some cases it may be useful to
1717
make a unittest class a friend of the class it tests.
1720
Friends extend, but do not break, the encapsulation
1721
boundary of a class. In some cases this is better than making
1722
a member public when you want to give only one other class
1723
access to it. However, most classes should interact with
1724
other classes solely through their public members.
1729
<STYLEPOINT title="Exceptions">
1731
We do not use C++ exceptions.
1736
<li>Exceptions allow higher levels of an application to
1737
decide how to handle "can't happen" failures in deeply
1738
nested functions, without the obscuring and error-prone
1739
bookkeeping of error codes.</li>
1743
<li>Exceptions are used by most other modern
1744
languages. Using them in C++ would make it more consistent with
1745
Python, Java, and the C++ that others are familiar with.</li>
1747
<li>Some third-party C++ libraries use exceptions, and turning
1748
them off internally makes it harder to integrate with those
1751
<li>Exceptions are the only way for a constructor to fail.
1752
We can simulate this with a factory function or an
1753
<code>Init()</code> method, but these require heap
1754
allocation or a new "invalid" state, respectively.</li>
1756
<li>Exceptions are really handy in testing frameworks.</li>
1761
<li>When you add a <code>throw</code> statement to an existing
1762
function, you must examine all of its transitive callers. Either
1763
they must make at least the basic exception safety guarantee, or
1764
they must never catch the exception and be happy with the
1765
program terminating as a result. For instance, if
1766
<code>f()</code> calls <code>g()</code> calls
1767
<code>h()</code>, and <code>h</code> throws an exception
1768
that <code>f</code> catches, <code>g</code> has to be
1769
careful or it may not clean up properly.</li>
1771
<li>More generally, exceptions make the control flow of
1772
programs difficult to evaluate by looking at code: functions
1773
may return in places you don't expect. This causes
1774
maintainability and debugging difficulties. You can minimize
1775
this cost via some rules on how and where exceptions can be
1776
used, but at the cost of more that a developer needs to know
1777
and understand.</li>
1779
<li>Exception safety requires both RAII and different coding
1780
practices. Lots of supporting machinery is needed to make
1781
writing correct exception-safe code easy. Further, to avoid
1782
requiring readers to understand the entire call graph,
1783
exception-safe code must isolate logic that writes to
1784
persistent state into a "commit" phase. This will have both
1785
benefits and costs (perhaps where you're forced to obfuscate
1786
code to isolate the commit). Allowing exceptions would force
1787
us to always pay those costs even when they're not worth
1790
<li>Turning on exceptions adds data to each binary produced,
1791
increasing compile time (probably slightly) and possibly
1792
increasing address space pressure.
1795
<li>The availability of exceptions may encourage developers
1796
to throw them when they are not appropriate or recover from
1797
them when it's not safe to do so. For example, invalid user
1798
input should not cause exceptions to be thrown. We would
1799
need to make the style guide even longer to document these
1805
On their face, the benefits of using exceptions outweigh the
1806
costs, especially in new projects. However, for existing code,
1807
the introduction of exceptions has implications on all dependent
1808
code. If exceptions can be propagated beyond a new project, it
1809
also becomes problematic to integrate the new project into
1810
existing exception-free code. Because most existing C++ code at
1811
Google is not prepared to deal with exceptions, it is
1812
comparatively difficult to adopt new code that generates
1816
Given that Google's existing code is not exception-tolerant, the
1817
costs of using exceptions are somewhat greater than the costs in
1818
a new project. The conversion process would be slow and
1819
error-prone. We don't believe that the available alternatives to
1820
exceptions, such as error codes and assertions, introduce a
1825
Our advice against using exceptions is not predicated on
1826
philosophical or moral grounds, but practical ones.
1828
Because we'd like to use our open-source
1829
projects at Google and it's difficult to do so if those projects
1830
use exceptions, we need to advise against exceptions in Google
1831
open-source projects as well.
1832
Things would probably be different if we had to do it all over
1836
There is an <a HREF="#Windows_Code">exception</a> to this
1837
rule (no pun intended) for Windows code.
1843
<STYLEPOINT title="Run-Time Type Information (RTTI)">
1845
We do not use Run Time Type Information (RTTI).
1849
RTTI allows a programmer to query the C++ class of an
1854
It is useful in some unittests. For example, it is useful in
1855
tests of factory classes where the test has to verify that a
1856
newly created object has the expected dynamic type.
1859
In rare circumstances, it is useful even outside of
1864
A query of type during run-time typically means a
1865
design problem. If you need to know the type of an
1866
object at runtime, that is often an indication that
1867
you should reconsider the design of your class.
1871
Do not use RTTI, except in unittests. If you find yourself
1872
in need of writing code that behaves differently based on
1873
the class of an object, consider one of the alternatives to
1877
Virtual methods are the preferred way of executing different
1878
code paths depending on a specific subclass type. This puts
1879
the work within the object itself.
1882
If the work belongs outside the object and instead in some
1883
processing code, consider a double-dispatch solution, such
1884
as the Visitor design pattern. This allows a facility
1885
outside the object itself to determine the type of class
1886
using the built-in type system.
1889
If you think you truly cannot use those ideas,
1891
you may use RTTI. But think twice
1892
about it. :-) Then think twice again.
1893
Do not hand-implement an RTTI-like workaround. The arguments
1894
against RTTI apply just as much to workarounds like class
1895
hierarchies with type tags.
1901
<STYLEPOINT title="Casting">
1903
Use C++ casts like <code>static_cast<>()</code>. Do not use
1904
other cast formats like <code>int y = (int)x;</code> or
1905
<code>int y = int(x);</code>.
1909
C++ introduced a different cast system from C that
1910
distinguishes the types of cast operations.
1913
The problem with C casts is the ambiguity of the operation;
1914
sometimes you are doing a <em>conversion</em> (e.g.,
1915
<code>(int)3.5</code>) and sometimes you are doing a
1916
<em>cast</em> (e.g., <code>(int)"hello"</code>); C++ casts
1917
avoid this. Additionally C++ casts are more visible when
1921
The syntax is nasty.
1925
Do not use C-style casts. Instead, use these C++-style
1931
<li> Use <code>static_cast</code> as the equivalent of a
1932
C-style cast that does value conversion, or when you need to explicitly up-cast
1933
a pointer from a class to its superclass.
1935
<li> Use <code>const_cast</code> to remove the <code>const</code>
1936
qualifier (see <a HREF="#Use_of_const">const</a>).
1940
<li> Use <code>reinterpret_cast</code> to do unsafe
1941
conversions of pointer types to and from integer and
1942
other pointer types. Use this only if you know what you are
1943
doing and you understand the aliasing issues.
1946
<li> Do not use <code>dynamic_cast</code> except in test code.
1947
If you need to know type information at runtime in this way
1948
outside of a unittest, you probably have a <A HREF="#Run-Time_Type_Information__RTTI_">design
1956
<STYLEPOINT title="Streams">
1958
Use streams only for logging.
1962
Streams are a replacement for <code>printf()</code> and
1963
<code>scanf()</code>.
1966
With streams, you do not need to know the type of the object
1967
you are printing. You do not have problems with format
1968
strings not matching the argument list. (Though with gcc, you
1969
do not have that problem with <code>printf</code> either.) Streams
1970
have automatic constructors and destructors that open and close the
1974
Streams make it difficult to do functionality like
1975
<code>pread()</code>. Some formatting (particularly the common
1976
format string idiom <code>%.*s</code>) is difficult if not
1977
impossible to do efficiently using streams without using
1978
<code>printf</code>-like hacks. Streams do not support operator
1979
reordering (the <code>%1s</code> directive), which is helpful for
1980
internationalization.
1985
Do not use streams, except where required by a logging interface.
1986
Use <code>printf</code>-like routines instead.
1989
There are various pros and cons to using streams, but in
1990
this case, as in many other cases, consistency trumps the
1991
debate. Do not use streams in your code.
1994
<SUBSECTION title="Extended Discussion">
1996
There has been debate on this issue, so this explains the
1997
reasoning in greater depth. Recall the Only One Way
1998
guiding principle: we want to make sure that whenever we
1999
do a certain type of I/O, the code looks the same in all
2000
those places. Because of this, we do not want to allow
2001
users to decide between using streams or using
2002
<code>printf</code> plus Read/Write/etc. Instead, we should
2003
settle on one or the other. We made an exception for logging
2004
because it is a pretty specialized application, and for
2008
Proponents of streams have argued that streams are the obvious
2009
choice of the two, but the issue is not actually so clear. For
2010
every advantage of streams they point out, there is an
2011
equivalent disadvantage. The biggest advantage is that
2012
you do not need to know the type of the object to be
2013
printing. This is a fair point. But, there is a
2014
downside: you can easily use the wrong type, and the
2015
compiler will not warn you. It is easy to make this
2016
kind of mistake without knowing when using streams.
2019
cout << this; // Prints the address
2020
cout << *this; // Prints the contents
2023
The compiler does not generate an error because
2024
<code><<</code> has been overloaded. We discourage
2025
overloading for just this reason.
2028
Some say <code>printf</code> formatting is ugly and hard to
2029
read, but streams are often no better. Consider the following
2030
two fragments, both with the same typo. Which is easier to
2034
cerr << "Error connecting to '" << foo->bar()->hostname.first
2035
<< ":" << foo->bar()->hostname.second << ": " << strerror(errno);
2037
fprintf(stderr, "Error connecting to '%s:%u: %s",
2038
foo->bar()->hostname.first, foo->bar()->hostname.second,
2042
And so on and so forth for any issue you might bring up.
2043
(You could argue, "Things would be better with the right
2044
wrappers," but if it is true for one scheme, is it not
2045
also true for the other? Also, remember the goal is to
2046
make the language smaller, not add yet more machinery that
2047
someone has to learn.)
2050
Either path would yield different advantages and
2051
disadvantages, and there is not a clearly superior
2052
solution. The simplicity doctrine mandates we settle on
2053
one of them though, and the majority decision was on
2054
<code>printf</code> + <code>read</code>/<code>write</code>.
2061
<STYLEPOINT title="Preincrement and Predecrement">
2063
Use prefix form (<code>++i</code>) of the increment and
2064
decrement operators with iterators and other template objects.
2068
When a variable is incremented (<code>++i</code> or
2069
<code>i++</code>) or decremented (<code>--i</code> or
2070
<code>i--</code>) and the value of the expression is not used,
2071
one must decide whether to preincrement (decrement) or
2072
postincrement (decrement).
2075
When the return value is ignored, the "pre" form
2076
(<code>++i</code>) is never less efficient than the "post"
2077
form (<code>i++</code>), and is often more efficient. This is
2078
because post-increment (or decrement) requires a copy of
2079
<code>i</code> to be made, which is the value of the
2080
expression. If <code>i</code> is an iterator or other
2081
non-scalar type, copying <code>i</code> could be expensive.
2082
Since the two types of increment behave the same when the
2083
value is ignored, why not just always pre-increment?
2086
The tradition developed, in C, of using post-increment when
2087
the expression value is not used, especially in <code>for</code>
2088
loops. Some find post-increment easier to read, since the
2089
"subject" (<code>i</code>) precedes the "verb" (<code>++</code>),
2090
just like in English.
2093
For simple scalar (non-object) values there is no reason to
2094
prefer one form and we allow either. For iterators and other
2095
template types, use pre-increment.
2100
<STYLEPOINT title="Use of const">
2102
We strongly recommend that you use <code>const</code> whenever
2103
it makes sense to do so.
2107
Declared variables and parameters can be preceded by the
2108
keyword <code>const</code> to indicate the variables are not
2109
changed (e.g., <code>const int foo</code>). Class functions
2110
can have the <code>const</code> qualifier to indicate the
2111
function does not change the state of the class member
2112
variables (e.g., <code>class Foo { int Bar(char c) const;
2116
Easier for people to understand how variables are being used.
2117
Allows the compiler to do better type checking, and,
2118
conceivably, generate better code. Helps people convince
2119
themselves of program correctness because they know the
2120
functions they call are limited in how they can modify your
2121
variables. Helps people know what functions are safe to use
2122
without locks in multi-threaded programs.
2125
<code>const</code> is viral: if you pass a <code>const</code>
2126
variable to a function, that function must have <code>const</code>
2127
in its prototype (or the variable will need a
2128
<code>const_cast</code>). This can be a particular problem
2129
when calling library functions.
2133
<code>const</code> variables, data members, methods and
2134
arguments add a level of compile-time type checking; it
2135
is better to detect errors as soon as possible.
2136
Therefore we strongly recommend that you use
2137
<code>const</code> whenever it makes sense to do so:
2140
<li> If a function does not modify an argument passed by
2141
reference or by pointer, that argument should be
2144
<li> Declare methods to be <code>const</code> whenever
2145
possible. Accessors should almost always be
2146
<code>const</code>. Other methods should be const if they do
2147
not modify any data members, do not call any
2148
non-<code>const</code> methods, and do not return a
2149
non-<code>const</code> pointer or non-<code>const</code>
2150
reference to a data member.
2152
<li> Consider making data members <code>const</code>
2153
whenever they do not need to be modified after
2158
However, do not go crazy with <code>const</code>. Something like
2159
<code>const int * const * const x;</code> is likely
2160
overkill, even if it accurately describes how const x is.
2161
Focus on what's really useful to know: in this case,
2162
<code>const int** x</code> is probably sufficient.
2165
The <code>mutable</code> keyword is allowed but is unsafe
2166
when used with threads, so thread safety should be carefully
2170
<SUBSECTION title="Where to put the const">
2172
Some people favor the form <code>int const *foo</code> to
2173
<code>const int* foo</code>. They argue that this is more
2174
readable because it's more consistent: it keeps the rule
2175
that <code>const</code> always follows the object it's
2176
describing. However, this consistency argument doesn't
2177
apply in this case, because the "don't go crazy" dictum
2178
eliminates most of the uses you'd have to be consistent with.
2180
Putting the <code>const</code> first is arguably more readable,
2181
since it follows English in putting the "adjective"
2182
(<code>const</code>) before the "noun" (<code>int</code>).
2185
That said, while we encourage putting <code>const</code> first,
2186
we do not require it. But be consistent with the code around
2193
<STYLEPOINT title="Integer Types">
2195
Of the built-in C++ integer types, the only one used
2197
is <code>int</code>. If a program needs a variable of a different
2200
a precise-width integer type from
2201
<code><stdint.h></code>, such as <code>int16_t</code>.
2205
C++ does not specify the sizes of its integer types. Typically
2206
people assume that <code>short</code> is 16 bits,
2207
<code>int</code> is 32 bits, <code>long</code> is 32 bits and
2208
<code>long long</code> is 64 bits.
2211
Uniformity of declaration.
2214
The sizes of integral types in C++ can vary based on compiler
2220
<code><stdint.h></code> defines
2221
types like <code>int16_t</code>, <code>uint32_t</code>,
2222
<code>int64_t</code>, etc.
2223
You should always use those in preference to
2224
<code>short</code>, <code>unsigned long long</code> and the
2225
like, when you need a guarantee on the size of an integer.
2226
Of the C integer types, only <code>int</code> should be
2227
used. When appropriate, you are welcome to use standard
2228
types like <code>size_t</code> and <code>ptrdiff_t</code>.
2231
We use <code>int</code> very often, for integers we know are not
2232
going to be too big, e.g., loop counters. Use plain old
2233
<code>int</code> for such things. You should assume that an
2237
but don't assume that it has more than 32 bits.
2238
If you need a 64-bit integer type, use
2239
<code>int64_t</code> or
2240
<code>uint64_t</code>.
2243
For integers we know can be "big",
2245
<code>int64_t</code>.
2249
You should not use the unsigned integer types such as
2250
<code>uint32_t</code>,
2251
unless the quantity you are representing is really a bit pattern
2252
rather than a number, or unless you need defined
2253
twos-complement overflow. In particular, do not use unsigned
2254
types to say a number will never be negative. Instead, use
2256
assertions for this.
2261
<SUBSECTION title="On Unsigned Integers">
2263
Some people, including some textbook authors, recommend
2264
using unsigned types to represent numbers that are never
2265
negative. This is intended as a form of self-documentation.
2266
However, in C, the advantages of such documentation are
2267
outweighed by the real bugs it can introduce. Consider:
2270
for (unsigned int i = foo.Length()-1; i >= 0; --i) ...
2273
This code will never terminate! Sometimes gcc will notice
2274
this bug and warn you, but often it will not. Equally bad
2275
bugs can occur when comparing signed and unsigned
2276
variables. Basically, C's type-promotion scheme causes
2277
unsigned types to behave differently than one might expect.
2280
So, document that a variable is non-negative using
2282
Don't use an unsigned type.
2288
<STYLEPOINT title="64-bit Portability">
2290
Code should be 64-bit and 32-bit friendly. Bear in mind problems of
2291
printing, comparisons, and structure alignment.
2297
<code>printf()</code> specifiers for some types are
2298
not cleanly portable between 32-bit and 64-bit
2299
systems. C99 defines some portable format
2300
specifiers. Unfortunately, MSVC 7.1 does not
2301
understand some of these specifiers and the
2302
standard is missing a few, so we have to define our
2303
own ugly versions in some cases (in the style of the
2304
standard include file <code>inttypes.h</code>):
2307
// printf macros for size_t, in the style of inttypes.h
2309
#define __PRIS_PREFIX "z"
2311
#define __PRIS_PREFIX
2314
// Use these macros after a % in a printf format string
2315
// to get correct 32/64 bit behavior, like this:
2316
// size_t size = records.size();
2317
// printf("%"PRIuS"\n", size);
2319
#define PRIdS __PRIS_PREFIX "d"
2320
#define PRIxS __PRIS_PREFIX "x"
2321
#define PRIuS __PRIS_PREFIX "u"
2322
#define PRIXS __PRIS_PREFIX "X"
2323
#define PRIoS __PRIS_PREFIX "o"
2325
<table border="1" summary="portable printf specifiers">
2334
<td><code>void *</code> (or any pointer)</td>
2335
<td><code>%lx</code></td>
2336
<td><code>%p</code></td>
2341
<td><code>int64_t</code></td>
2342
<td><code>%qd</code>,
2343
<code>%lld</code></td>
2344
<td><code>%"PRId64"</code></td>
2349
<td><code>uint64_t</code></td>
2350
<td><code>%qu</code>,
2352
<code>%llx</code></td>
2353
<td><code>%"PRIu64"</code>,
2354
<code>%"PRIx64"</code></td>
2359
<td><code>size_t</code></td>
2360
<td><code>%u</code></td>
2361
<td><code>%"PRIuS"</code>,
2362
<code>%"PRIxS"</code></td>
2363
<td>C99 specifies <code>%zu</code></td>
2366
<td><code>ptrdiff_t</code></td>
2367
<td><code>%d</code></td>
2368
<td><code>%"PRIdS"</code></td>
2369
<td>C99 specifies <code>%zd</code></td>
2375
Note that the <code>PRI*</code> macros expand to independent
2376
strings which are concatenated by the compiler. Hence
2377
if you are using a non-constant format string, you
2378
need to insert the value of the macro into the format,
2379
rather than the name. It is still possible, as usual,
2380
to include length specifiers, etc., after the
2381
<code>%</code> when using the <code>PRI*</code>
2382
macros. So, e.g. <code>printf("x = %30"PRIuS"\n",
2383
x)</code> would expand on 32-bit Linux to
2384
<code>printf("x = %30" "u" "\n", x)</code>, which the
2385
compiler will treat as <code>printf("x = %30u\n",
2391
<li> Remember that <code>sizeof(void *)</code> !=
2392
<code>sizeof(int)</code>. Use <code>intptr_t</code> if
2393
you want a pointer-sized integer.
2396
<li> You may need to be careful with structure alignments,
2397
particularly for structures being stored on disk. Any
2398
class/structure with a
2400
<code>int64_t</code>/<code>uint64_t</code>
2401
member will by default end up being 8-byte aligned on a 64-bit
2402
system. If you have such structures being shared on disk
2403
between 32-bit and 64-bit code, you will need to ensure
2404
that they are packed the same on both architectures.
2406
Most compilers offer a way to alter
2407
structure alignment. For gcc, you can use
2408
<code>__attribute__((packed))</code>. MSVC offers
2409
<code>#pragma pack()</code> and
2410
<code>__declspec(align())</code>.
2415
Use the <code>LL</code> or <code>ULL</code> suffixes as
2416
needed to create 64-bit constants. For example:
2419
int64_t my_value = 0x123456789LL;
2420
uint64_t my_mask = 3ULL << 48;
2424
<li> If you really need different code on 32-bit and 64-bit
2425
systems, use <code>#ifdef _LP64</code> to choose between
2426
the code variants. (But please avoid this if
2427
possible, and keep any such changes localized.)
2433
<STYLEPOINT title="Preprocessor Macros">
2435
Be very cautious with macros. Prefer inline functions, enums,
2436
and <code>const</code> variables to macros.
2440
Macros mean that the code you see is not the same as the code
2441
the compiler sees. This can introduce unexpected behavior,
2442
especially since macros have global scope.
2445
Luckily, macros are not nearly as necessary in C++ as they are
2446
in C. Instead of using a macro to inline performance-critical
2447
code, use an inline function. Instead of using a macro to
2448
store a constant, use a <code>const</code> variable. Instead of
2449
using a macro to "abbreviate" a long variable name, use a
2450
reference. Instead of using a macro to conditionally compile code
2451
... well, don't do that at all (except, of course, for the
2452
<code>#define</code> guards to prevent double inclusion of
2453
header files). It makes testing much more difficult.
2456
Macros can do things these other techniques cannot, and you do
2457
see them in the codebase, especially in the lower-level
2458
libraries. And some of their special features (like
2459
stringifying, concatenation, and so forth) are not available
2460
through the language proper. But before using a macro,
2461
consider carefully whether there's a non-macro way to achieve
2465
The following usage pattern will avoid many problems with
2466
macros; if you use macros, follow it whenever possible:
2469
<li> Don't define macros in a <code>.h</code> file.
2471
<li> <code>#define</code> macros right before you use them,
2472
and <code>#undef</code> them right after.
2474
<li> Do not just <code>#undef</code> an existing macro before
2475
replacing it with your own; instead, pick a name that's
2476
likely to be unique.
2478
<li> Try not to use macros that expand to unbalanced C++
2479
constructs, or at least document that behavior well.
2481
<li> Prefer not using <code>##</code> to generate function/class/variable
2488
<STYLEPOINT title="0 and NULL">
2490
Use <code>0</code> for integers, <code>0.0</code> for reals,
2491
<code>NULL</code> for pointers, and <code>'\0'</code> for chars.
2495
Use <code>0</code> for integers and <code>0.0</code> for reals.
2496
This is not controversial.
2499
For pointers (address values), there is a choice between <code>0</code>
2500
and <code>NULL</code>. Bjarne Stroustrup prefers an unadorned
2501
<code>0</code>. We prefer <code>NULL</code> because it looks like a
2502
pointer. In fact, some C++ compilers, such as gcc 4.1.0, provide special
2503
definitions of <code>NULL</code> which enable them to give useful
2504
warnings, particularly in situations where <code>sizeof(NULL)</code>
2505
is not equal to <code>sizeof(0)</code>.
2508
Use <code>'\0'</code> for chars.
2509
This is the correct type and also makes code more readable.
2514
<STYLEPOINT title="sizeof">
2516
Use <code>sizeof(<var>varname</var>)</code> instead of
2517
<code>sizeof(<var>type</var>)</code> whenever possible.
2521
Use <code>sizeof(<var>varname</var>)</code> because it will update
2522
appropriately if the type of the variable changes.
2523
<code>sizeof(<var>type</var>)</code> may make sense in some cases,
2524
but should generally be avoided because it can fall out of sync if
2525
the variable's type changes.
2530
memset(&data, 0, sizeof(data));
2533
memset(&data, 0, sizeof(Struct));
2539
<STYLEPOINT title="Boost">
2541
Use only approved libraries from the Boost library collection.
2545
The <a href="http://www.boost.org/">Boost library collection</a> is
2546
a popular collection of peer-reviewed, free, open-source C++ libraries.
2549
Boost code is generally very high-quality, is widely portable, and fills
2550
many important gaps in the C++ standard library, such as type traits,
2551
better binders, and better smart pointers. It also provides an
2552
implementation of the TR1 extension to the standard library.
2555
Some Boost libraries encourage coding practices which can hamper
2556
readability, such as metaprogramming and other advanced template
2557
techniques, and an excessively "functional" style of programming.
2564
In order to maintain a high level of readability for all contributors
2565
who might read and maintain code, we only allow an approved subset of
2566
Boost features. Currently, the following libraries are permitted:
2568
<li> <a href="http://www.boost.org/libs/utility/call_traits.htm">
2569
Call Traits</a> from <code>boost/call_traits.hpp</code>
2571
<li> <a href="http://www.boost.org/libs/utility/compressed_pair.htm">
2572
Compressed Pair</a> from <code>boost/compressed_pair.hpp</code>
2574
<li> <a href="http://www.boost.org/libs/ptr_container/">
2575
Pointer Container</a> from <code>boost/ptr_container</code> except
2576
serialization and wrappers for containers not in the C++03
2577
standard (<code>ptr_circular_buffer.hpp</code> and
2578
<code>ptr_unordered*</code>)
2580
<li> <a href="http://www.boost.org/libs/array/">
2581
Array</a> from <code>boost/array.hpp</code>
2583
<li> <a href="http://www.boost.org/libs/graph/">
2584
The Boost Graph Library (BGL)</a> from <code>boost/graph</code>,
2585
except serialization (<code>adj_list_serialize.hpp</code>) and
2586
parallel/distributed algorithms and data structures
2587
(<code>boost/graph/parallel/*</code> and
2588
<code>boost/graph/distributed/*</code>).
2590
<li> <a href="http://www.boost.org/libs/property_map/">
2591
Property Map</a> from <code>boost/property_map</code>, except
2592
parallel/distributed property maps
2593
(<code>boost/property_map/parallel/*</code>).
2596
<a href="http://www.boost.org/libs/iterator/">
2597
Iterator</a> that deals with defining iterators:
2598
<code>boost/iterator/iterator_adaptor.hpp</code>,
2599
<code>boost/iterator/iterator_facade.hpp</code>, and
2600
<code>boost/function_output_iterator.hpp</code></li>
2602
We are actively considering adding other Boost features to the list, so
2603
this rule may be relaxed in the future.
2609
<STYLEPOINT title="C++0x">
2611
Use only approved libraries and language extensions from C++0x.
2612
Currently, none are approved.
2616
C++0x is the next ISO C++ standard, currently in
2617
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf">final
2618
committee draft</a> form. It contains
2619
<a href="http://en.wikipedia.org/wiki/C%2B%2B0x">significant
2620
changes</a> both to the language and libraries.
2623
We expect that C++0x will become the next standard, and eventually will
2624
be supported by most C++ compilers. It standardizes some common C++
2625
extensions that we use already, allows shorthands for some operations,
2626
and has some safety improvements.
2630
The C++0x standard is substantialy more complex than its predecessor
2631
(1,300 pages versus 800 pages), and is
2632
unfamilar to many developers. The long-term effects of some
2633
features on code readability and maintenance are unknown. We cannot
2634
predict when its various features will be implemented uniformly by
2635
tools that may be of interest (gcc, icc, clang, Eclipse, etc.).
2638
As with <a href="#Boost">Boost</a>, some C++0x extensions encourage
2639
coding practices that hamper readability—for example by removing
2640
checked redundancy (such as type names) that may be helpful to readers,
2641
or by encouraging template metaprogramming. Other extensions
2642
duplicate functionality available through existing
2643
mechanisms, which may lead to
2644
confusion and conversion costs.
2648
Use only C++0x libraries and language features that have been approved
2649
for use. Currently, no such features are approved.
2650
Features will be approved individually as appropriate.
2657
<CATEGORY title="Naming">
2659
The most important consistency rules are those that govern
2660
naming. The style of a name immediately informs us what sort of
2661
thing the named entity is: a type, a variable, a function, a
2662
constant, a macro, etc., without requiring us to search for the
2663
declaration of that entity. The pattern-matching engine in our
2664
brains relies a great deal on these naming rules.
2668
Naming rules are pretty arbitrary, but
2670
we feel that consistency is more important than individual preferences
2671
in this area, so regardless of whether you find them sensible or not,
2672
the rules are the rules.
2675
<STYLEPOINT title="General Naming Rules">
2677
Function names, variable names, and filenames should be
2678
descriptive; eschew abbreviation. Types and variables should be
2679
nouns, while functions should be "command" verbs.
2682
<SUBSECTION title="How to Name">
2684
Give as descriptive a name as possible, within reason. Do
2685
not worry about saving horizontal space as it is far more
2686
important to make your code immediately understandable by a
2687
new reader. Examples of well-chosen names:
2690
int num_errors; // Good.
2691
int num_completed_connections; // Good.
2694
Poorly-chosen names use ambiguous abbreviations or arbitrary
2695
characters that do not convey meaning:
2698
int n; // Bad - meaningless.
2699
int nerr; // Bad - ambiguous abbreviation.
2700
int n_comp_conns; // Bad - ambiguous abbreviation.
2703
Type and variable names should typically be nouns: e.g.,
2704
<code>FileOpener</code>,
2706
<code>num_errors</code>.
2709
Function names should typically be imperative (that is they
2710
should be commands): e.g., <code>OpenFile()</code>,
2711
<code>set_num_errors()</code>. There is an exception for
2712
accessors, which, described more completely in <a HREF="#Function_Names">Function Names</a>, should be named
2713
the same as the variable they access.
2717
<SUBSECTION title="Abbreviations">
2719
Do not use abbreviations unless they are extremely well
2720
known outside your project. For example:
2724
// These show proper names with no abbreviations.
2725
int num_dns_connections; // Most people know what "DNS" stands for.
2726
int price_count_reader; // OK, price count. Makes sense.
2730
// Abbreviations can be confusing or ambiguous outside a small group.
2731
int wgc_connections; // Only your group knows what this stands for.
2732
int pc_reader; // Lots of things can be abbreviated "pc".
2735
Never abbreviate by leaving out letters:
2738
int error_count; // Good.
2741
int error_cnt; // Bad.
2747
<STYLEPOINT title="File Names">
2749
Filenames should be all lowercase and can include underscores
2750
(<code>_</code>) or dashes (<code>-</code>). Follow the
2751
convention that your
2754
uses. If there is no consistent local pattern to follow, prefer "_".
2758
Examples of acceptable file names:
2762
my_useful_class.cc<br/>
2763
my-useful-class.cc<br/>
2764
myusefulclass.cc<br/>
2765
myusefulclass_test.cc // _unittest and _regtest are deprecated.<br/>
2769
C++ files should end in <code>.cc</code> and header files
2770
should end in <code>.h</code>.
2773
Do not use filenames that already exist
2774
in <code>/usr/include</code>, such as <code>db.h</code>.
2777
In general, make your filenames very specific. For example,
2778
use <code>http_server_logs.h</code> rather
2779
than <code>logs.h</code>. A very common case is to have a
2780
pair of files called, e.g., <code>foo_bar.h</code>
2781
and <code>foo_bar.cc</code>, defining a class
2782
called <code>FooBar</code>.
2785
Inline functions must be in a <code>.h</code> file. If your
2786
inline functions are very short, they should go directly into your
2787
<code>.h</code> file. However, if your inline functions
2788
include a lot of code, they may go into a third file that
2789
ends in <code>-inl.h</code>. In a class with a lot of inline
2790
code, your class could have three files:
2793
url_table.h // The class declaration.
2794
url_table.cc // The class definition.
2795
url_table-inl.h // Inline functions that include lots of code.
2798
See also the section <a href="#The_-inl.h_Files">-inl.h Files</a>
2803
<STYLEPOINT title="Type Names">
2805
Type names start with a capital letter and have a capital
2806
letter for each new word, with no underscores:
2807
<code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.
2811
The names of all types — classes, structs, typedefs, and enums
2812
— have the same naming convention. Type names should start
2813
with a capital letter and have a capital letter for each new
2814
word. No underscores. For example:
2817
// classes and structs
2818
class UrlTable { ...
2819
class UrlTableTester { ...
2820
struct UrlTableProperties { ...
2823
typedef hash_map<UrlTableProperties *, string> PropertiesMap;
2826
enum UrlTableErrors { ...
2831
<STYLEPOINT title="Variable Names">
2833
Variable names are all lowercase, with underscores between
2834
words. Class member variables have trailing underscores. For
2835
instance: <code>my_exciting_local_variable</code>,
2836
<code>my_exciting_member_variable_</code>.
2839
<SUBSECTION title="Common Variable names">
2844
string table_name; // OK - uses underscore.
2845
string tablename; // OK - all lowercase.
2848
string tableName; // Bad - mixed case.
2852
<SUBSECTION title="Class Data Members">
2854
Data members (also called instance variables or member
2855
variables) are lowercase with optional underscores like
2856
regular variable names, but always end with a trailing
2860
string table_name_; // OK - underscore at end.
2861
string tablename_; // OK.
2865
<SUBSECTION title="Struct Variables">
2867
Data members in structs should be named like regular
2868
variables without the trailing underscores that data members
2872
struct UrlTableProperties {
2878
See <a HREF="#Structs_vs._Classes">Structs vs. Classes</a> for a
2879
discussion of when to use a struct versus a class.
2883
<SUBSECTION title="Global Variables">
2885
There are no special requirements for global variables,
2886
which should be rare in any case, but if you use one,
2887
consider prefixing it with <code>g_</code> or some other
2888
marker to easily distinguish it from local variables.
2894
<STYLEPOINT title="Constant Names">
2896
Use a <code>k</code> followed by mixed case:
2897
<code>kDaysInAWeek</code>.
2901
All compile-time constants, whether they are declared locally,
2902
globally, or as part of a class, follow a slightly different
2903
naming convention from other variables. Use a <code>k</code>
2904
followed by words with uppercase first letters:
2907
const int kDaysInAWeek = 7;
2912
<STYLEPOINT title="Function Names">
2914
Regular functions have mixed case; accessors and mutators match
2915
the name of the variable: <code>MyExcitingFunction()</code>,
2916
<code>MyExcitingMethod()</code>,
2917
<code>my_exciting_member_variable()</code>,
2918
<code>set_my_exciting_member_variable()</code>.
2921
<SUBSECTION title="Regular Functions">
2923
Functions should start with a capital letter and have a
2924
capital letter for each new word. No underscores.
2927
If your function crashes upon an error, you should append OrDie to
2928
the function name. This only applies to functions which could be
2929
used by production code and to errors that are reasonably
2930
likely to occur during normal operation.
2939
<SUBSECTION title="Accessors and Mutators">
2941
Accessors and mutators (get and set functions) should match
2942
the name of the variable they are getting and setting. This
2943
shows an excerpt of a class whose instance variable is
2944
<code>num_entries_</code>.
2950
int num_entries() const { return num_entries_; }
2951
void set_num_entries(int num_entries) { num_entries_ = num_entries; }
2958
You may also use lowercase letters for other very short
2959
inlined functions. For example if a function were so cheap
2960
you would not cache the value if you were calling it in a
2961
loop, then lowercase naming would be acceptable.
2967
<STYLEPOINT title="Namespace Names">
2970
Namespace names are all lower-case, and based on project names and
2971
possibly their directory structure:
2972
<code>google_awesome_project</code>.
2976
See <a HREF="#Namespaces">Namespaces</a> for a discussion of
2977
namespaces and how to name them.
2982
<STYLEPOINT title="Enumerator Names">
2984
Enumerators should be named <i>either</i> like
2985
<A HREF="#Constant_Names">constants</A> or like
2986
<A HREF="#Macro_Names">macros</A>: either <code>kEnumName</code>
2987
or <code>ENUM_NAME</code>.
2991
Preferably, the individual enumerators should be named like
2992
<A HREF="#Constant_Names">constants</A>. However, it is also
2993
acceptable to name them like <A HREF="#Macro_Names">macros</A>. The enumeration name,
2994
<code>UrlTableErrors</code> (and
2995
<code>AlternateUrlTableErrors</code>), is a type, and
2996
therefore mixed case.
2999
enum UrlTableErrors {
3002
kErrorMalformedInput,
3004
enum AlternateUrlTableErrors {
3007
MALFORMED_INPUT = 2,
3011
Until January 2009, the style was to name enum values like
3012
<A HREF="#Macro_Names">macros</A>. This caused problems with
3013
name collisions between enum values and macros. Hence, the
3014
change to prefer constant-style naming was put in place. New
3015
code should prefer constant-style naming if possible.
3016
However, there is no reason to change old code to use
3017
constant-style names, unless the old names are actually
3018
causing a compile-time problem.
3024
<STYLEPOINT title="Macro Names">
3026
You're not really going to <A HREF="#Preprocessor_Macros">define
3027
a macro</A>, are you? If you do, they're like this:
3028
<code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.
3032
Please see the <a href="#Preprocessor_Macros">description of
3033
macros</a>; in general macros should <em>not</em> be used.
3034
However, if they are absolutely needed, then they should be
3035
named with all capitals and underscores.
3038
#define ROUND(x) ...
3039
#define PI_ROUNDED 3.0
3044
<STYLEPOINT title="Exceptions to Naming Rules">
3046
If you are naming something that is analogous to an existing C
3047
or C++ entity then you can follow the existing naming convention
3053
<dt> <code>bigopen()</code> </dt>
3054
<dd> function name, follows form of <code>open()</code> </dd>
3055
<dt> <code>uint</code> </dt>
3056
<dd> <code>typedef</code> </dd>
3057
<dt> <code>bigpos</code> </dt>
3058
<dd> <code>struct</code> or <code>class</code>, follows form of
3059
<code>pos</code> </dd>
3060
<dt> <code>sparse_hash_map</code> </dt>
3061
<dd> STL-like entity; follows STL naming conventions </dd>
3062
<dt> <code>LONGLONG_MAX</code> </dt>
3063
<dd> a constant, as in <code>INT_MAX</code> </dd>
3070
<CATEGORY title="Comments">
3072
Though a pain to write, comments are absolutely vital to keeping our
3073
code readable. The following rules describe what you should
3074
comment and where. But remember: while comments are very
3075
important, the best code is self-documenting. Giving sensible
3076
names to types and variables is much better than using obscure
3077
names that you must then explain through comments.
3080
When writing your comments, write for your audience: the next
3083
who will need to understand your code. Be generous — the next
3089
<STYLEPOINT title="Comment Style">
3091
Use either the <code>//</code> or <code>/* */</code> syntax, as long
3092
as you are consistent.
3096
You can use either the <code>//</code> or the <code>/* */</code>
3097
syntax; however, <code>//</code> is <em>much</em> more common.
3098
Be consistent with how you comment and what style you use where.
3103
<STYLEPOINT title="File Comments">
3105
Start each file with a copyright notice, followed by a
3106
description of the contents of the file.
3109
<SUBSECTION title="Legal Notice and Author Line">
3113
Every file should contain the following items, in order:
3115
<li>a copyright statement (for example,
3116
<code>Copyright 2008 Google Inc.</code>)</li>
3117
<li>a license boilerplate. Choose the appropriate boilerplate
3118
for the license used by the project (for example,
3119
Apache 2.0, BSD, LGPL, GPL)</li>
3120
<li>an author line to identify the original author of the
3125
If you make significant changes to a file that someone else
3126
originally wrote, add yourself to the author line. This can
3127
be very helpful when another
3130
has questions about the file and needs to know whom to contact
3135
<SUBSECTION title="File Contents">
3137
Every file should have a comment at the top, below the copyright
3138
notice and author line, that describes the contents of the file.
3141
Generally a <code>.h</code> file will describe the classes
3142
that are declared in the file with an overview of what they
3143
are for and how they are used. A <code>.cc</code> file
3144
should contain more information about implementation details
3145
or discussions of tricky algorithms. If you feel the
3146
implementation details or a discussion of the algorithms
3147
would be useful for someone reading the <code>.h</code>,
3148
feel free to put it there instead, but mention in the
3149
<code>.cc</code> that the documentation is in the
3150
<code>.h</code> file.
3153
Do not duplicate comments in both the <code>.h</code> and
3154
the <code>.cc</code>. Duplicated comments diverge.
3160
<STYLEPOINT title="Class Comments">
3162
Every class definition should have an accompanying comment that
3163
describes what it is for and how it should be used.
3167
// Iterates over the contents of a GargantuanTable. Sample usage:
3168
// GargantuanTableIterator* iter = table->NewIterator();
3169
// for (iter->Seek("foo"); !iter->done(); iter->Next()) {
3170
// process(iter->key(), iter->value());
3173
class GargantuanTableIterator {
3178
If you have already described a class in detail in the
3179
comments at the top of your file feel free to simply state
3180
"See comment at top of file for a complete description", but
3181
be sure to have some sort of comment.
3184
Document the synchronization assumptions the class makes, if
3185
any. If an instance of the class can be accessed by multiple
3186
threads, take extra care to document the rules and invariants
3187
surrounding multithreaded use.
3192
<STYLEPOINT title="Function Comments">
3194
Declaration comments describe use of the function; comments at
3195
the definition of a function describe operation.
3198
<SUBSECTION title="Function Declarations">
3200
Every function declaration should have comments immediately
3201
preceding it that describe what the function does and how to
3202
use it. These comments should be descriptive ("Opens the
3203
file") rather than imperative ("Open the file"); the comment
3204
describes the function, it does not tell the function what
3205
to do. In general, these comments do not describe how the
3206
function performs its task. Instead, that should be left to
3207
comments in the function definition.
3210
Types of things to mention in comments at the function
3214
<li> What the inputs and outputs are.
3216
<li> For class member functions: whether the object
3217
remembers reference arguments beyond the
3218
duration of the method call, and whether it will
3221
<li> If the function allocates memory that the caller
3224
<li> Whether any of the arguments can be <code>NULL</code>.
3226
<li> If there are any performance implications of how a
3229
<li> If the function is re-entrant. What are its
3230
synchronization assumptions?
3237
// Returns an iterator for this table. It is the client's
3238
// responsibility to delete the iterator when it is done with it,
3239
// and it must not use the iterator once the GargantuanTable object
3240
// on which the iterator was created has been deleted.
3242
// The iterator is initially positioned at the beginning of the table.
3244
// This method is equivalent to:
3245
// Iterator* iter = table->NewIterator();
3246
// iter->Seek("");
3248
// If you are going to immediately seek to another place in the
3249
// returned iterator, it will be faster to use NewIterator()
3250
// and avoid the extra seek.
3251
Iterator* GetIterator() const;
3254
However, do not be unnecessarily verbose or state the
3255
completely obvious. Notice below that it is not necessary
3256
to say "returns false otherwise" because this is implied.
3259
// Returns true if the table cannot hold any more entries.
3263
When commenting constructors and destructors, remember that
3264
the person reading your code knows what constructors and
3265
destructors are for, so comments that just say something like
3266
"destroys this object" are not useful. Document what
3267
constructors do with their arguments (for example, if they
3268
take ownership of pointers), and what cleanup the destructor
3269
does. If this is trivial, just skip the comment. It is
3270
quite common for destructors not to have a header comment.
3274
<SUBSECTION title="Function Definitions">
3276
Each function definition should have a comment describing
3277
what the function does if there's anything tricky about how it does
3278
its job. For example, in the definition comment you might
3279
describe any coding tricks you use, give an overview of the
3280
steps you go through, or explain why you chose to implement
3281
the function in the way you did rather than using a viable
3282
alternative. For instance, you might mention why it must
3283
acquire a lock for the first half of the function but why it
3284
is not needed for the second half.
3287
Note you should <em>not</em> just repeat the comments given
3288
with the function declaration, in the <code>.h</code> file or
3289
wherever. It's okay to recapitulate briefly what the function
3290
does, but the focus of the comments should be on how it does it.
3296
<STYLEPOINT title="Variable Comments">
3298
In general the actual name of the variable should be descriptive
3299
enough to give a good idea of what the variable is used for. In
3300
certain cases, more comments are required.
3303
<SUBSECTION title="Class Data Members">
3305
Each class data member (also called an instance variable or
3306
member variable) should have a comment describing what it is
3307
used for. If the variable can take sentinel values with
3308
special meanings, such as <code>NULL</code> or -1, document this.
3313
// Keeps track of the total number of entries in the table.
3314
// Used to ensure we do not go over the limit. -1 means
3315
// that we don't yet know how many entries the table has.
3316
int num_total_entries_;
3320
<SUBSECTION title="Global Variables">
3322
As with data members, all global variables should have a
3323
comment describing what they are and what they are used for.
3327
// The total number of tests cases that we run through in this regression test.
3328
const int kNumTestCases = 6;
3334
<STYLEPOINT title="Implementation Comments">
3336
In your implementation you should have comments in tricky,
3337
non-obvious, interesting, or important parts of your code.
3340
<SUBSECTION title="Class Data Members">
3342
Tricky or complicated code blocks should have comments
3343
before them. Example:
3346
// Divide result by two, taking into account that x
3347
// contains the carry from the add.
3348
for (int i = 0; i < result->size(); i++) {
3349
x = (x << 8) + (*result)[i];
3350
(*result)[i] = x >> 1;
3355
<SUBSECTION title="Line Comments">
3357
Also, lines that are non-obvious should get a comment at the
3358
end of the line. These end-of-line comments should be
3359
separated from the code by 2 spaces. Example:
3362
// If we have enough memory, mmap the data portion too.
3363
mmap_budget = max<int64>(0, mmap_budget - index_->length());
3364
if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock))
3365
return; // Error already logged.
3368
Note that there are both comments that describe what the
3369
code is doing, and comments that mention that an error has
3370
already been logged when the function returns.
3373
If you have several comments on subsequent lines, it can
3374
often be more readable to line them up:
3377
DoSomething(); // Comment here so the comments line up.
3378
DoSomethingElseThatIsLonger(); // Comment here so there are two spaces between
3379
// the code and the comment.
3380
{ // One space before comment when opening a new scope is allowed,
3381
// thus the comment lines up with the following comments and code.
3382
DoSomethingElse(); // Two spaces before line comments normally.
3386
<SUBSECTION title="NULL, true/false, 1, 2, 3...">
3388
When you pass in <code>NULL</code>, boolean, or literal integer
3389
values to functions, you should consider adding a comment about
3390
what they are, or make your code self-documenting by using
3391
constants. For example, compare:
3394
bool success = CalculateSomething(interesting_value,
3397
NULL); // What are these arguments??
3403
bool success = CalculateSomething(interesting_value,
3404
10, // Default base value.
3405
false, // Not the first time we're calling this.
3406
NULL); // No callback.
3409
Or alternatively, constants or self-describing variables:
3412
const int kDefaultBaseValue = 10;
3413
const bool kFirstTimeCalling = false;
3414
Callback *null_callback = NULL;
3415
bool success = CalculateSomething(interesting_value,
3422
<SUBSECTION title="Don'ts">
3424
Note that you should <em>never</em> describe the code
3425
itself. Assume that the person reading the code knows C++
3426
better than you do, even though he or she does not know what
3427
you are trying to do:
3430
// Now go through the b array and make sure that if i occurs,
3431
// the next element is i+1.
3432
... // Geez. What a useless comment.
3438
<STYLEPOINT title="Punctuation, Spelling and Grammar">
3440
Pay attention to punctuation, spelling, and grammar; it is
3441
easier to read well-written comments than badly written ones.
3445
Comments should usually be written as complete
3446
sentences with proper capitalization and periods at the end.
3447
Shorter comments, such as comments at the end of a line of
3448
code, can sometimes be less formal, but you should be
3449
consistent with your style. Complete sentences are more
3450
readable, and they provide some assurance that the comment is
3451
complete and not an unfinished thought.
3454
Although it can be frustrating to have a code reviewer point
3455
out that you are using a comma when you should be using a
3456
semicolon, it is very important that source code maintain a
3457
high level of clarity and readability. Proper punctuation,
3458
spelling, and grammar help with that goal.
3463
<STYLEPOINT title="TODO Comments">
3465
Use <code>TODO</code> comments for code that is temporary, a
3466
short-term solution, or good-enough but not perfect.
3470
<code>TODO</code>s should include the string <code>TODO</code> in
3471
all caps, followed by the
3473
name, e-mail address, or other
3475
of the person who can best provide context about the problem
3476
referenced by the <code>TODO</code>. A colon is optional. The main
3477
purpose is to have a consistent <code>TODO</code> format that can be
3478
searched to find the person who can provide more details upon request.
3479
A <code>TODO</code> is not a commitment that the person referenced
3480
will fix the problem. Thus when you create a <code>TODO</code>, it is
3488
// TODO(kl@gmail.com): Use a "*" here for concatenation operator.
3489
// TODO(Zeke) change this to use relations.
3492
If your <code>TODO</code> is of the form "At a future date do
3493
something" make sure that you either include a very specific
3494
date ("Fix by November 2005") or a very specific event
3495
("Remove this code when all clients can handle XML responses.").
3500
<STYLEPOINT title="Deprecation Comments">
3502
Mark deprecated interface points with <code>DEPRECATED</code> comments.
3506
You can mark an interface as deprecated by writing a comment containing
3507
the word <code>DEPRECATED</code> in all caps. The comment goes either
3508
before the declaration of the interface or on the same line as the
3513
After the word <code>DEPRECATED</code>, write your name, e-mail address,
3514
or other identifier in parentheses.
3517
A deprecation comment must include simple, clear directions for people to
3518
fix their callsites. In C++, you can implement a deprecated function as
3519
an inline function that calls the new interface point.
3522
Marking an interface point <code>DEPRECATED</code> will not magically
3523
cause any callsites to change. If you want people to actually stop using
3524
the deprecated facility, you will have to fix the callsites yourself or
3525
recruit a crew to help you.
3528
New code should not contain calls to deprecated interface points. Use
3529
the new interface point instead. If you cannot understand the
3530
directions, find the person who created the deprecation and ask them for
3531
help using the new interface point.
3539
<CATEGORY title="Formatting">
3541
Coding style and formatting are pretty arbitrary, but a
3544
is much easier to follow if everyone uses the same style. Individuals
3545
may not agree with every aspect of the formatting rules, and some of
3546
the rules may take some getting used to, but it is important that all
3548
project contributors
3549
follow the style rules so that
3552
can all read and understand everyone's code easily.
3556
To help you format code correctly, we've created a <A HREF="http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el">settings
3560
<STYLEPOINT title="Line Length">
3562
Each line of text in your code should be at most 80 characters
3568
We recognize that this rule is controversial, but so much existing
3569
code already adheres to it, and we feel that consistency is
3576
that it is rude to force them to resize their windows and there
3577
is no need for anything longer. Some folks are used to having
3578
several code windows side-by-side, and thus don't have room to
3579
widen their windows in any case. People set up their work
3580
environment assuming a particular maximum window width, and 80
3581
columns has been the traditional standard. Why change it?
3584
Proponents of change argue that a wider line can make code
3585
more readable. The 80-column limit is an hidebound
3586
throwback to 1960s mainframes;
3588
modern equipment has
3589
wide screens that can easily show longer lines.
3594
80 characters is the maximum.
3597
Exception: if a comment line contains an example command or
3598
a literal URL longer than 80 characters, that line may be
3599
longer than 80 characters for ease of cut and paste.
3602
Exception: an <code>#include</code> statement with a long
3603
path may exceed 80 columns. Try to avoid situations where this
3607
Exception: you needn't be concerned about
3608
<a href="#The__define_Guard">header guards</a>
3609
that exceed the maximum length.
3616
<STYLEPOINT title="Non-ASCII Characters">
3618
Non-ASCII characters should be rare, and must use UTF-8 formatting.
3622
You shouldn't hard-code user-facing text in source, even English,
3623
so use of non-ASCII characters should be rare. However, in certain
3624
cases it is appropriate to include such words in your code. For
3625
example, if your code parses data files from foreign sources,
3626
it may be appropriate to hard-code the non-ASCII string(s) used in
3627
those data files as delimiters. More commonly, unittest code
3630
need to be localized) might contain non-ASCII strings. In such
3631
cases, you should use UTF-8, since that is
3633
an encoding understood by most tools able
3634
to handle more than just ASCII.
3635
Hex encoding is also OK, and encouraged where it enhances
3636
readability — for example, <code>"\xEF\xBB\xBF"</code> is the
3637
Unicode zero-width no-break space character, which would be
3638
invisible if included in the source as straight UTF-8.
3643
<STYLEPOINT title="Spaces vs. Tabs">
3645
Use only spaces, and indent 2 spaces at a time.
3649
We use spaces for indentation. Do not use tabs in your code.
3650
You should set your editor to emit spaces when you hit the tab
3656
<STYLEPOINT title="Function Declarations and Definitions">
3658
Return type on the same line as function name, parameters on the
3659
same line if they fit.
3663
Functions look like this:
3666
ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
3672
If you have too much text to fit on one line:
3675
ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,
3682
or if you cannot fit even the first parameter:
3685
ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
3686
Type par_name1, // 4 space indent
3689
DoSomething(); // 2 space indent
3694
Some points to note:
3697
<li> The return type is always on the same line as the
3700
<li> The open parenthesis is always on the same line as the
3703
<li> There is never a space between the function name and the
3706
<li> There is never a space between the parentheses and the
3709
<li> The open curly brace is always at the end of the same
3710
line as the last parameter.
3712
<li> The close curly brace is either on the last line by itself
3713
or (if other style rules permit) on the same line as the
3716
<li> There should be a space between the close parenthesis and
3717
the open curly brace.
3719
<li> All parameters should be named, with identical names in the
3720
declaration and implementation.
3722
<li> All parameters should be aligned if possible.
3724
<li> Default indentation is 2 spaces.
3726
<li> Wrapped parameters have a 4 space indent.
3730
If your function is <code>const</code>, the <code>const</code>
3731
keyword should be on the same line as the last parameter:
3734
// Everything in this function signature fits on a single line
3735
ReturnType FunctionName(Type par) const {
3739
// This function signature requires multiple lines, but
3740
// the const keyword is on the line with the last parameter.
3741
ReturnType ReallyLongFunctionName(Type par1,
3747
If some parameters are unused, comment out the variable name in the
3748
function definition:
3751
// Always have named parameters in interfaces.
3754
virtual void Rotate(double radians) = 0;
3757
// Always have named parameters in the declaration.
3758
class Circle : public Shape {
3760
virtual void Rotate(double radians);
3763
// Comment out unused named parameters in definitions.
3764
void Circle::Rotate(double /*radians*/) {}
3767
// Bad - if someone wants to implement later, it's not clear what the
3769
void Circle::Rotate(double) {}
3774
<STYLEPOINT title="Function Calls">
3776
On one line if it fits; otherwise, wrap arguments at the
3781
Function calls have the following format:
3784
bool retval = DoSomething(argument1, argument2, argument3);
3787
If the arguments do not all fit on one line, they should be
3788
broken up onto multiple lines, with each subsequent line
3789
aligned with the first argument. Do not add spaces after the
3790
open paren or before the close paren:
3793
bool retval = DoSomething(averyveryveryverylongargument1,
3794
argument2, argument3);
3797
If the function has many arguments, consider having one per
3798
line if this makes the code more readable:
3801
bool retval = DoSomething(argument1,
3807
If the function signature is so long that it cannot fit within
3808
the maximum <a href="#Line_Length">line length</a>, you may
3809
place all arguments on subsequent lines:
3816
DoSomethingThatRequiresALongFunctionName(
3817
very_long_argument1, // 4 space indent
3826
<STYLEPOINT title="Conditionals">
3828
Prefer no spaces inside parentheses. The <code>else</code>
3829
keyword belongs on a new line.
3833
There are two acceptable formats for a basic conditional
3834
statement. One includes spaces between the parentheses and the
3835
condition, and one does not.
3838
The most common form is without spaces. Either is fine, but
3839
<em>be consistent</em>. If you are modifying a file, use the
3840
format that is already present. If you are writing new code,
3841
use the format that the other files in that directory or
3842
project use. If in doubt and you have no personal preference,
3843
do not add the spaces.
3846
if (condition) { // no spaces inside parentheses
3847
... // 2 space indent.
3848
} else { // The else goes on the same line as the closing brace.
3853
If you prefer you may add spaces inside the
3857
if ( condition ) { // spaces inside parentheses - rare
3858
... // 2 space indent.
3859
} else { // The else goes on the same line as the closing brace.
3864
Note that in all cases you must have a space between the
3865
<code>if</code> and the open parenthesis. You must also have
3866
a space between the close parenthesis and the curly brace, if
3870
if(condition) // Bad - space missing after IF.
3871
if (condition){ // Bad - space missing before {.
3872
if(condition){ // Doubly bad.
3875
if (condition) { // Good - proper space after IF and before {.
3878
Short conditional statements may be written on one line if
3879
this enhances readability. You may use this only when the
3880
line is brief and the statement does not use the
3881
<code>else</code> clause.
3884
if (x == kFoo) return new Foo();
3885
if (x == kBar) return new Bar();
3888
This is not allowed when the if statement has an
3892
// Not allowed - IF statement on one line when there is an ELSE clause
3897
In general, curly braces are not required for single-line
3898
statements, but they are allowed if you like them;
3899
conditional or loop statements with complex conditions or
3900
statements may be more readable with curly braces. Some
3903
require that an <CODE>if</CODE> must always always have an
3908
DoSomething(); // 2 space indent.
3911
DoSomething(); // 2 space indent.
3915
However, if one part of an <code>if</code>-<code>else</code>
3916
statement uses curly braces, the other part must too:
3919
// Not allowed - curly on IF but not ELSE
3925
// Not allowed - curly on ELSE but not IF
3933
// Curly braces around both IF and ELSE required because
3934
// one of the clauses used braces.
3944
<STYLEPOINT title="Loops and Switch Statements">
3946
Switch statements may use braces for blocks. Empty loop bodies should use
3947
<code>{}</code> or <code>continue</code>.
3951
<code>case</code> blocks in <code>switch</code> statements can have
3952
curly braces or not, depending on your preference. If you do
3953
include curly braces they should be placed as shown below.
3956
If not conditional on an enumerated value, switch statements
3957
should always have a <code>default</code> case (in the case of
3958
an enumerated value, the compiler will warn you if any values
3959
are not handled). If the default case should never execute,
3961
<code>assert</code>:
3966
case 0: { // 2 space indent
3967
... // 4 space indent
3980
Empty loop bodies should use <code>{}</code> or
3981
<code>continue</code>, but not a single semicolon.
3985
// Repeat test until it returns false.
3987
for (int i = 0; i < kSomeNumber; ++i) {} // Good - empty body.
3988
while (condition) continue; // Good - continue indicates no logic.
3991
while (condition); // Bad - looks like part of do/while loop.
3996
<STYLEPOINT title="Pointer and Reference Expressions">
3998
No spaces around period or arrow. Pointer operators do not have
4003
The following are examples of correctly-formatted pointer and
4004
reference expressions:
4016
<li> There are no spaces around the period or arrow when
4019
<li> Pointer operators have no space after the <code>*</code> or
4024
When declaring a pointer variable or argument, you may place
4025
the asterisk adjacent to either the type or to the variable
4029
// These are fine, space preceding.
4031
const string &str;
4033
// These are fine, space following.
4034
char* c; // but remember to do "char* c, *d, *e, ...;"!
4035
const string& str;
4038
char * c; // Bad - spaces on both sides of *
4039
const string & str; // Bad - spaces on both sides of &
4042
You should do this consistently within a single
4044
so, when modifying an existing file, use the style in that
4050
<STYLEPOINT title="Boolean Expressions">
4052
When you have a boolean expression that is longer than the <a href="#Line_Length">standard line length</a>, be consistent in
4053
how you break up the lines.
4057
In this example, the logical AND operator is always at the end
4061
if (this_one_thing > this_other_thing &&
4062
a_third_thing == a_fourth_thing &&
4063
yet_another && last_one) {
4068
Note that when the code wraps in this example, both of
4069
the <code>&&</code> logical AND operators are at the
4070
end of the line. This is more common in Google code, though
4071
wrapping all operators at the beginning of the line is also
4072
allowed. Feel free to insert extra parentheses judiciously,
4073
because they can be very helpful in increasing readability
4074
when used appropriately. Also note that you should always use the
4075
punctuation operators, such as <code>&&</code> and
4076
<code>~</code>, rather than the word operators, such as <code>and</code>
4077
and <code>compl</code>.
4082
<STYLEPOINT title="Return Values">
4084
Do not needlessly surround the <code>return</code> expression with
4089
Use parentheses in <code>return expr;</code> only where you would use
4090
them in <code>x = expr;</code>.
4093
return result; // No parentheses in the simple case.
4094
return (some_long_condition && // Parentheses ok to make a complex
4095
another_condition); // expression more readable.
4098
return (value); // You wouldn't write var = (value);
4099
return(result); // return is not a function!
4106
<STYLEPOINT title="Variable and Array Initialization">
4108
Your choice of <code>=</code> or <code>()</code>.
4112
You may choose between <code>=</code> and <code>()</code>; the
4113
following are all correct:
4118
string name("Some Name");
4119
string name = "Some Name";
4124
<STYLEPOINT title="Preprocessor Directives">
4126
The hash mark that starts a preprocessor directive should
4127
always be at the beginning of the line.
4131
Even when preprocessor directives are within the body of
4132
indented code, the directives should start at the beginning of
4136
// Good - directives at beginning of line
4137
if (lopsided_score) {
4138
#if DISASTER_PENDING // Correct -- Starts at beginning of line
4140
# if NOTIFY // OK but not required -- Spaces after #
4148
// Bad - indented directives
4149
if (lopsided_score) {
4150
#if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line
4152
#endif // Wrong! Do not indent "#endif"
4159
<STYLEPOINT title="Class Format">
4161
Sections in <code>public</code>, <code>protected</code> and
4162
<code>private</code> order, each indented one space.
4166
The basic format for a class declaration (lacking the
4167
comments, see <a HREF="#Class_Comments">Class Comments</a> for
4168
a discussion of what comments are needed) is:
4171
class MyClass : public OtherClass {
4172
public: // Note the 1 space indent!
4173
MyClass(); // Regular 2 space indent.
4174
explicit MyClass(int var);
4177
void SomeFunction();
4178
void SomeFunctionThatDoesNothing() {
4181
void set_some_var(int var) { some_var_ = var; }
4182
int some_var() const { return some_var_; }
4185
bool SomeInternalFunction();
4188
int some_other_var_;
4189
DISALLOW_COPY_AND_ASSIGN(MyClass);
4196
<li> Any base class name should be on the same line as the
4197
subclass name, subject to the 80-column limit.
4199
<li> The <code>public:</code>, <code>protected:</code>, and
4200
<code>private:</code> keywords should be indented one
4203
<li> Except for the first instance, these keywords should be preceded
4204
by a blank line. This rule is optional in small classes.
4206
<li> Do not leave a blank line after these keywords.
4208
<li> The <code>public</code> section should be first, followed by
4209
the <code>protected</code> and finally the
4210
<code>private</code> section.
4212
<li> See <a HREF="#Declaration_Order">Declaration Order</a> for
4213
rules on ordering declarations within each of these sections.
4219
<STYLEPOINT title="Constructor Initializer Lists">
4221
Constructor initializer lists can be all on one line or with
4222
subsequent lines indented four spaces.
4226
There are two acceptable formats for initializer lists:
4229
// When it all fits on one line:
4230
MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {}
4236
// When it requires multiple lines, indent 4 spaces, putting the colon on
4237
// the first initializer line:
4238
MyClass::MyClass(int var)
4239
: some_var_(var), // 4 space indent
4240
some_other_var_(var + 1) { // lined up
4249
<STYLEPOINT title="Namespace Formatting">
4251
The contents of namespaces are not indented.
4255
<a href="#Namespaces">Namespaces</a> do not add an extra level of
4256
indentation. For example, use:
4261
void foo() { // Correct. No extra indentation within namespace.
4268
Do not indent within a namespace:
4273
// Wrong. Indented when it should not be.
4281
When declaring nested namespaces, put each namespace on its own line.
4290
<STYLEPOINT title="Horizontal Whitespace">
4292
Use of horizontal whitespace depends on location. Never put trailing
4293
whitespace at the end of a line.
4296
<SUBSECTION title="General">
4298
void f(bool b) { // Open braces should always have a space before them.
4300
int i = 0; // Semicolons usually have no space before them.
4301
int x[] = { 0 }; // Spaces inside braces for array initialization are
4302
int x[] = {0}; // optional. If you use them, put them on both sides!
4303
// Spaces around the colon in inheritance and initializer lists.
4304
class Foo : public Bar {
4306
// For inline function implementations, put spaces between the braces
4307
// and the implementation itself.
4308
Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces.
4309
void Reset() { baz_ = 0; } // Spaces separating braces from implementation.
4313
Adding trailing whitespace can cause extra work for others editing
4314
the same file, when they merge, as can removing existing trailing
4315
whitespace. So: Don't introduce trailing whitespace. Remove it
4316
if you're already changing that line, or do it in a separate
4319
operation (preferably when no-one else
4320
is working on the file).
4323
<SUBSECTION title="Loops and Conditionals">
4325
if (b) { // Space after the keyword in conditions and loops.
4326
} else { // Spaces around else.
4328
while (test) {} // There is usually no space inside parentheses.
4330
for (int i = 0; i < 5; ++i) {
4331
switch ( i ) { // Loops and conditions may have spaces inside
4332
if ( test ) { // parentheses, but this is rare. Be consistent.
4333
for ( int i = 0; i < 5; ++i ) {
4334
for ( ; i < 5 ; ++i) { // For loops always have a space after the
4335
... // semicolon, and may have a space before the
4338
case 1: // No space before colon in a switch case.
4340
case 2: break; // Use a space after a colon if there's code after it.
4343
<SUBSECTION title="Operators">
4345
x = 0; // Assignment operators always have spaces around
4347
x = -5; // No spaces separating unary operators and their
4349
if (x && !y)
4351
v = w * x + y / z; // Binary operators usually have spaces around them,
4352
v = w*x + y/z; // but it's okay to remove spaces around factors.
4353
v = w * (x + z); // Parentheses should have no spaces inside them.
4356
<SUBSECTION title="Templates and Casts">
4358
vector<string> x; // No spaces inside the angle
4359
y = static_cast<char*>(x); // brackets (< and >), before
4360
// <, or between >( in a cast.
4361
vector<char *> x; // Spaces between type and pointer are
4362
// okay, but be consistent.
4363
set<list<string> > x; // C++ requires a space in > >.
4364
set< list<string> > x; // You may optionally use
4365
// symmetric spacing in < <.
4372
<STYLEPOINT title="Vertical Whitespace">
4374
Minimize use of vertical whitespace.
4378
This is more a principle than a rule: don't use blank lines
4379
when you don't have to. In particular, don't put more than
4380
one or two blank lines between functions, resist starting
4381
functions with a blank line, don't end functions with a blank
4382
line, and be discriminating with your use of blank lines
4386
The basic principle is: The more code that fits on one screen,
4387
the easier it is to follow and understand the control flow of
4388
the program. Of course, readability can suffer from code
4389
being too dense as well as too spread out, so use your
4390
judgement. But in general, minimize use of vertical
4394
Some rules of thumb to help when blank lines may be useful:
4397
<li> Blank lines at the beginning or end of a function very
4398
rarely help readability.
4400
<li> Blank lines inside a chain of if-else blocks may well
4408
<CATEGORY title="Exceptions to the Rules">
4410
The coding conventions described above are mandatory. However,
4411
like all good rules, these sometimes have exceptions, which we
4417
<STYLEPOINT title="Existing Non-conformant Code">
4419
You may diverge from the rules when dealing with code that does not
4420
conform to this style guide.
4424
If you find yourself modifying code that was written to
4425
specifications other than those presented by this guide, you may
4426
have to diverge from these rules in order to stay consistent with
4427
the local conventions in that code. If you are in doubt about
4428
how to do this, ask the original author or the person currently
4429
responsible for the code. Remember that <em>consistency</em>
4430
includes local consistency, too.
4437
<STYLEPOINT title="Windows Code">
4440
Windows programmers have developed their own set of coding
4441
conventions, mainly derived from the conventions in Windows headers
4442
and other Microsoft code. We want to make it easy for anyone to
4443
understand your code, so we have a single set of guidelines for
4444
everyone writing C++ on any platform.
4448
It is worth reiterating a few of the guidelines that you might
4449
forget if you are used to the prevalent Windows style:
4452
<li> Do not use Hungarian notation (for example, naming an
4453
integer <code>iNum</code>). Use the Google naming conventions,
4454
including the <code>.cc</code> extension for source files.
4456
<li> Windows defines many of its own synonyms for primitive
4457
types, such as <code>DWORD</code>, <code>HANDLE</code>, etc.
4458
It is perfectly acceptable, and encouraged, that you use these
4459
types when calling Windows API functions. Even so, keep as
4460
close as you can to the underlying C++ types. For example, use
4461
<code>const TCHAR *</code> instead of <code>LPCTSTR</code>.
4463
<li> When compiling with Microsoft Visual C++, set the
4464
compiler to warning level 3 or higher, and treat all
4467
<li> Do not use <code>#pragma once</code>; instead use the
4468
standard Google include guards. The path in the include
4469
guards should be relative to the top of your project
4472
<li> In fact, do not use any nonstandard extensions, like
4473
<code>#pragma</code> and <code>__declspec</code>, unless you
4474
absolutely must. Using <code>__declspec(dllimport)</code> and
4475
<code>__declspec(dllexport)</code> is allowed; however, you
4476
must use them through macros such as <code>DLLIMPORT</code>
4477
and <code>DLLEXPORT</code>, so that someone can easily disable
4478
the extensions if they share the code.
4482
However, there are just a few rules that we occasionally need
4483
to break on Windows:
4486
<li> Normally we <a HREF="#Multiple_Inheritance">forbid
4487
the use of multiple implementation inheritance</a>; however,
4488
it is required when using COM and some ATL/WTL
4489
classes. You may use multiple implementation inheritance
4490
to implement COM or ATL/WTL classes and interfaces.
4492
<li> Although you should not use exceptions in your own code,
4493
they are used extensively in the ATL and some STLs,
4494
including the one that comes with Visual C++. When using
4495
the ATL, you should define <code>_ATL_NO_EXCEPTIONS</code> to
4496
disable exceptions. You should investigate whether you can
4497
also disable exceptions in your STL, but if not, it is OK to
4498
turn on exceptions in the compiler. (Note that this is
4499
only to get the STL to compile. You should still not
4500
write exception handling code yourself.)
4502
<li> The usual way of working with precompiled headers is to
4503
include a header file at the top of each source file,
4504
typically with a name like <code>StdAfx.h</code> or
4505
<code>precompile.h</code>. To make your code easier to share
4506
with other projects, avoid including this file explicitly
4507
(except in <code>precompile.cc</code>), and use the
4508
<code>/FI</code> compiler option to include the file
4511
<li> Resource headers, which are usually named
4512
<code>resource.h</code> and contain only macros, do not need
4513
to conform to these style guidelines.
4524
Use common sense and <em>BE CONSISTENT</em>.
4527
If you are editing code, take a few minutes to look at the
4528
code around you and determine its style. If they use spaces
4529
around their <code>if</code> clauses, you should, too. If
4530
their comments have little boxes of stars around them, make
4531
your comments have little boxes of stars around them too.
4534
The point of having style guidelines is to have a common
4535
vocabulary of coding so people can concentrate on what you are
4536
saying, rather than on how you are saying it. We present
4537
global style rules here so people know the vocabulary. But
4538
local style is also important. If code you add to a file
4539
looks drastically different from the existing code around it,
4540
the discontinuity throws readers out of their rhythm when they
4541
go to read it. Try to avoid this.
4545
OK, enough writing about writing code; the code itself is much
4546
more interesting. Have fun!
4559
Benjy Weinberger<br/>
4560
Craig Silverstein<br/>
4561
Gregory Eitzmann<br/>