~ubuntu-branches/ubuntu/oneiric/unity/oneiric

« back to all changes in this revision

Viewing changes to guides/cppguide.xml

  • Committer: Bazaar Package Importer
  • Author(s): Didier Roche
  • Date: 2011-08-01 19:53:15 UTC
  • mfrom: (1.1.49 upstream)
  • Revision ID: james.westby@ubuntu.com-20110801195315-mrewa9g7ctnk41oh
Tags: 4.6.0-0ubuntu1
* New upstream release.
  - compiz crashed with SIGSEGV in __strlen_sse2() (LP: #814619)
  - PlacesHomeView::PlacesHomeView leaks memory (LP: #818450)
  - PluginAdapter::MaximizeIfBigEnough leaks memory (LP: #818477)
  - Launcher - Make Launcher left of screen reveal more responsive and less
    prone to false positives (LP: #765819)
  - Launcher - clicking on a App launcher icon incorrectly un-minimizes
    windows (LP: #783434)
  - Unity doesn't get any mouse wheel scroll event in Indicators InputArea
    (LP: #814574)
  - Unity launcher gets cluttered when having multiple partitions and/or
    external volumes attached (LP: #713423)
  - Unity panel menus and indicators slow to respond. Too much lag.
    (LP: #742664)
  - In Unity the distinction between GVolume, GDrive and GMount is a bit
    confusing. (LP: #799890)
  - Launcher - When a item is deleted by dragging to Trash, the trash should
    pulse once before the Launcher disappears (LP: #750311)
  - ccsm needs an option to change launcher opacity (LP: #815032)
  - add a ccsm option to hide volumes in launcher (LP: #794707)
  - scale plugin doesn't work as desired when "Click Desktop To Show
    Desktop" is true (LP: #810315)
  - mute/unmute sound when user clicks on sound applet using scroll button
    or middle mouse button (LP: #609860)
  - Secondary activate (i.e. middle click) support for indicators advanced
    usage (LP: #812933)
* debian/control:
  - dep on latest libunity-misc
  - dep on latest nux
  - add build-dep on libgnome-desktop-3-dev
* debian/rules:
  - bump libunity-core-4.0-4 shlib for ABI break
  - don't ship unity dialogs right now. Not ready for alpha quality
* distro-patch the grey to darker grey (until the blur is done in nux)
* Switch to dpkg-source 3.0 (quilt) format
* debian/patches/01_revert_removed_function_for_unity2d_to_build.patch:
  - revert a removed API making unity-2d not building

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?xml version="1.0"?>
 
2
<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
 
3
<GUIDE title="Unity C++ Style Guide">
 
4
 
 
5
<!--
 
6
<ACKNOWLEDGEMENTS>
 
7
  This document was based on the Google C++ Style Guide
 
8
  <p>Revision 3.188</p>
 
9
  <address>
 
10
    Benjy Weinberger<br/>
 
11
    Craig Silverstein<br/>
 
12
    Gregory Eitzmann<br/>
 
13
    Mark Mentovai<br/>
 
14
    Tashana Landray
 
15
  </address>
 
16
</ACKNOWLEDGEMENTS>
 
17
-->
 
18
<p align="right">
 
19
Revision 4.0
 
20
</p>
 
21
 
 
22
<address>
 
23
Tim Penhey<br />
 
24
Neil J. Patel
 
25
</address>
 
26
 
 
27
<OVERVIEW>
 
28
<CATEGORY title="Important Note">
 
29
  <STYLEPOINT title="Displaying Hidden Details in this Guide">
 
30
     <SUMMARY>
 
31
       This style guide contains many details that are initially hidden from
 
32
       view.  They are marked by the triangle icon, which you see here on your
 
33
       left.  Click it now.  You should see "Hooray" appear below.
 
34
     </SUMMARY>
 
35
     <BODY>
 
36
       <p>
 
37
        Hooray!  Now you know you can expand points to get more
 
38
        details.  Alternatively, there's an "expand all" at the
 
39
        top of this document.
 
40
       </p>
 
41
     </BODY>
 
42
  </STYLEPOINT>
 
43
</CATEGORY>
 
44
<CATEGORY title="Background">
 
45
  <p>
 
46
    As every C++ programmer knows, the language has many powerful features,
 
47
    but this power brings with it complexity, which in turn can make code more
 
48
    bug-prone and harder to read and maintain.
 
49
  </p>
 
50
  <p>
 
51
    The goal of this guide is to manage this complexity by describing in
 
52
    detail the dos and don'ts of writing C++ code. These rules exist to keep
 
53
    the code base manageable while still allowing coders to use C++ language
 
54
    features productively.
 
55
  </p>
 
56
  <p>
 
57
    <em>Style</em>, also known as readability, is what we call the conventions
 
58
    that govern our C++ code. The term Style is a bit of a misnomer, since
 
59
    these conventions cover far more than just source file formatting.
 
60
  </p>
 
61
  <p>
 
62
    One way in which we keep the code base manageable is by enforcing
 
63
    <em>consistency</em>.  It is very important that any programmer be able to
 
64
    look at another's code and quickly understand it.  Maintaining a uniform
 
65
    style and following conventions means that we can more easily use
 
66
    "pattern-matching" to infer what various symbols are and what invariants
 
67
    are true about them. Creating common, required idioms and patterns makes
 
68
    code much easier to understand.  In some cases there might be good
 
69
    arguments for changing certain style rules, but we nonetheless keep things
 
70
    as they are in order to preserve consistency.
 
71
  </p>
 
72
  <p>
 
73
    Another issue this guide addresses is that of C++ feature bloat.  C++ is a
 
74
    huge language with many advanced features. In some cases we constrain, or
 
75
    even ban, use of certain features. We do this to keep code simple and to
 
76
    avoid the various common errors and problems that these features can
 
77
    cause.  This guide lists these features and explains why their use is
 
78
    restricted.
 
79
  </p>
 
80
  <p>
 
81
    Note that this guide is not a C++ tutorial: we assume that the reader is
 
82
    familiar with the language.
 
83
  </p>
 
84
</CATEGORY>
 
85
</OVERVIEW>
 
86
 
 
87
<CATEGORY title="Header Files">
 
88
  <p>
 
89
    In general, every <code>.cpp</code> file should have an associated
 
90
    <code>.h</code> file. There are some common exceptions, such as
 
91
    unittests and small <code>.cpp</code> files containing just a
 
92
    <code>main()</code> function.
 
93
  </p>
 
94
  <p>
 
95
    Correct use of header files can make a huge difference to the
 
96
    readability, size and performance of your code.
 
97
  </p>
 
98
  <p>
 
99
    The following rules will guide you through the various pitfalls of
 
100
    using header files.
 
101
  </p>
 
102
 
 
103
  <STYLEPOINT title="The #define Guard">
 
104
    <SUMMARY>
 
105
      All header files should have <code>#define</code> guards to
 
106
      prevent multiple inclusion.  The format of the symbol name
 
107
      should be
 
108
      <code><i>&lt;PROJECT&gt;</i>_<i>&lt;PATH&gt;</i>_<i>&lt;FILE&gt;</i>_H_</code>.
 
109
    </SUMMARY>
 
110
    <BODY>
 
111
 
 
112
      <p>
 
113
        To guarantee uniqueness, they should be based on the full path
 
114
        in a project's source tree.  For example, the file
 
115
        <code>foo/src/bar/baz.h</code> in project <code>foo</code> should
 
116
        have the following guard:
 
117
      </p>
 
118
      <CODE_SNIPPET>
 
119
         #ifndef FOO_BAR_BAZ_H_
 
120
         #define FOO_BAR_BAZ_H_
 
121
 
 
122
         ...
 
123
 
 
124
         #endif  // FOO_BAR_BAZ_H_
 
125
      </CODE_SNIPPET>
 
126
 
 
127
    </BODY>
 
128
  </STYLEPOINT>
 
129
 
 
130
  <STYLEPOINT title="Header File Dependencies">
 
131
    <SUMMARY>
 
132
        Don't use an <code>#include</code> when a forward declaration
 
133
        would suffice.
 
134
    </SUMMARY>
 
135
    <BODY>
 
136
      <p>
 
137
        When you include a header file you introduce a dependency that
 
138
        will cause your code to be recompiled whenever the header file
 
139
        changes. If your header file includes other header files, any
 
140
        change to those files will cause any code that includes your
 
141
        header to be recompiled.  Therefore, we prefer to minimize
 
142
        includes, particularly includes of header files in other
 
143
        header files.
 
144
      </p>
 
145
      <p>
 
146
        You can significantly reduce the number of header files you
 
147
        need to include in your own header files by using forward
 
148
        declarations.  For example, if your header file uses the
 
149
        <code>File</code> class in ways that do not require access to
 
150
        the declaration of the <code>File</code> class, your header
 
151
        file can just forward declare <code>class File;</code> instead
 
152
        of having to <code>#include "file/base/file.h"</code>.
 
153
      </p>
 
154
      <p>
 
155
        How can we use a class <code>Foo</code> in a header file
 
156
        without access to its definition?
 
157
      </p>
 
158
      <ul>
 
159
        <li> We can declare data members of type <code>Foo*</code> or
 
160
             <code>Foo&amp;</code>.
 
161
             </li>
 
162
        <li> We can declare (but not define) functions with arguments,
 
163
             and/or return values, of type <code>Foo</code>.  (One
 
164
             exception is if an argument <code>Foo</code>
 
165
             or <code>const Foo&amp;</code> has a
 
166
             non-<code>explicit</code>, one-argument constructor,
 
167
 
 
168
             in which case we need the full definition to support
 
169
             automatic type conversion.)
 
170
             </li>
 
171
        <li> We can declare static data members of type
 
172
             <code>Foo</code>.  This is because static data members
 
173
             are defined outside the class definition.
 
174
             </li>
 
175
      </ul>
 
176
      <p>
 
177
        On the other hand, you must include the header file for
 
178
        <code>Foo</code> if your class subclasses <code>Foo</code> or
 
179
        has a data member of type <code>Foo</code>.
 
180
      </p>
 
181
      <p>
 
182
        Sometimes it makes sense to have pointer (or better,
 
183
        <code>scoped_ptr</code>)
 
184
        members instead of object members. However, this complicates code
 
185
        readability and imposes a performance penalty, so avoid doing
 
186
        this transformation if the only purpose is to minimize includes
 
187
        in header files.
 
188
      </p>
 
189
      <p>
 
190
        Of course, <code>.cpp</code> files typically do require the
 
191
        definitions of the classes they use, and usually have to
 
192
        include several header files.
 
193
      </p>
 
194
 
 
195
      <SUBSECTION title="Note:">
 
196
        If you use a symbol <code>Foo</code> in your source file, you
 
197
        should bring in a definition for <code>Foo</code> yourself,
 
198
        either via an #include or via a forward declaration.  Do not
 
199
        depend on the symbol being brought in transitively via headers
 
200
        not directly included.  One exception is if <code>Foo</code>
 
201
        is used in <code>myfile.cpp</code>, it's ok to #include (or
 
202
        forward-declare) <code>Foo</code> in <code>myfile.h</code>,
 
203
        instead of <code>myfile.cpp</code>.
 
204
      </SUBSECTION>
 
205
    </BODY>
 
206
  </STYLEPOINT>
 
207
 
 
208
  <STYLEPOINT title="Inline Functions">
 
209
    <SUMMARY>
 
210
      Define functions inline only when they are small, say, 10 lines
 
211
      or less.
 
212
    </SUMMARY>
 
213
    <BODY>
 
214
      <DEFINITION>
 
215
        You can declare functions in a way that allows the compiler to
 
216
        expand them inline rather than calling them through the usual
 
217
        function call mechanism.
 
218
      </DEFINITION>
 
219
      <PROS>
 
220
        Inlining a function can generate more efficient object code,
 
221
        as long as the inlined function is small. Feel free to inline
 
222
        accessors and mutators, and other short, performance-critical
 
223
        functions.
 
224
      </PROS>
 
225
      <CONS>
 
226
        Overuse of inlining can actually make programs slower.
 
227
        Depending on a function's size, inlining it can cause the code
 
228
        size to increase or decrease.  Inlining a very small accessor
 
229
        function will usually decrease code size while inlining a very
 
230
        large function can dramatically increase code size.  On modern
 
231
        processors smaller code usually runs faster due to better use
 
232
        of the instruction cache.
 
233
      </CONS>
 
234
      <DECISION>
 
235
        <p>
 
236
          A decent rule of thumb is to not inline a function if it is
 
237
          more than 10 lines long. Beware of destructors, which are
 
238
          often longer than they appear because of implicit member-
 
239
          and base-destructor calls!
 
240
        </p>
 
241
        <p>
 
242
          Another useful rule of thumb: it's typically not cost
 
243
          effective to inline functions with loops or switch
 
244
          statements (unless, in the common case, the loop or switch
 
245
          statement is never executed).
 
246
        </p>
 
247
        <p>
 
248
          It is important to know that functions are not always
 
249
          inlined even if they are declared as such; for example,
 
250
          virtual and recursive functions are not normally inlined.
 
251
          Usually recursive functions should not be inline.  The main
 
252
          reason for making a virtual function inline is to place its
 
253
          definition in the class, either for convenience or to
 
254
          document its behavior, e.g., for accessors and mutators.
 
255
        </p>
 
256
      </DECISION>
 
257
    </BODY>
 
258
  </STYLEPOINT>
 
259
 
 
260
  <STYLEPOINT title="The -inl.h Files">
 
261
    <SUMMARY>
 
262
      You may use file names with a <code>-inl.h</code> suffix to define
 
263
      complex inline functions when needed.
 
264
    </SUMMARY>
 
265
    <BODY>
 
266
      <p>
 
267
        The definition of an inline function needs to be in a header
 
268
        file, so that the compiler has the definition available for
 
269
        inlining at the call sites.  However, implementation code
 
270
        properly belongs in <code>.cpp</code> files, and we do not like
 
271
        to have much actual code in <code>.h</code> files unless there
 
272
        is a readability or performance advantage.
 
273
      </p>
 
274
      <p>
 
275
        If an inline function definition is short, with very little,
 
276
        if any, logic in it, you should put the code in your
 
277
        <code>.h</code> file.  For example, accessors and mutators
 
278
        should certainly be inside a class definition.  More complex
 
279
        inline functions may also be put in a <code>.h</code> file for
 
280
        the convenience of the implementer and callers, though if this
 
281
        makes the <code>.h</code> file too unwieldy you can instead
 
282
        put that code in a separate <code>-inl.h</code> file.
 
283
        This separates the implementation from the class definition,
 
284
        while still allowing the implementation to be included where
 
285
        necessary.
 
286
      </p>
 
287
      <p>
 
288
        Another use of <code>-inl.h</code> files is for definitions of
 
289
        function templates.  This can be used to keep your template
 
290
        definitions easy to read.
 
291
      </p>
 
292
      <p>
 
293
        Do not forget that a <code>-inl.h</code> file requires a
 
294
        <a href="#The__define_Guard"><code>#define</code> guard</a> just
 
295
        like any other header file.
 
296
      </p>
 
297
 
 
298
    </BODY>
 
299
  </STYLEPOINT>
 
300
 
 
301
  <STYLEPOINT title="Function Parameter Ordering">
 
302
    <SUMMARY>
 
303
      When defining a function, parameter order is: inputs,
 
304
      then outputs.
 
305
    </SUMMARY>
 
306
    <BODY>
 
307
      <p>
 
308
        Parameters to C/C++ functions are either input to the
 
309
        function, output from the function, or both. Input parameters
 
310
        are usually values or <code>const</code> references, while output
 
311
        and input/output parameters will be non-<code>const</code>
 
312
        pointers. When ordering function parameters, put all input-only
 
313
        parameters before any output parameters.  In particular, do not add
 
314
        new parameters to the end of the function just because they are
 
315
        new; place new input-only parameters before the output
 
316
        parameters.
 
317
      </p>
 
318
      <p>
 
319
        This is not a hard-and-fast rule.  Parameters that are both
 
320
        input and output (often classes/structs) muddy the waters,
 
321
        and, as always, consistency with related functions may require
 
322
        you to bend the rule.
 
323
      </p>
 
324
    </BODY>
 
325
  </STYLEPOINT>
 
326
 
 
327
  <STYLEPOINT title="Names and Order of Includes">
 
328
    <SUMMARY>
 
329
      Use standard order for readability and to avoid hidden
 
330
      dependencies: C library, C++ library,
 
331
 
 
332
      other libraries' <code>.h</code>, your
 
333
      project's
 
334
      <code>.h</code>.
 
335
    </SUMMARY>
 
336
    <BODY>
 
337
      <p>
 
338
 
 
339
        All of a project's header files should be
 
340
        listed as descendants of the project's source directory
 
341
        without use of UNIX directory shortcuts <code>.</code> (the current
 
342
        directory) or <code>..</code> (the parent directory).  For
 
343
        example,
 
344
 
 
345
        <code>my-awesome-project/src/base/logging.h</code>
 
346
        should be included as
 
347
      </p>
 
348
      <CODE_SNIPPET>
 
349
        #include "base/logging.h"
 
350
      </CODE_SNIPPET>
 
351
      <p>
 
352
        In <code><var>dir/foo</var>.cpp</code> or <code><var>dir/foo_test</var>.cpp</code>,
 
353
        whose main purpose is to implement or test the stuff in
 
354
        <code><var>dir2/foo2</var>.h</code>, order your includes as
 
355
        follows:
 
356
      </p>
 
357
      <ol>
 
358
        <li> <code><var>dir2/foo2</var>.h</code> (preferred location
 
359
          &#8212; see details below).</li>
 
360
        <li> C system files.</li>
 
361
        <li> C++ system files.</li>
 
362
        <li> Other libraries' <code>.h</code> files.</li>
 
363
        <li>
 
364
             Your project's
 
365
             <code>.h</code> files.</li>
 
366
      </ol>
 
367
      <p>
 
368
        The preferred ordering reduces hidden dependencies.  We want
 
369
        every header file to be compilable on its own.  The easiest
 
370
        way to achieve this is to make sure that every one of them is
 
371
        the first <code>.h</code> file <code>#include</code>d in some
 
372
        <code>.cpp</code>.
 
373
      </p>
 
374
      <p>
 
375
        <code><var>dir/foo</var>.cpp</code> and
 
376
        <code><var>dir2/foo2</var>.h</code> are often in the same
 
377
        directory (e.g. <code>base/basictypes_test.cpp</code> and
 
378
        <code>base/basictypes.h</code>), but can be in different
 
379
        directories too.
 
380
      </p>
 
381
 
 
382
      <p>
 
383
        Within each section it is nice to order the includes
 
384
        alphabetically.
 
385
      </p>
 
386
      <p>
 
387
        For example, the includes in
 
388
 
 
389
        <code>my-awesome-project/src/foo/internal/fooserver.cpp</code>
 
390
        might look like this:
 
391
      </p>
 
392
      <CODE_SNIPPET>
 
393
        #include "foo/public/fooserver.h"  // Preferred location.
 
394
 
 
395
        #include &lt;sys/types.h&gt;
 
396
        #include &lt;unistd.h&gt;
 
397
 
 
398
        #include &lt;hash_map&gt;
 
399
        #include &lt;vector&gt;
 
400
 
 
401
        #include "base/basictypes.h"
 
402
        #include "base/commandlineflags.h"
 
403
        #include "foo/public/bar.h"
 
404
      </CODE_SNIPPET>
 
405
    </BODY>
 
406
  </STYLEPOINT>
 
407
</CATEGORY>
 
408
 
 
409
<CATEGORY title="Scoping">
 
410
  <STYLEPOINT title="Namespaces">
 
411
    <SUMMARY>
 
412
      Unnamed namespaces in <code>.cpp</code> files are encouraged.  With
 
413
      named namespaces, choose the name based on the
 
414
 
 
415
      project, and possibly its path.
 
416
      Do not use a <SYNTAX>using-directive</SYNTAX>.
 
417
    </SUMMARY>
 
418
    <BODY>
 
419
      <DEFINITION>
 
420
        Namespaces subdivide the global scope into distinct, named
 
421
        scopes, and so are useful for preventing name collisions in
 
422
        the global scope.
 
423
      </DEFINITION>
 
424
      <PROS>
 
425
        <p>
 
426
          Namespaces provide a (hierarchical) axis of naming, in
 
427
          addition to the (also hierarchical) name axis provided by
 
428
          classes.
 
429
        </p>
 
430
        <p>
 
431
          For example, if two different projects have a class
 
432
          <code>Foo</code> in the global scope, these symbols may
 
433
          collide at compile time or at runtime.  If each project
 
434
          places their code in a namespace, <code>project1::Foo</code>
 
435
          and <code>project2::Foo</code> are now distinct symbols that
 
436
          do not collide.
 
437
        </p>
 
438
      </PROS>
 
439
      <CONS>
 
440
        <p>
 
441
          Namespaces can be confusing, because they provide an
 
442
          additional (hierarchical) axis of naming, in addition to the
 
443
          (also hierarchical) name axis provided by classes.
 
444
        </p>
 
445
        <p>
 
446
          Use of unnamed spaces in header files can easily cause
 
447
          violations of the C++ One Definition Rule (ODR).
 
448
        </p>
 
449
      </CONS>
 
450
      <DECISION>
 
451
        <p>
 
452
          Use namespaces according to the policy described below.
 
453
        </p>
 
454
 
 
455
        <SUBSECTION title="Unnamed Namespaces">
 
456
          <ul>
 
457
            <li> Unnamed namespaces are allowed and even encouraged in
 
458
                 <code>.cpp</code> files, to avoid runtime naming
 
459
                 conflicts:
 
460
                 <CODE_SNIPPET>
 
461
                   namespace {                           // This is in a .cpp file.
 
462
 
 
463
                   // The content of a namespace is not indented
 
464
                   enum { kUnused, kEOF, kError };       // Commonly used tokens.
 
465
                   bool AtEof() { return pos_ == kEOF; }  // Uses our namespace's EOF.
 
466
 
 
467
                   }  // namespace
 
468
                 </CODE_SNIPPET>
 
469
 
 
470
                 <p>
 
471
                   However, file-scope declarations that are
 
472
                   associated with a particular class may be declared
 
473
                   in that class as types, static data members or
 
474
                   static member functions rather than as members of
 
475
                   an unnamed namespace.  Terminate the unnamed
 
476
                   namespace as shown, with a comment <code>//
 
477
                   namespace</code>.
 
478
                 </p>
 
479
                 </li>
 
480
            <li> Do not use unnamed namespaces in <code>.h</code>
 
481
                 files.
 
482
                 </li>
 
483
          </ul>
 
484
        </SUBSECTION>
 
485
 
 
486
        <SUBSECTION title="Named Namespaces">
 
487
          <p>
 
488
            Named namespaces should be used as follows:
 
489
          </p>
 
490
          <ul>
 
491
            <li> Namespaces wrap the entire source file after includes, <a
 
492
            href="http://google-gflags.googlecode.com/">gflags</a>
 
493
            definitions/declarations, and forward declarations of classes from
 
494
            other namespaces:
 
495
                 <CODE_SNIPPET>
 
496
                   // In the .h file
 
497
                   namespace mynamespace {
 
498
 
 
499
                   // All declarations are within the namespace scope.
 
500
                   // Notice the lack of indentation.
 
501
                   class MyClass {
 
502
                    public:
 
503
                     ...
 
504
                     void Foo();
 
505
                   };
 
506
 
 
507
                   }  // namespace mynamespace
 
508
                 </CODE_SNIPPET>
 
509
                 <CODE_SNIPPET>
 
510
                   // In the .cpp file
 
511
                   namespace mynamespace {
 
512
 
 
513
                   // Definition of functions is within scope of the namespace.
 
514
                   void MyClass::Foo() {
 
515
                     ...
 
516
                   }
 
517
 
 
518
                   }  // namespace mynamespace
 
519
                 </CODE_SNIPPET>
 
520
                 <p>
 
521
                   The typical <code>.cpp</code> file might have more
 
522
                   complex detail, including the need to reference classes
 
523
                   in other namespaces.
 
524
                 </p>
 
525
                 <CODE_SNIPPET>
 
526
                   #include "a.h"
 
527
 
 
528
                   DEFINE_bool(someflag, false, "dummy flag");
 
529
 
 
530
                   class C;  // Forward declaration of class C in the global namespace.
 
531
                   namespace a { class A; }  // Forward declaration of a::A.
 
532
 
 
533
                   namespace b {
 
534
 
 
535
                   ...code for b...         // Code goes against the left margin.
 
536
 
 
537
                   }  // namespace b
 
538
                 </CODE_SNIPPET>
 
539
                 </li>
 
540
 
 
541
 
 
542
 
 
543
            <li> Do not declare anything in namespace
 
544
                 <code>std</code>, not even forward declarations of
 
545
                 standard library classes.  Declaring entities in
 
546
                 namespace <code>std</code> is undefined behavior,
 
547
                 i.e., not portable.  To declare entities from the
 
548
                 standard library, include the appropriate header
 
549
                 file.
 
550
                 </li>
 
551
 
 
552
            <li> You may not use a <SYNTAX>using-directive</SYNTAX> to
 
553
                 make all names from a namespace available.
 
554
                 <BAD_CODE_SNIPPET>
 
555
                   // Forbidden -- This pollutes the namespace.
 
556
                   using namespace foo;
 
557
                 </BAD_CODE_SNIPPET>
 
558
                 </li>
 
559
 
 
560
            <li> You may use a <SYNTAX>using-declaration</SYNTAX>
 
561
                 anywhere in a <code>.cpp</code> file, and in functions,
 
562
                 methods or classes in <code>.h</code> files.
 
563
                 <CODE_SNIPPET>
 
564
                   // OK in .cpp files.
 
565
                   // Must be in a function, method or class in .h files.
 
566
                   using ::foo::bar;
 
567
                 </CODE_SNIPPET>
 
568
                 </li>
 
569
 
 
570
            <li> Namespace aliases are allowed anywhere in a
 
571
                 <code>.cpp</code> file, anywhere inside the named
 
572
                 namespace that wraps an entire <code>.h</code> file,
 
573
                 and in functions and methods.
 
574
                 <CODE_SNIPPET>
 
575
                   // Shorten access to some commonly used names in .cpp files.
 
576
                   namespace fbz = ::foo::bar::baz;
 
577
 
 
578
                   // Shorten access to some commonly used names (in a .h file).
 
579
                   namespace librarian {
 
580
                   // The following alias is available to all files including
 
581
                   // this header (in namespace librarian):
 
582
                   // alias names should therefore be chosen consistently
 
583
                   // within a project.
 
584
                   namespace pd_s = ::pipeline_diagnostics::sidetable;
 
585
 
 
586
                   inline void my_inline_function() {
 
587
                     // namespace alias local to a function (or method).
 
588
                     namespace fbz = ::foo::bar::baz;
 
589
                     ...
 
590
                   }
 
591
                   }  // namespace librarian
 
592
                 </CODE_SNIPPET>
 
593
                 <p>
 
594
                 Note that an alias in a .h file is visible to everyone
 
595
                 #including that file, so public headers (those available
 
596
                 outside a project) and headers transitively #included by them,
 
597
                 should avoid defining aliases, as part of the general
 
598
                 goal of keeping public APIs as small as possible.
 
599
                 </p>
 
600
                 </li>
 
601
          </ul>
 
602
        </SUBSECTION>
 
603
 
 
604
 
 
605
 
 
606
 
 
607
 
 
608
 
 
609
      </DECISION>
 
610
    </BODY>
 
611
  </STYLEPOINT>
 
612
 
 
613
  <STYLEPOINT title="Nested Classes">
 
614
    <SUMMARY>
 
615
      Although you may use public nested classes when they are part of
 
616
      an interface, consider a <a HREF="#Namespaces">namespace</a> to
 
617
      keep declarations out of the global scope.
 
618
    </SUMMARY>
 
619
    <BODY>
 
620
      <DEFINITION>
 
621
        A class can define another class within it; this is also
 
622
        called a <SYNTAX>member class</SYNTAX>.
 
623
        <CODE_SNIPPET>
 
624
          class Foo {
 
625
 
 
626
           private:
 
627
            // Bar is a member class, nested within Foo.
 
628
            class Bar {
 
629
              ...
 
630
            };
 
631
 
 
632
          };
 
633
        </CODE_SNIPPET>
 
634
      </DEFINITION>
 
635
      <PROS>
 
636
        This is useful when the nested (or member) class is only used
 
637
        by the enclosing class; making it a member puts it in the
 
638
        enclosing class scope rather than polluting the outer scope
 
639
        with the class name.  Nested classes can be forward declared
 
640
        within the enclosing class and then defined in the
 
641
        <code>.cpp</code> file to avoid including the nested class
 
642
        definition in the enclosing class declaration, since the
 
643
        nested class definition is usually only relevant to the
 
644
        implementation.
 
645
      </PROS>
 
646
      <CONS>
 
647
        Nested classes can be forward-declared only within the
 
648
        definition of the enclosing class. Thus, any header file
 
649
        manipulating a <code>Foo::Bar*</code> pointer will have to
 
650
        include the full class declaration for <code>Foo</code>.
 
651
      </CONS>
 
652
      <DECISION>
 
653
        Do not make nested classes public unless they are actually
 
654
        part of the interface, e.g., a class that holds a set of
 
655
        options for some method.
 
656
 
 
657
      </DECISION>
 
658
    </BODY>
 
659
  </STYLEPOINT>
 
660
 
 
661
  <STYLEPOINT title="Nonmember, Static Member, and Global Functions">
 
662
    <SUMMARY>
 
663
      Prefer nonmember functions within a namespace or static member
 
664
      functions to global functions; use completely global functions
 
665
      rarely.
 
666
    </SUMMARY>
 
667
    <BODY>
 
668
      <PROS>
 
669
        Nonmember and static member functions can be useful in some
 
670
        situations.  Putting nonmember functions in a namespace avoids
 
671
        polluting the global namespace.
 
672
      </PROS>
 
673
      <CONS>
 
674
        Nonmember and static member functions may make more sense as
 
675
        members of a new class, especially if they access external
 
676
        resources or have significant dependencies.
 
677
      </CONS>
 
678
      <DECISION>
 
679
        <p>
 
680
          Sometimes it is useful, or even necessary, to define a
 
681
          function not bound to a class instance.  Such a function can
 
682
          be either a static member or a nonmember function.
 
683
          Nonmember functions should not depend on external variables,
 
684
          and should nearly always exist in a namespace.  Rather than
 
685
          creating classes only to group static member functions which
 
686
          do not share static data, use
 
687
          <a href="#Namespaces">namespaces</a> instead.
 
688
        </p>
 
689
        <p>
 
690
          Functions defined in the same compilation unit as production
 
691
          classes may introduce unnecessary coupling and link-time
 
692
          dependencies when directly called from other compilation
 
693
          units; static member functions are particularly susceptible
 
694
          to this.  Consider extracting a new class, or placing the
 
695
          functions in a namespace possibly in a separate library.
 
696
        </p>
 
697
        <p>
 
698
          If you must define a nonmember function and it is only
 
699
          needed in its <code>.cpp</code> file, use an unnamed
 
700
          <a HREF="#Namespaces">namespace</a> or <code>static</code>
 
701
          linkage (eg <code>static int Foo() {...}</code>) to limit
 
702
          its scope.
 
703
        </p>
 
704
      </DECISION>
 
705
    </BODY>
 
706
  </STYLEPOINT>
 
707
 
 
708
  <STYLEPOINT title="Local Variables">
 
709
    <SUMMARY>
 
710
      Place a function's variables in the narrowest scope possible,
 
711
      and initialize variables in the declaration.
 
712
    </SUMMARY>
 
713
    <BODY>
 
714
      <p>
 
715
        C++ allows you to declare variables anywhere in a function.
 
716
        We encourage you to declare them in as local a scope as
 
717
        possible, and as close to the first use as possible. This
 
718
        makes it easier for the reader to find the declaration and see
 
719
        what type the variable is and what it was initialized to.  In
 
720
        particular, initialization should be used instead of
 
721
        declaration and assignment, e.g.
 
722
      </p>
 
723
      <BAD_CODE_SNIPPET>
 
724
        int i;
 
725
        i = f();      // Bad -- initialization separate from declaration.
 
726
      </BAD_CODE_SNIPPET>
 
727
      <CODE_SNIPPET>
 
728
        int j = g();  // Good -- declaration has initialization.
 
729
      </CODE_SNIPPET>
 
730
      <p>
 
731
        Note that gcc implements <code>for (int i = 0; i
 
732
        &lt; 10; ++i)</code> correctly (the scope of <code>i</code> is
 
733
        only the scope of the <code>for</code> loop), so you can then
 
734
        reuse <code>i</code> in another <code>for</code> loop in the
 
735
        same scope.  It also correctly scopes declarations in
 
736
        <code>if</code> and <code>while</code> statements, e.g.
 
737
      </p>
 
738
      <CODE_SNIPPET>
 
739
        while (const char* p = strchr(str, '/')) str = p + 1;
 
740
      </CODE_SNIPPET>
 
741
      <p>
 
742
        There is one caveat:  if the variable is an object, its
 
743
        constructor is invoked every time it enters scope and is
 
744
        created, and its destructor is invoked every time it goes
 
745
        out of scope.
 
746
      </p>
 
747
      <BAD_CODE_SNIPPET>
 
748
        // Inefficient implementation:
 
749
        for (int i = 0; i &lt; 1000000; ++i) {
 
750
          Foo f;  // My ctor and dtor get called 1000000 times each.
 
751
          f.DoSomething(i);
 
752
        }
 
753
      </BAD_CODE_SNIPPET>
 
754
      <p>
 
755
        It may be more efficient to declare such a variable used in a
 
756
        loop outside that loop:
 
757
      </p>
 
758
      <CODE_SNIPPET>
 
759
        Foo f;  // My ctor and dtor get called once each.
 
760
        for (int i = 0; i &lt; 1000000; ++i) {
 
761
          f.DoSomething(i);
 
762
        }
 
763
      </CODE_SNIPPET>
 
764
    </BODY>
 
765
  </STYLEPOINT>
 
766
 
 
767
  <STYLEPOINT title="Static and Global Variables">
 
768
    <SUMMARY>
 
769
      Static or global variables of class type are forbidden: they cause
 
770
      hard-to-find bugs due to indeterminate order of construction and
 
771
      destruction.
 
772
    </SUMMARY>
 
773
    <BODY>
 
774
      <p>
 
775
        Objects with static storage duration, including global variables,
 
776
        static variables, static class member variables, and function static
 
777
        variables, must be Plain Old Data (POD): only ints, chars, floats, or
 
778
        pointers, or arrays/structs of POD.
 
779
      </p>
 
780
      <p>
 
781
        The order in which class constructors and initializers for
 
782
        static variables are called is only partially specified in C++ and can
 
783
        even change from build to build, which can cause bugs that are difficult
 
784
        to find.  Therefore in addition to banning globals of class type, we do
 
785
        not allow static POD variables to be initialized with the result of a
 
786
        function, unless that function (such as getenv(), or getpid()) does not
 
787
        itself depend on any other globals.
 
788
      </p>
 
789
      <p>
 
790
        Likewise, the order in which destructors are called is defined to be the
 
791
        reverse of the order in which the constructors were called.  Since
 
792
        constructor order is indeterminate, so is destructor order.
 
793
        For example, at program-end time a static variable might have
 
794
        been destroyed, but code still running -- perhaps in another thread --
 
795
        tries to access it and fails.  Or the destructor for a static 'string'
 
796
        variable might be run prior to the destructor for another variable that
 
797
        contains a reference to that string.
 
798
      </p>
 
799
      <p>
 
800
        As a result we only allow static variables to contain POD data.  This
 
801
        rule completely disallows <code>vector</code> (use C arrays instead), or
 
802
        <code>string</code> (use <code>const char []</code>).
 
803
      </p>
 
804
 
 
805
      <p>
 
806
        If you need a static or global variable of a class type, consider
 
807
        initializing a pointer (which will never be freed), from either your
 
808
        main() function or from pthread_once().  Note that this must be a raw
 
809
        pointer, not a "smart" pointer, since the smart pointer's destructor
 
810
        will have the order-of-destructor issue that we are trying to avoid.
 
811
      </p>
 
812
 
 
813
 
 
814
    </BODY>
 
815
  </STYLEPOINT>
 
816
</CATEGORY>
 
817
 
 
818
<CATEGORY title="Classes">
 
819
  Classes are the fundamental unit of code in C++. Naturally, we use
 
820
  them extensively. This section lists the main dos and don'ts you
 
821
  should follow when writing a class.
 
822
 
 
823
  <STYLEPOINT title="Doing Work in Constructors">
 
824
    <SUMMARY>
 
825
      In general, constructors should merely set member variables to their
 
826
      initial values.  Any complex initialization should go in an explicit
 
827
      <code>Init()</code> method.
 
828
    </SUMMARY>
 
829
    <BODY>
 
830
      <DEFINITION>
 
831
        It is possible to perform initialization in the body of the
 
832
        constructor.
 
833
      </DEFINITION>
 
834
      <PROS>
 
835
        Convenience in typing.  No need to worry about whether the
 
836
        class has been initialized or not.
 
837
      </PROS>
 
838
      <CONS>
 
839
        The problems with doing work in constructors are:
 
840
        <ul>
 
841
          <li> There is no easy way for constructors to signal errors,
 
842
               short of using exceptions (which are
 
843
               <a HREF="#Exceptions">forbidden</a>).
 
844
               </li>
 
845
          <li> If the work fails, we now have an object whose
 
846
               initialization code failed, so it may be an
 
847
               indeterminate state.
 
848
               </li>
 
849
          <li> If the work calls virtual functions, these calls will
 
850
               not get dispatched to the subclass implementations.
 
851
               Future modification to your class can quietly introduce
 
852
               this problem even if your class is not currently
 
853
               subclassed, causing much confusion.
 
854
               </li>
 
855
          <li> If someone creates a global variable of this type
 
856
               (which is against the rules, but still), the
 
857
               constructor code will be called before
 
858
               <code>main()</code>, possibly breaking some implicit
 
859
               assumptions in the constructor code.  For instance,
 
860
 
 
861
               <a href="http://google-gflags.googlecode.com/">gflags</a>
 
862
               will not yet have been initialized.
 
863
               </li>
 
864
        </ul>
 
865
      </CONS>
 
866
      <DECISION>
 
867
        If your object requires non-trivial initialization, consider
 
868
        having an explicit <code>Init()</code> method.  In particular,
 
869
        constructors should not call virtual functions, attempt to raise
 
870
        errors, access potentially uninitialized global variables, etc.
 
871
      </DECISION>
 
872
    </BODY>
 
873
  </STYLEPOINT>
 
874
 
 
875
  <STYLEPOINT title="Default Constructors">
 
876
    <SUMMARY>
 
877
      You must define a default constructor if your class defines
 
878
      member variables and has no other constructors.  Otherwise the
 
879
      compiler will do it for you, badly.
 
880
    </SUMMARY>
 
881
    <BODY>
 
882
      <DEFINITION>
 
883
        The default constructor is called when we <code>new</code> a
 
884
        class object with no arguments.  It is always called when
 
885
        calling <code>new[]</code> (for arrays).
 
886
      </DEFINITION>
 
887
      <PROS>
 
888
        Initializing structures by default, to hold "impossible"
 
889
        values, makes debugging much easier.
 
890
      </PROS>
 
891
      <CONS>
 
892
        Extra work for you, the code writer.
 
893
      </CONS>
 
894
      <DECISION>
 
895
        <p>
 
896
          If your class defines member variables and has no other
 
897
          constructors you must define a default constructor (one that
 
898
          takes no arguments). It should preferably initialize the
 
899
          object in such a way that its internal state is consistent
 
900
          and valid.
 
901
        </p>
 
902
        <p>
 
903
          The reason for this is that if you have no other
 
904
          constructors and do not define a default constructor, the
 
905
          compiler will generate one for you. This compiler
 
906
          generated constructor may not initialize your object
 
907
          sensibly.
 
908
        </p>
 
909
        <p>
 
910
          If your class inherits from an existing class but you add no
 
911
          new member variables, you are not required to have a default
 
912
          constructor.
 
913
 
 
914
        </p>
 
915
      </DECISION>
 
916
    </BODY>
 
917
  </STYLEPOINT>
 
918
 
 
919
  <STYLEPOINT title="Explicit Constructors">
 
920
    <SUMMARY>
 
921
      Use the C++ keyword <code>explicit</code> for constructors with
 
922
      one argument.
 
923
    </SUMMARY>
 
924
    <BODY>
 
925
      <DEFINITION>
 
926
        Normally, if a constructor takes one argument, it can be used
 
927
        as a conversion.  For instance, if you define
 
928
        <code>Foo::Foo(string name)</code> and then pass a string to a
 
929
        function that expects a <code>Foo</code>, the constructor will
 
930
        be called to convert the string into a <code>Foo</code> and
 
931
        will pass the <code>Foo</code> to your function for you.  This
 
932
        can be convenient but is also a source of trouble when things
 
933
        get converted and new objects created without you meaning them
 
934
        to.  Declaring a constructor <code>explicit</code> prevents it
 
935
        from being invoked implicitly as a conversion.
 
936
      </DEFINITION>
 
937
      <PROS>
 
938
        Avoids undesirable conversions.
 
939
      </PROS>
 
940
      <CONS>
 
941
        None.
 
942
      </CONS>
 
943
      <DECISION>
 
944
        <p>
 
945
          We require all single argument constructors to be
 
946
          explicit. Always put <code>explicit</code> in front of
 
947
          one-argument constructors in the class definition:
 
948
          <code>explicit Foo(string name);</code>
 
949
        </p>
 
950
        <p>
 
951
          The exception is copy constructors, which, in the rare
 
952
          cases when we allow them, should probably not be
 
953
          <code>explicit</code>.
 
954
 
 
955
          Classes that are intended to be
 
956
          transparent wrappers around other classes are also
 
957
          exceptions.
 
958
          Such exceptions should be clearly marked with comments.
 
959
        </p>
 
960
      </DECISION>
 
961
    </BODY>
 
962
  </STYLEPOINT>
 
963
 
 
964
  <STYLEPOINT title="Copy Constructors">
 
965
    <SUMMARY>
 
966
      Provide a copy constructor and assignment operator only when necessary.
 
967
      Otherwise, disable them with <code>DISALLOW_COPY_AND_ASSIGN</code>.
 
968
    </SUMMARY>
 
969
    <BODY>
 
970
      <DEFINITION>
 
971
        The copy constructor and assignment operator are used to create copies
 
972
        of objects. The copy constructor is implicitly invoked by the
 
973
        compiler in some situations, e.g. passing objects by value.
 
974
      </DEFINITION>
 
975
      <PROS>
 
976
        Copy constructors make it easy to copy objects.  STL
 
977
        containers require that all contents be copyable and
 
978
        assignable. Copy constructors can be more efficient than
 
979
        <code>CopyFrom()</code>-style workarounds because they combine
 
980
        construction with copying, the compiler can elide them in some
 
981
        contexts, and they make it easier to avoid heap allocation.
 
982
      </PROS>
 
983
      <CONS>
 
984
        Implicit copying of objects in C++ is a rich source of bugs
 
985
        and of performance problems. It also reduces readability, as
 
986
        it becomes hard to track which objects are being passed around
 
987
        by value as opposed to by reference, and therefore where
 
988
        changes to an object are reflected.
 
989
      </CONS>
 
990
      <DECISION>
 
991
        <p>
 
992
          Few classes need to be copyable. Most should have neither a
 
993
          copy constructor nor an assignment operator. In many situations,
 
994
          a pointer or reference will work just as well as a copied value,
 
995
          with better performance. For example, you can pass function
 
996
          parameters by reference or pointer instead of by value, and you can
 
997
          store pointers rather than objects in an STL container.
 
998
        </p>
 
999
        <p>
 
1000
          If your class needs to be copyable, prefer providing a copy method,
 
1001
          such as <code>CopyFrom()</code> or <code>Clone()</code>, rather than
 
1002
          a copy constructor, because such methods cannot be invoked
 
1003
          implicitly. If a copy method is insufficient in your situation
 
1004
          (e.g. for performance reasons, or because your class needs to be
 
1005
          stored by value in an STL container), provide both a copy
 
1006
          constructor and assignment operator.
 
1007
        </p>
 
1008
        <p>
 
1009
          If your class does not need a copy constructor or assignment
 
1010
          operator, you must explicitly disable them.
 
1011
 
 
1012
 
 
1013
          To do so, add dummy declarations for the copy constructor and
 
1014
          assignment operator in the <code>private:</code> section of your
 
1015
          class, but do not provide any corresponding definition (so that
 
1016
          any attempt to use them results in a link error).
 
1017
        </p>
 
1018
        <p>
 
1019
          For convenience, a <code>DISALLOW_COPY_AND_ASSIGN</code> macro
 
1020
          can be used:
 
1021
        </p>
 
1022
        <CODE_SNIPPET>
 
1023
          // A macro to disallow the copy constructor and operator= functions
 
1024
          // This should be used in the private: declarations for a class
 
1025
          #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
 
1026
            TypeName(const TypeName&amp;);               \
 
1027
            void operator=(const TypeName&amp;)
 
1028
        </CODE_SNIPPET>
 
1029
        <p>
 
1030
          Then, in <code>class Foo</code>:
 
1031
        </p>
 
1032
        <CODE_SNIPPET>
 
1033
          class Foo {
 
1034
           public:
 
1035
            Foo(int f);
 
1036
            ~Foo();
 
1037
 
 
1038
           private:
 
1039
            DISALLOW_COPY_AND_ASSIGN(Foo);
 
1040
          };
 
1041
        </CODE_SNIPPET>
 
1042
        <p>
 
1043
        </p>
 
1044
 
 
1045
      </DECISION>
 
1046
    </BODY>
 
1047
  </STYLEPOINT>
 
1048
 
 
1049
  <STYLEPOINT title="Structs vs. Classes">
 
1050
    <SUMMARY>
 
1051
      Use a <code>struct</code> only for passive objects that carry data;
 
1052
      everything else is a <code>class</code>.
 
1053
    </SUMMARY>
 
1054
    <BODY>
 
1055
      <p>
 
1056
        The <code>struct</code> and <code>class</code> keywords behave
 
1057
        almost identically in C++.  We add our own semantic meanings
 
1058
        to each keyword, so you should use the appropriate keyword for
 
1059
        the data-type you're defining.
 
1060
      </p>
 
1061
      <p>
 
1062
        <code>structs</code> should be used for passive objects that carry
 
1063
        data, and may have associated constants, but lack any functionality
 
1064
        other than access/setting the data members. The
 
1065
        accessing/setting of fields is done by directly accessing the
 
1066
        fields rather than through method invocations. Methods should
 
1067
        not provide behavior but should only be used to set up the
 
1068
        data members, e.g., constructor, destructor,
 
1069
        <code>Initialize()</code>, <code>Reset()</code>,
 
1070
        <code>Validate()</code>.
 
1071
      </p>
 
1072
      <p>
 
1073
        If more functionality is required, a <code>class</code> is more
 
1074
        appropriate.  If in doubt, make it a <code>class</code>.
 
1075
      </p>
 
1076
      <p>
 
1077
        For consistency with STL, you can use <code>struct</code>
 
1078
        instead of <code>class</code> for functors and traits.
 
1079
      </p>
 
1080
      <p>
 
1081
        Note that member variables in structs and classes have
 
1082
        <a HREF="#Variable_Names">different naming rules</a>.
 
1083
      </p>
 
1084
    </BODY>
 
1085
  </STYLEPOINT>
 
1086
 
 
1087
  <STYLEPOINT title="Inheritance">
 
1088
    <SUMMARY>
 
1089
      Composition is often more appropriate than inheritance.  When
 
1090
      using inheritance, make it <code>public</code>.
 
1091
    </SUMMARY>
 
1092
    <BODY>
 
1093
      <DEFINITION>
 
1094
        When a sub-class inherits from a base class, it includes the
 
1095
        definitions of all the data and operations that the parent
 
1096
        base class defines.  In practice, inheritance is used in two
 
1097
        major ways in C++: implementation inheritance, in which
 
1098
        actual code is inherited by the child, and <A HREF="#Interfaces">interface inheritance</A>, in which only
 
1099
        method names are inherited.
 
1100
      </DEFINITION>
 
1101
      <PROS>
 
1102
        Implementation inheritance reduces code size by re-using the
 
1103
        base class code as it specializes an existing type.  Because
 
1104
        inheritance is a compile-time declaration, you and the
 
1105
        compiler can understand the operation and detect errors.
 
1106
        Interface inheritance can be used to programmatically enforce
 
1107
        that a class expose a particular API.  Again, the compiler
 
1108
        can detect errors, in this case, when a class does not define
 
1109
        a necessary method of the API.
 
1110
      </PROS>
 
1111
      <CONS>
 
1112
        For implementation inheritance, because the code implementing
 
1113
        a sub-class is spread between the base and the sub-class, it
 
1114
        can be more difficult to understand an implementation.  The
 
1115
        sub-class cannot override functions that are not virtual, so
 
1116
        the sub-class cannot change implementation.  The base class
 
1117
        may also define some data members, so that specifies physical
 
1118
        layout of the base class.
 
1119
      </CONS>
 
1120
      <DECISION>
 
1121
        <p>
 
1122
          All inheritance should be <code>public</code>.  If you want to
 
1123
          do private inheritance, you should be including an instance of
 
1124
          the base class as a member instead.
 
1125
        </p>
 
1126
        <p>
 
1127
          Do not overuse implementation inheritance.  Composition is
 
1128
          often more appropriate. Try to restrict use of inheritance
 
1129
          to the "is-a" case: <code>Bar</code> subclasses
 
1130
          <code>Foo</code> if it can reasonably be said that
 
1131
          <code>Bar</code> "is a kind of" <code>Foo</code>.
 
1132
        </p>
 
1133
        <p>
 
1134
          Make your destructor <code>virtual</code> if necessary. If
 
1135
          your class has virtual methods, its destructor
 
1136
 
 
1137
          should be virtual.
 
1138
        </p>
 
1139
        <p>
 
1140
          Limit the use of <code>protected</code> to those member
 
1141
          functions that might need to be accessed from subclasses.
 
1142
          Note that <a href="#Access_Control">data members should
 
1143
          be private</a>.
 
1144
        </p>
 
1145
        <p>
 
1146
          When redefining an inherited virtual function, explicitly
 
1147
          declare it <code>virtual</code> in the declaration of the
 
1148
          derived class.  Rationale: If <code>virtual</code> is
 
1149
          omitted, the reader has to check all ancestors of the
 
1150
          class in question to determine if the function is virtual
 
1151
          or not.
 
1152
        </p>
 
1153
      </DECISION>
 
1154
    </BODY>
 
1155
  </STYLEPOINT>
 
1156
 
 
1157
  <STYLEPOINT title="Multiple Inheritance">
 
1158
    <SUMMARY>
 
1159
      Only very rarely is multiple implementation inheritance actually
 
1160
      useful.  We allow multiple inheritance only when at most one of
 
1161
      the base classes has an implementation; all other base classes
 
1162
      must be <A HREF="#Interfaces">pure interface</A> classes tagged
 
1163
      with the <code>Interface</code> suffix.
 
1164
    </SUMMARY>
 
1165
    <BODY>
 
1166
      <DEFINITION>
 
1167
        Multiple inheritance allows a sub-class to have more than one
 
1168
        base class.  We distinguish between base classes that are
 
1169
        <em>pure interfaces</em> and those that have an
 
1170
        <em>implementation</em>.
 
1171
      </DEFINITION>
 
1172
      <PROS>
 
1173
        Multiple implementation inheritance may let you re-use even more code
 
1174
        than single inheritance (see <a HREF="#Inheritance">Inheritance</a>).
 
1175
      </PROS>
 
1176
      <CONS>
 
1177
        Only very rarely is multiple <em>implementation</em>
 
1178
        inheritance actually useful. When multiple implementation
 
1179
        inheritance seems like the solution, you can usually find a
 
1180
        different, more explicit, and cleaner solution.
 
1181
      </CONS>
 
1182
      <DECISION>
 
1183
        Multiple inheritance is allowed only when all superclasses, with the
 
1184
        possible exception of the first one, are <A HREF="#Interfaces">pure
 
1185
        interfaces</A>.  In order to ensure that they remain pure interfaces,
 
1186
        they must end with the <code>Interface</code> suffix.
 
1187
        <SUBSECTION title="Note:">
 
1188
          There is an <a HREF="#Windows_Code">exception</a> to this
 
1189
          rule on Windows.
 
1190
        </SUBSECTION>
 
1191
      </DECISION>
 
1192
    </BODY>
 
1193
  </STYLEPOINT>
 
1194
 
 
1195
  <STYLEPOINT title="Interfaces">
 
1196
    <SUMMARY>
 
1197
      Classes that satisfy certain conditions are allowed, but not required, to
 
1198
      end with an <code>Interface</code> suffix.
 
1199
    </SUMMARY>
 
1200
    <BODY>
 
1201
      <DEFINITION>
 
1202
        <p>
 
1203
        A class is a pure interface if it meets the following requirements:
 
1204
        </p>
 
1205
        <ul>
 
1206
          <li> It has only public pure virtual ("<code>= 0</code>") methods
 
1207
               and static methods (but see below for destructor).
 
1208
               </li>
 
1209
          <li> It may not have non-static data members.
 
1210
               </li>
 
1211
          <li> It need not have any constructors defined.  If a constructor is
 
1212
               provided, it must take no arguments and it must be protected.
 
1213
               </li>
 
1214
          <li> If it is a subclass, it may only be derived from classes
 
1215
               that satisfy these conditions and are tagged with the
 
1216
               <code>Interface</code> suffix.
 
1217
               </li>
 
1218
        </ul>
 
1219
        <p>
 
1220
          An interface class can never be directly instantiated
 
1221
          because of the pure virtual method(s) it declares.  To make
 
1222
          sure all implementations of the interface can be destroyed
 
1223
          correctly, they must also declare a virtual destructor (in
 
1224
          an exception to the first rule, this should not be pure).  See
 
1225
          Stroustrup, <cite>The C++ Programming Language</cite>, 3rd
 
1226
          edition, section 12.4 for details.
 
1227
        </p>
 
1228
      </DEFINITION>
 
1229
      <PROS>
 
1230
        Tagging a class with the <code>Interface</code> suffix lets
 
1231
        others know that they must not add implemented methods or non
 
1232
        static data members.  This is particularly important in the case of
 
1233
        <A HREF="#Multiple_Inheritance">multiple inheritance</A>.
 
1234
        Additionally, the interface concept is already well-understood by
 
1235
        Java programmers.
 
1236
      </PROS>
 
1237
      <CONS>
 
1238
        The <code>Interface</code> suffix lengthens the class name, which
 
1239
        can make it harder to read and understand.  Also, the interface
 
1240
        property may be considered an implementation detail that shouldn't
 
1241
        be exposed to clients.
 
1242
      </CONS>
 
1243
      <DECISION>
 
1244
        A class may end with <code>Interface</code> only if it meets the
 
1245
        above requirements.  We do not require the converse, however:
 
1246
        classes that meet the above requirements are not required to end
 
1247
        with <code>Interface</code>.
 
1248
      </DECISION>
 
1249
    </BODY>
 
1250
  </STYLEPOINT>
 
1251
 
 
1252
  <STYLEPOINT title="Operator Overloading">
 
1253
    <SUMMARY>
 
1254
      Do not overload operators except in rare, special circumstances.
 
1255
    </SUMMARY>
 
1256
    <BODY>
 
1257
      <DEFINITION>
 
1258
        A class can define that operators such as <code>+</code> and
 
1259
        <code>/</code> operate on the class as if it were a built-in
 
1260
        type.
 
1261
      </DEFINITION>
 
1262
      <PROS>
 
1263
        Can make code appear more intuitive because a class will
 
1264
        behave in the same way as built-in types (such as
 
1265
        <code>int</code>).  Overloaded operators are more playful
 
1266
        names for functions that are less-colorfully named, such as
 
1267
        <code>Equals()</code> or <code>Add()</code>.  For some
 
1268
        template functions to work correctly, you may need to define
 
1269
        operators.
 
1270
      </PROS>
 
1271
      <CONS>
 
1272
        While operator overloading can make code more intuitive, it
 
1273
        has several drawbacks:
 
1274
        <ul>
 
1275
          <li> It can fool our intuition into thinking that expensive
 
1276
               operations are cheap, built-in operations.
 
1277
               </li>
 
1278
          <li> It is much harder to find the call sites for overloaded
 
1279
               operators.  Searching for <code>Equals()</code> is much
 
1280
               easier than searching for relevant invocations of
 
1281
               <code>==</code>.
 
1282
               </li>
 
1283
          <li> Some operators work on pointers too, making it easy to
 
1284
               introduce bugs.  <code>Foo + 4</code> may do one thing,
 
1285
               while <code>&amp;Foo + 4</code> does something totally
 
1286
               different. The compiler does not complain for either of
 
1287
               these, making this very hard to debug.
 
1288
               </li>
 
1289
        </ul>
 
1290
        Overloading also has surprising ramifications.  For instance,
 
1291
        if a class overloads unary <code>operator&amp;</code>, it
 
1292
        cannot safely be forward-declared.
 
1293
      </CONS>
 
1294
      <DECISION>
 
1295
        <p>
 
1296
          In general, do not overload operators. The assignment operator
 
1297
          (<code>operator=</code>), in particular, is insidious and
 
1298
          should be avoided.  You can define functions like
 
1299
          <code>Equals()</code> and <code>CopyFrom()</code> if you
 
1300
          need them.  Likewise, avoid the dangerous
 
1301
          unary <code>operator&amp;</code> at all costs, if there's
 
1302
          any possibility the class might be forward-declared.
 
1303
        </p>
 
1304
        <p>
 
1305
          However, there may be rare cases where you need to overload
 
1306
          an operator to interoperate with templates or "standard" C++
 
1307
          classes (such as <code>operator&lt;&lt;(ostream&amp;, const
 
1308
          T&amp;)</code> for logging).  These are acceptable if fully
 
1309
          justified, but you should try to avoid these whenever
 
1310
          possible.  In particular, do not overload <code>operator==</code>
 
1311
          or <code>operator&lt;</code> just so that your class can be
 
1312
          used as a key in an STL container; instead, you should
 
1313
          create equality and comparison functor types when declaring
 
1314
          the container.
 
1315
        </p>
 
1316
        <p>
 
1317
          Some of the STL algorithms do require you to overload
 
1318
          <code>operator==</code>, and you may do so in these cases,
 
1319
          provided you document why.
 
1320
        </p>
 
1321
        <p>
 
1322
          See also <a HREF="#Copy_Constructors">Copy Constructors</a>
 
1323
          and <a HREF="#Function_Overloading">Function
 
1324
          Overloading</a>.
 
1325
        </p>
 
1326
      </DECISION>
 
1327
    </BODY>
 
1328
  </STYLEPOINT>
 
1329
 
 
1330
  <STYLEPOINT title="Access Control">
 
1331
    <SUMMARY>
 
1332
      Make data members <code>private</code>, and provide
 
1333
      access to them through accessor functions as needed (for
 
1334
      technical reasons, we allow data members of a test fixture class
 
1335
      to be <code>protected</code> when using
 
1336
 
 
1337
      <A HREF="http://code.google.com/p/googletest/">
 
1338
      Google Test</A>). Typically a variable would be
 
1339
      called <code>foo_</code> and the accessor function
 
1340
      <code>foo()</code>.  You may also want a mutator function
 
1341
      <code>set_foo()</code>.
 
1342
      Exception: <code>static const</code> data members (typically
 
1343
      called <code>kFoo</code>) need not be <code>private</code>.
 
1344
    </SUMMARY>
 
1345
    <BODY>
 
1346
      <p>
 
1347
        The definitions of accessors are usually inlined in the header
 
1348
        file.
 
1349
      </p>
 
1350
      <p>
 
1351
        See also <a HREF="#Inheritance">Inheritance</a> and <a HREF="#Function_Names">Function Names</a>.
 
1352
      </p>
 
1353
    </BODY>
 
1354
  </STYLEPOINT>
 
1355
 
 
1356
  <STYLEPOINT title="Declaration Order">
 
1357
    <SUMMARY>
 
1358
      Use the specified order of declarations within a class:
 
1359
      <code>public:</code> before <code>private:</code>, methods
 
1360
      before data members (variables), etc.
 
1361
    </SUMMARY>
 
1362
    <BODY>
 
1363
      <p>
 
1364
        Your class definition should start with its <code>public:</code>
 
1365
        section, followed by its <code>protected:</code> section and
 
1366
        then its <code>private:</code> section. If any of these sections
 
1367
        are empty, omit them.
 
1368
      </p>
 
1369
      <p>
 
1370
        Within each section, the declarations generally should be in
 
1371
        the following order:
 
1372
      </p>
 
1373
      <ul>
 
1374
        <li> Typedefs and Enums</li>
 
1375
        <li> Constants (<code>static const</code> data members)</li>
 
1376
        <li> Constructors</li>
 
1377
        <li> Destructor</li>
 
1378
        <li> Methods, including static methods</li>
 
1379
        <li> Data Members (except <code>static const</code> data members)</li>
 
1380
      </ul>
 
1381
      <p>
 
1382
        Friend declarations should always be in the private section, and
 
1383
        the <code>DISALLOW_COPY_AND_ASSIGN</code> macro invocation
 
1384
        should be at the end of the <code>private:</code> section. It
 
1385
        should be the last thing in the class. See <a HREF="#Copy_Constructors">Copy Constructors</a>.
 
1386
      </p>
 
1387
      <p>
 
1388
        Method definitions in the corresponding <code>.cpp</code> file
 
1389
        should be the same as the declaration order, as much as possible.
 
1390
      </p>
 
1391
      <p>
 
1392
        Do not put large method definitions inline in the class
 
1393
        definition.  Usually, only trivial or performance-critical,
 
1394
        and very short, methods may be defined inline.  See <a HREF="#Inline_Functions">Inline Functions</a> for more
 
1395
        details.
 
1396
      </p>
 
1397
    </BODY>
 
1398
  </STYLEPOINT>
 
1399
 
 
1400
  <STYLEPOINT title="Write Short Functions">
 
1401
    <SUMMARY>
 
1402
      Prefer small and focused functions.
 
1403
    </SUMMARY>
 
1404
    <BODY>
 
1405
      <p>
 
1406
        We recognize that long functions are sometimes appropriate, so
 
1407
        no hard limit is placed on functions length. If a function
 
1408
        exceeds about 40 lines, think about whether it can be broken
 
1409
        up without harming the structure of the program.
 
1410
      </p>
 
1411
      <p>
 
1412
        Even if your long function works perfectly now, someone
 
1413
        modifying it in a few months may add new behavior. This could
 
1414
        result in bugs that are hard to find.  Keeping your functions
 
1415
        short and simple makes it easier for other people to read and
 
1416
        modify your code.
 
1417
      </p>
 
1418
      <p>
 
1419
        You could find long and complicated functions when working
 
1420
        with
 
1421
 
 
1422
        some
 
1423
        code.  Do not be intimidated by modifying existing
 
1424
        code: if working with such a function proves to be difficult,
 
1425
        you find that errors are hard to debug, or you want to use a
 
1426
        piece of it in several different contexts, consider breaking
 
1427
        up the function into smaller and more manageable pieces.
 
1428
      </p>
 
1429
    </BODY>
 
1430
  </STYLEPOINT>
 
1431
</CATEGORY>
 
1432
 
 
1433
<CATEGORY title="Google-Specific Magic">
 
1434
 
 
1435
  <p>
 
1436
    There are various tricks and utilities that we use to make C++
 
1437
    code more robust, and various ways we use C++ that may differ from
 
1438
    what you see elsewhere.
 
1439
  </p>
 
1440
 
 
1441
 
 
1442
 
 
1443
  <STYLEPOINT title="Smart Pointers">
 
1444
 
 
1445
    <SUMMARY>
 
1446
      If you actually need pointer semantics, <code>scoped_ptr</code>
 
1447
      is great.  You should only use <code>std::tr1::shared_ptr</code>
 
1448
      with a non-const referent when it is truly necessary to share ownership
 
1449
      of an object (e.g. inside an STL container). You should never use
 
1450
      <code>auto_ptr</code>.
 
1451
    </SUMMARY>
 
1452
    <BODY>
 
1453
      <DEFINITION>
 
1454
        "Smart" pointers are objects that act like pointers, but automate
 
1455
        management of the underlying memory.
 
1456
      </DEFINITION>
 
1457
      <PROS>
 
1458
        Smart pointers are extremely useful for preventing memory leaks, and
 
1459
        are essential for writing exception-safe code. They also formalize
 
1460
        and document the ownership of dynamically allocated memory.
 
1461
      </PROS>
 
1462
      <CONS>
 
1463
        We prefer designs in which objects have single, fixed owners. Smart
 
1464
        pointers which enable sharing or transfer of ownership can act as a
 
1465
        tempting alternative to a careful design of ownership semantics,
 
1466
        leading to confusing code and even bugs in which memory is never
 
1467
        deleted. The semantics of smart pointers (especially
 
1468
        <code>auto_ptr</code>) can be nonobvious and confusing. The
 
1469
        exception-safety benefits of smart pointers are not decisive, since
 
1470
        we do not allow exceptions.
 
1471
      </CONS>
 
1472
      <DECISION>
 
1473
        <dl>
 
1474
          <dt><code>scoped_ptr</code></dt>
 
1475
          <dd>Straightforward and risk-free. Use wherever appropriate.</dd>
 
1476
          <dt><code>auto_ptr</code></dt>
 
1477
          <dd>Confusing and bug-prone ownership-transfer semantics. Do not use.
 
1478
            </dd>
 
1479
          <dt><code>shared_ptr</code></dt>
 
1480
          <dd>
 
1481
          Safe with const referents (i.e. <code>shared_ptr&lt;const
 
1482
          T&gt;</code>). Reference-counted pointers with non-const referents
 
1483
          can occasionally be the best design, but try to rewrite with single
 
1484
          owners where possible.
 
1485
          </dd>
 
1486
        </dl>
 
1487
      </DECISION>
 
1488
    </BODY>
 
1489
  </STYLEPOINT>
 
1490
 
 
1491
  <STYLEPOINT title="cpplint">
 
1492
    <SUMMARY>
 
1493
      Use
 
1494
      <code>cpplint.py</code>
 
1495
      to detect style errors.
 
1496
    </SUMMARY>
 
1497
    <BODY>
 
1498
      <p>
 
1499
        <code>cpplint.py</code>
 
1500
        is a tool that reads a source file and
 
1501
        identifies many style errors.  It is not perfect, and has both false
 
1502
        positives and false negatives, but it is still a valuable tool.  False
 
1503
        positives can be ignored by putting <code>// NOLINT</code> at
 
1504
        the end of the line.
 
1505
      </p>
 
1506
 
 
1507
      <p>
 
1508
        Some projects have instructions on how to run <code>cpplint.py</code>
 
1509
        from their project tools. If the project you are contributing to does
 
1510
        not, you can download <A HREF="http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py"><code>cpplint.py</code></A> separately.
 
1511
      </p>
 
1512
    </BODY>
 
1513
  </STYLEPOINT>
 
1514
 
 
1515
 
 
1516
</CATEGORY>
 
1517
 
 
1518
<CATEGORY title="Other C++ Features">
 
1519
  <STYLEPOINT title="Reference Arguments">
 
1520
    <SUMMARY>
 
1521
      All parameters passed by reference must be labeled
 
1522
      <code>const</code>.
 
1523
    </SUMMARY>
 
1524
    <BODY>
 
1525
      <DEFINITION>
 
1526
        In C, if a function needs to modify a variable, the
 
1527
        parameter must use a pointer, eg <code>int foo(int
 
1528
        *pval)</code>.  In C++, the function can alternatively
 
1529
        declare a reference parameter: <code>int foo(int
 
1530
        &amp;val)</code>.
 
1531
      </DEFINITION>
 
1532
      <PROS>
 
1533
        Defining a parameter as reference avoids ugly code like
 
1534
        <code>(*pval)++</code>.  Necessary for some applications like
 
1535
        copy constructors.  Makes it clear, unlike with pointers, that
 
1536
        <code>NULL</code> is not a possible value.
 
1537
      </PROS>
 
1538
      <CONS>
 
1539
        References can be confusing, as they have value syntax but
 
1540
        pointer semantics.
 
1541
      </CONS>
 
1542
      <DECISION>
 
1543
        <p>
 
1544
          Within function parameter lists all references must be
 
1545
          <code>const</code>:
 
1546
        </p>
 
1547
        <CODE_SNIPPET>
 
1548
          void Foo(const string &amp;in, string *out);
 
1549
        </CODE_SNIPPET>
 
1550
        <p>
 
1551
          In fact it is a very strong convention in Unity code that input
 
1552
          arguments are values or <code>const</code> references while
 
1553
          output arguments are pointers.  Input parameters may be
 
1554
          <code>const</code> pointers, but we never allow
 
1555
          non-<code>const</code> reference parameters.
 
1556
        </p>
 
1557
        <p>
 
1558
          One case when you might want an input parameter to be a
 
1559
          <code>const</code> pointer is if you want to emphasize that the
 
1560
          argument is not copied, so it must exist for the lifetime of the
 
1561
          object; it is usually best to document this in comments as
 
1562
          well.  STL adapters such as <code>bind2nd</code> and
 
1563
          <code>mem_fun</code> do not permit reference parameters, so
 
1564
          you must declare functions with pointer parameters in these
 
1565
          cases, too.
 
1566
        </p>
 
1567
      </DECISION>
 
1568
    </BODY>
 
1569
  </STYLEPOINT>
 
1570
 
 
1571
  <STYLEPOINT title="Function Overloading">
 
1572
    <SUMMARY>
 
1573
      Use overloaded functions (including constructors) only if a
 
1574
      reader looking at a call site can get a good idea of what is
 
1575
      happening without having to first figure out exactly which
 
1576
      overload is being called.
 
1577
    </SUMMARY>
 
1578
    <BODY>
 
1579
      <DEFINITION>
 
1580
        <p>
 
1581
          You may write a function that takes a
 
1582
          <code>const string&amp;</code> and overload it with another that
 
1583
          takes <code>const char*</code>.
 
1584
        </p>
 
1585
        <CODE_SNIPPET>
 
1586
          class MyClass {
 
1587
           public:
 
1588
            void Analyze(const string &amp;text);
 
1589
            void Analyze(const char *text, size_t textlen);
 
1590
          };
 
1591
        </CODE_SNIPPET>
 
1592
      </DEFINITION>
 
1593
      <PROS>
 
1594
        Overloading can make code more intuitive by allowing an
 
1595
        identically-named function to take different arguments.  It
 
1596
        may be necessary for templatized code, and it can be
 
1597
        convenient for Visitors.
 
1598
      </PROS>
 
1599
      <CONS>
 
1600
        If a function is overloaded by the argument types alone, a
 
1601
        reader may have to understand C++'s complex matching rules in
 
1602
        order to tell what's going on.  Also many people are confused
 
1603
        by the semantics of inheritance if a derived class overrides
 
1604
        only some of the variants of a function.
 
1605
      </CONS>
 
1606
      <DECISION>
 
1607
        If you want to overload a function, consider qualifying the
 
1608
        name with some information about the arguments, e.g.,
 
1609
        <code>AppendString()</code>, <code>AppendInt()</code> rather
 
1610
        than just <code>Append()</code>.
 
1611
 
 
1612
      </DECISION>
 
1613
    </BODY>
 
1614
  </STYLEPOINT>
 
1615
 
 
1616
  <STYLEPOINT title="Default Arguments">
 
1617
    <SUMMARY>
 
1618
      We do not allow default function parameters, except in
 
1619
      a few uncommon situations explained below.
 
1620
    </SUMMARY>
 
1621
    <BODY>
 
1622
      <PROS>
 
1623
        Often you have a function that uses lots of default values,
 
1624
        but occasionally you want to override the defaults.  Default
 
1625
        parameters allow an easy way to do this without having to
 
1626
        define many functions for the rare exceptions.
 
1627
      </PROS>
 
1628
      <CONS>
 
1629
        People often figure out how to use an
 
1630
        API by looking at existing code that uses it.
 
1631
        Default parameters are more difficult to maintain because
 
1632
        copy-and-paste from previous code may not reveal all the
 
1633
        parameters.  Copy-and-pasting of code segments can cause major
 
1634
        problems when the default arguments are not appropriate for
 
1635
        the new code.
 
1636
      </CONS>
 
1637
      <DECISION>
 
1638
        <p>
 
1639
          Except as described below, we require all arguments to be
 
1640
          explicitly specified, to force programmers to consider the API
 
1641
          and the values they are passing for each argument rather than
 
1642
          silently accepting defaults they may not be aware of.
 
1643
        </p>
 
1644
        <p>
 
1645
          One specific exception is when default arguments are used to
 
1646
          simulate variable-length argument lists.
 
1647
        </p>
 
1648
        <CODE_SNIPPET>
 
1649
          // Support up to 4 params by using a default empty AlphaNum.
 
1650
          string StrCat(const AlphaNum &amp;a,
 
1651
                        const AlphaNum &amp;b = gEmptyAlphaNum,
 
1652
                        const AlphaNum &amp;c = gEmptyAlphaNum,
 
1653
                        const AlphaNum &amp;d = gEmptyAlphaNum);
 
1654
        </CODE_SNIPPET>
 
1655
      </DECISION>
 
1656
    </BODY>
 
1657
  </STYLEPOINT>
 
1658
 
 
1659
  <STYLEPOINT title="Variable-Length Arrays and alloca()">
 
1660
    <SUMMARY>
 
1661
      We do not allow variable-length arrays or <code>alloca()</code>.
 
1662
    </SUMMARY>
 
1663
    <BODY>
 
1664
      <PROS>
 
1665
        Variable-length arrays have natural-looking syntax.  Both
 
1666
        variable-length arrays and <code>alloca()</code> are very
 
1667
        efficient.
 
1668
      </PROS>
 
1669
      <CONS>
 
1670
        Variable-length arrays and alloca are not part of Standard
 
1671
        C++.  More importantly, they allocate a data-dependent amount
 
1672
        of stack space that can trigger difficult-to-find memory
 
1673
        overwriting bugs: "It ran fine on my machine, but dies
 
1674
        mysteriously in production".
 
1675
      </CONS>
 
1676
 
 
1677
      <DECISION>
 
1678
        Use a safe allocator instead, such as
 
1679
        <code>scoped_ptr</code>/<code>scoped_array</code>.
 
1680
      </DECISION>
 
1681
    </BODY>
 
1682
  </STYLEPOINT>
 
1683
 
 
1684
  <STYLEPOINT title="Friends">
 
1685
    <SUMMARY>
 
1686
      We allow use of <code>friend</code> classes and functions,
 
1687
      within reason.
 
1688
    </SUMMARY>
 
1689
    <BODY>
 
1690
      <p>
 
1691
        Friends should usually be defined in the same file so that the
 
1692
        reader does not have to look in another file to find uses of
 
1693
        the private members of a class.  A common use of
 
1694
        <code>friend</code> is to have a <code>FooBuilder</code> class
 
1695
        be a friend of <code>Foo</code> so that it can construct the
 
1696
        inner state of <code>Foo</code> correctly, without exposing
 
1697
        this state to the world.  In some cases it may be useful to
 
1698
        make a unittest class a friend of the class it tests.
 
1699
      </p>
 
1700
      <p>
 
1701
        Friends extend, but do not break, the encapsulation
 
1702
        boundary of a class.  In some cases this is better than making
 
1703
        a member public when you want to give only one other class
 
1704
        access to it.  However, most classes should interact with
 
1705
        other classes solely through their public members.
 
1706
      </p>
 
1707
    </BODY>
 
1708
  </STYLEPOINT>
 
1709
 
 
1710
  <STYLEPOINT title="Exceptions">
 
1711
    <SUMMARY>
 
1712
      We do not use C++ exceptions.
 
1713
    </SUMMARY>
 
1714
    <BODY>
 
1715
      <PROS>
 
1716
        <ul>
 
1717
          <li>Exceptions allow higher levels of an application to
 
1718
          decide how to handle "can't happen" failures in deeply
 
1719
          nested functions, without the obscuring and error-prone
 
1720
          bookkeeping of error codes.</li>
 
1721
 
 
1722
 
 
1723
 
 
1724
          <li>Exceptions are used by most other modern
 
1725
          languages.  Using them in C++ would make it more consistent with
 
1726
          Python, Java, and the C++ that others are familiar with.</li>
 
1727
 
 
1728
          <li>Some third-party C++ libraries use exceptions, and turning
 
1729
          them off internally makes it harder to integrate with those
 
1730
          libraries.</li>
 
1731
 
 
1732
          <li>Exceptions are the only way for a constructor to fail.
 
1733
          We can simulate this with a factory function or an
 
1734
          <code>Init()</code> method, but these require heap
 
1735
          allocation or a new "invalid" state, respectively.</li>
 
1736
 
 
1737
          <li>Exceptions are really handy in testing frameworks.</li>
 
1738
        </ul>
 
1739
      </PROS>
 
1740
      <CONS>
 
1741
        <ul>
 
1742
          <li>When you add a <code>throw</code> statement to an existing
 
1743
          function, you must examine all of its transitive callers. Either
 
1744
          they must make at least the basic exception safety guarantee, or
 
1745
          they must never catch the exception and be happy with the
 
1746
          program terminating as a result. For instance, if
 
1747
          <code>f()</code> calls <code>g()</code> calls
 
1748
          <code>h()</code>, and <code>h</code> throws an exception
 
1749
          that <code>f</code> catches, <code>g</code> has to be
 
1750
          careful or it may not clean up properly.</li>
 
1751
 
 
1752
          <li>More generally, exceptions make the control flow of
 
1753
          programs difficult to evaluate by looking at code: functions
 
1754
          may return in places you don't expect. This causes
 
1755
          maintainability and debugging difficulties. You can minimize
 
1756
          this cost via some rules on how and where exceptions can be
 
1757
          used, but at the cost of more that a developer needs to know
 
1758
          and understand.</li>
 
1759
 
 
1760
          <li>Exception safety requires both RAII and different coding
 
1761
          practices. Lots of supporting machinery is needed to make
 
1762
          writing correct exception-safe code easy. Further, to avoid
 
1763
          requiring readers to understand the entire call graph,
 
1764
          exception-safe code must isolate logic that writes to
 
1765
          persistent state into a "commit" phase. This will have both
 
1766
          benefits and costs (perhaps where you're forced to obfuscate
 
1767
          code to isolate the commit). Allowing exceptions would force
 
1768
          us to always pay those costs even when they're not worth
 
1769
          it.</li>
 
1770
 
 
1771
          <li>Turning on exceptions adds data to each binary produced,
 
1772
          increasing compile time (probably slightly) and possibly
 
1773
          increasing address space pressure.
 
1774
          </li>
 
1775
 
 
1776
          <li>The availability of exceptions may encourage developers
 
1777
          to throw them when they are not appropriate or recover from
 
1778
          them when it's not safe to do so. For example, invalid user
 
1779
          input should not cause exceptions to be thrown. We would
 
1780
          need to make the style guide even longer to document these
 
1781
          restrictions!</li>
 
1782
        </ul>
 
1783
      </CONS>
 
1784
      <DECISION>
 
1785
        <p>
 
1786
          On their face, the benefits of using exceptions outweigh the
 
1787
          costs, especially in new projects.  However, for existing code,
 
1788
          the introduction of exceptions has implications on all dependent
 
1789
          code.  If exceptions can be propagated beyond a new project, it
 
1790
          also becomes problematic to integrate the new project into
 
1791
          existing exception-free code.  Because most existing C++ code at
 
1792
          Google is not prepared to deal with exceptions, it is
 
1793
          comparatively difficult to adopt new code that generates
 
1794
          exceptions.
 
1795
        </p>
 
1796
        <p>
 
1797
          Given that Google's existing code is not exception-tolerant, the
 
1798
          costs of using exceptions are somewhat greater than the costs in
 
1799
          a new project.  The conversion process would be slow and
 
1800
          error-prone.  We don't believe that the available alternatives to
 
1801
          exceptions, such as error codes and assertions, introduce a
 
1802
          significant burden.
 
1803
 
 
1804
        </p>
 
1805
        <p>
 
1806
          Our advice against using exceptions is not predicated on
 
1807
          philosophical or moral grounds, but practical ones.
 
1808
 
 
1809
          Because we'd like to use our open-source
 
1810
          projects at Google and it's difficult to do so if those projects
 
1811
          use exceptions, we need to advise against exceptions in Google
 
1812
          open-source projects as well.
 
1813
          Things would probably be different if we had to do it all over
 
1814
          again from scratch.
 
1815
        </p>
 
1816
        <p>
 
1817
          There is an <a HREF="#Windows_Code">exception</a> to this
 
1818
          rule (no pun intended) for Windows code.
 
1819
        </p>
 
1820
      </DECISION>
 
1821
    </BODY>
 
1822
  </STYLEPOINT>
 
1823
 
 
1824
  <STYLEPOINT title="Run-Time Type Information (RTTI)">
 
1825
    <SUMMARY>
 
1826
      We do not use Run Time Type Information (RTTI).
 
1827
    </SUMMARY>
 
1828
    <BODY>
 
1829
      <DEFINITION>
 
1830
        RTTI allows a programmer to query the C++ class of an
 
1831
        object at run time.
 
1832
      </DEFINITION>
 
1833
      <PROS>
 
1834
        <p>
 
1835
          It is useful in some unittests. For example, it is useful in
 
1836
          tests of factory classes where the test has to verify that a
 
1837
          newly created object has the expected dynamic type.
 
1838
        </p>
 
1839
        <p>
 
1840
          In rare circumstances, it is useful even outside of
 
1841
          tests.
 
1842
        </p>
 
1843
      </PROS>
 
1844
      <CONS>
 
1845
        A query of type during run-time typically means a
 
1846
        design problem.  If you need to know the type of an
 
1847
        object at runtime, that is often an indication that
 
1848
        you should reconsider the design of your class.
 
1849
      </CONS>
 
1850
      <DECISION>
 
1851
        <p>
 
1852
          Do not use RTTI, except in unittests.  If you find yourself
 
1853
          in need of writing code that behaves differently based on
 
1854
          the class of an object, consider one of the alternatives to
 
1855
          querying the type.
 
1856
        </p>
 
1857
        <p>
 
1858
          Virtual methods are the preferred way of executing different
 
1859
          code paths depending on a specific subclass type.  This puts
 
1860
          the work within the object itself.
 
1861
        </p>
 
1862
        <p>
 
1863
          If the work belongs outside the object and instead in some
 
1864
          processing code, consider a double-dispatch solution, such
 
1865
          as the Visitor design pattern.  This allows a facility
 
1866
          outside the object itself to determine the type of class
 
1867
          using the built-in type system.
 
1868
        </p>
 
1869
        <p>
 
1870
          If you think you truly cannot use those ideas,
 
1871
 
 
1872
          you may use RTTI.  But think twice
 
1873
          about it.  :-)  Then think twice again.
 
1874
          Do not hand-implement an RTTI-like workaround. The arguments
 
1875
          against RTTI apply just as much to workarounds like class
 
1876
          hierarchies with type tags.
 
1877
        </p>
 
1878
      </DECISION>
 
1879
    </BODY>
 
1880
  </STYLEPOINT>
 
1881
 
 
1882
  <STYLEPOINT title="Casting">
 
1883
    <SUMMARY>
 
1884
      Use C++ casts like <code>static_cast&lt;&gt;()</code>.  Do not use
 
1885
      other cast formats like <code>int y = (int)x;</code> or
 
1886
      <code>int y = int(x);</code>.
 
1887
    </SUMMARY>
 
1888
    <BODY>
 
1889
      <DEFINITION>
 
1890
        C++ introduced a different cast system from C that
 
1891
        distinguishes the types of cast operations.
 
1892
      </DEFINITION>
 
1893
      <PROS>
 
1894
        The problem with C casts is the ambiguity of the operation;
 
1895
        sometimes you are doing a <em>conversion</em> (e.g.,
 
1896
        <code>(int)3.5</code>) and sometimes you are doing a
 
1897
        <em>cast</em> (e.g., <code>(int)"hello"</code>); C++ casts
 
1898
        avoid this.  Additionally C++ casts are more visible when
 
1899
        searching for them.
 
1900
      </PROS>
 
1901
      <CONS>
 
1902
        The syntax is nasty.
 
1903
      </CONS>
 
1904
      <DECISION>
 
1905
        <p>
 
1906
          Do not use C-style casts.  Instead, use these C++-style
 
1907
          casts.
 
1908
 
 
1909
        </p>
 
1910
        <ul>
 
1911
 
 
1912
          <li> Use <code>static_cast</code> as the equivalent of a
 
1913
               C-style cast that does value conversion, or when you need to explicitly up-cast
 
1914
               a pointer from a class to its superclass.
 
1915
               </li>
 
1916
          <li> Use <code>const_cast</code> to remove the <code>const</code>
 
1917
               qualifier (see <a HREF="#Use_of_const">const</a>).
 
1918
               </li>
 
1919
 
 
1920
 
 
1921
          <li> Use <code>reinterpret_cast</code> to do unsafe
 
1922
               conversions of pointer types to and from integer and
 
1923
               other pointer types. Use this only if you know what you are
 
1924
               doing and you understand the aliasing issues.
 
1925
 
 
1926
               </li>
 
1927
          <li> Do not use <code>dynamic_cast</code> except in test code.
 
1928
               If you need to know type information at runtime in this way
 
1929
               outside of a unittest, you probably have a <A HREF="#Run-Time_Type_Information__RTTI_">design
 
1930
               flaw</A>.
 
1931
               </li>
 
1932
        </ul>
 
1933
      </DECISION>
 
1934
    </BODY>
 
1935
  </STYLEPOINT>
 
1936
 
 
1937
  <STYLEPOINT title="Streams">
 
1938
    <SUMMARY>
 
1939
      Use streams only for logging.
 
1940
    </SUMMARY>
 
1941
    <BODY>
 
1942
      <DEFINITION>
 
1943
        Streams are a replacement for <code>printf()</code> and
 
1944
        <code>scanf()</code>.
 
1945
      </DEFINITION>
 
1946
      <PROS>
 
1947
        With streams, you do not need to know the type of the object
 
1948
        you are printing.  You do not have problems with format
 
1949
        strings not matching the argument list.  (Though with gcc, you
 
1950
        do not have that problem with <code>printf</code> either.)  Streams
 
1951
        have automatic constructors and destructors that open and close the
 
1952
        relevant files.
 
1953
      </PROS>
 
1954
      <CONS>
 
1955
        Streams make it difficult to do functionality like
 
1956
        <code>pread()</code>.  Some formatting (particularly the common
 
1957
        format string idiom <code>%.*s</code>) is difficult if not
 
1958
        impossible to do efficiently using streams without using
 
1959
        <code>printf</code>-like hacks.  Streams do not support operator
 
1960
        reordering (the <code>%1s</code> directive), which is helpful for
 
1961
        internationalization.
 
1962
      </CONS>
 
1963
      <DECISION>
 
1964
 
 
1965
        <p>
 
1966
          Do not use streams, except where required by a logging interface.
 
1967
          Use <code>printf</code>-like routines instead.
 
1968
        </p>
 
1969
        <p>
 
1970
          There are various pros and cons to using streams, but in
 
1971
          this case, as in many other cases, consistency trumps the
 
1972
          debate.  Do not use streams in your code.
 
1973
        </p>
 
1974
 
 
1975
        <SUBSECTION title="Extended Discussion">
 
1976
          <p>
 
1977
            There has been debate on this issue, so this explains the
 
1978
            reasoning in greater depth.  Recall the Only One Way
 
1979
            guiding principle: we want to make sure that whenever we
 
1980
            do a certain type of I/O, the code looks the same in all
 
1981
            those places.  Because of this, we do not want to allow
 
1982
            users to decide between using streams or using
 
1983
            <code>printf</code> plus Read/Write/etc.  Instead, we should
 
1984
            settle on one or the other.  We made an exception for logging
 
1985
            because it is a pretty specialized application, and for
 
1986
            historical reasons.
 
1987
          </p>
 
1988
          <p>
 
1989
            Proponents of streams have argued that streams are the obvious
 
1990
            choice of the two, but the issue is not actually so clear.  For
 
1991
            every advantage of streams they point out, there is an
 
1992
            equivalent disadvantage.  The biggest advantage is that
 
1993
            you do not need to know the type of the object to be
 
1994
            printing.  This is a fair point.  But, there is a
 
1995
            downside: you can easily use the wrong type, and the
 
1996
            compiler will not warn you.  It is easy to make this
 
1997
            kind of mistake without knowing when using streams.
 
1998
          </p>
 
1999
          <CODE_SNIPPET>
 
2000
            cout &lt;&lt; this;  // Prints the address
 
2001
            cout &lt;&lt; *this;  // Prints the contents
 
2002
          </CODE_SNIPPET>
 
2003
          <p>
 
2004
            The compiler does not generate an error because
 
2005
            <code>&lt;&lt;</code> has been overloaded.  We discourage
 
2006
            overloading for just this reason.
 
2007
          </p>
 
2008
          <p>
 
2009
            Some say <code>printf</code> formatting is ugly and hard to
 
2010
            read, but streams are often no better.  Consider the following
 
2011
            two fragments, both with the same typo.  Which is easier to
 
2012
            discover?
 
2013
          </p>
 
2014
          <CODE_SNIPPET>
 
2015
             cerr &lt;&lt; "Error connecting to '" &lt;&lt; foo-&gt;bar()-&gt;hostname.first
 
2016
                  &lt;&lt; ":" &lt;&lt; foo-&gt;bar()-&gt;hostname.second &lt;&lt; ": " &lt;&lt; strerror(errno);
 
2017
 
 
2018
             fprintf(stderr, "Error connecting to '%s:%u: %s",
 
2019
                     foo-&gt;bar()-&gt;hostname.first, foo-&gt;bar()-&gt;hostname.second,
 
2020
                     strerror(errno));
 
2021
          </CODE_SNIPPET>
 
2022
          <p>
 
2023
            And so on and so forth for any issue you might bring up.
 
2024
            (You could argue, "Things would be better with the right
 
2025
            wrappers," but if it is true for one scheme, is it not
 
2026
            also true for the other?  Also, remember the goal is to
 
2027
            make the language smaller, not add yet more machinery that
 
2028
            someone has to learn.)
 
2029
          </p>
 
2030
          <p>
 
2031
            Either path would yield different advantages and
 
2032
            disadvantages, and there is not a clearly superior
 
2033
            solution.  The simplicity doctrine mandates we settle on
 
2034
            one of them though, and the majority decision was on
 
2035
            <code>printf</code> + <code>read</code>/<code>write</code>.
 
2036
          </p>
 
2037
        </SUBSECTION>
 
2038
      </DECISION>
 
2039
    </BODY>
 
2040
  </STYLEPOINT>
 
2041
 
 
2042
  <STYLEPOINT title="Preincrement and Predecrement">
 
2043
    <SUMMARY>
 
2044
      Use prefix form (<code>++i</code>) of the increment and
 
2045
      decrement operators with iterators and other template objects.
 
2046
    </SUMMARY>
 
2047
    <BODY>
 
2048
      <DEFINITION>
 
2049
        When a variable is incremented (<code>++i</code> or
 
2050
        <code>i++</code>) or decremented (<code>--i</code> or
 
2051
        <code>i--</code>) and the value of the expression is not used,
 
2052
        one must decide whether to preincrement (decrement) or
 
2053
        postincrement (decrement).
 
2054
      </DEFINITION>
 
2055
      <PROS>
 
2056
        When the return value is ignored, the "pre" form
 
2057
        (<code>++i</code>) is never less efficient than the "post"
 
2058
        form (<code>i++</code>), and is often more efficient.  This is
 
2059
        because post-increment (or decrement) requires a copy of
 
2060
        <code>i</code> to be made, which is the value of the
 
2061
        expression.  If <code>i</code> is an iterator or other
 
2062
        non-scalar type, copying <code>i</code> could be expensive.
 
2063
        Since the two types of increment behave the same when the
 
2064
        value is ignored, why not just always pre-increment?
 
2065
      </PROS>
 
2066
      <CONS>
 
2067
        The tradition developed, in C, of using post-increment when
 
2068
        the expression value is not used, especially in <code>for</code>
 
2069
        loops.  Some find post-increment easier to read, since the
 
2070
        "subject" (<code>i</code>) precedes the "verb" (<code>++</code>),
 
2071
        just like in English.
 
2072
      </CONS>
 
2073
      <DECISION>
 
2074
        For simple scalar (non-object) values there is no reason to
 
2075
        prefer one form and we allow either.  For iterators and other
 
2076
        template types, use pre-increment.
 
2077
      </DECISION>
 
2078
    </BODY>
 
2079
  </STYLEPOINT>
 
2080
 
 
2081
  <STYLEPOINT title="Use of const">
 
2082
    <SUMMARY>
 
2083
      We strongly recommend that you use <code>const</code> whenever
 
2084
      it makes sense to do so.
 
2085
    </SUMMARY>
 
2086
    <BODY>
 
2087
      <DEFINITION>
 
2088
        Declared variables and parameters can be preceded by the
 
2089
        keyword <code>const</code> to indicate the variables are not
 
2090
        changed (e.g., <code>const int foo</code>).  Class functions
 
2091
        can have the <code>const</code> qualifier to indicate the
 
2092
        function does not change the state of the class member
 
2093
        variables (e.g., <code>class Foo { int Bar(char c) const;
 
2094
        };</code>).
 
2095
      </DEFINITION>
 
2096
      <PROS>
 
2097
        Easier for people to understand how variables are being used.
 
2098
        Allows the compiler to do better type checking, and,
 
2099
        conceivably, generate better code.  Helps people convince
 
2100
        themselves of program correctness because they know the
 
2101
        functions they call are limited in how they can modify your
 
2102
        variables.  Helps people know what functions are safe to use
 
2103
        without locks in multi-threaded programs.
 
2104
      </PROS>
 
2105
      <CONS>
 
2106
        <code>const</code> is viral: if you pass a <code>const</code>
 
2107
        variable to a function, that function must have <code>const</code>
 
2108
        in its prototype (or the variable will need a
 
2109
        <code>const_cast</code>).  This can be a particular problem
 
2110
        when calling library functions.
 
2111
      </CONS>
 
2112
      <DECISION>
 
2113
        <p>
 
2114
          <code>const</code> variables, data members, methods and
 
2115
          arguments add a level of compile-time type checking; it
 
2116
          is better to detect errors as soon as possible.
 
2117
          Therefore we strongly recommend that you use
 
2118
          <code>const</code> whenever it makes sense to do so:
 
2119
        </p>
 
2120
        <ul>
 
2121
          <li> If a function does not modify an argument passed by
 
2122
               reference or by pointer, that argument should be
 
2123
               <code>const</code>.
 
2124
               </li>
 
2125
          <li> Declare methods to be <code>const</code> whenever
 
2126
               possible. Accessors should almost always be
 
2127
               <code>const</code>. Other methods should be const if they do
 
2128
               not modify any data members, do not call any
 
2129
               non-<code>const</code> methods, and do not return a
 
2130
               non-<code>const</code> pointer or non-<code>const</code>
 
2131
               reference to a data member.
 
2132
               </li>
 
2133
          <li> Consider making data members <code>const</code>
 
2134
               whenever they do not need to be modified after
 
2135
               construction.
 
2136
               </li>
 
2137
        </ul>
 
2138
        <p>
 
2139
          However, do not go crazy with <code>const</code>.  Something like
 
2140
          <code>const int * const * const x;</code> is likely
 
2141
          overkill, even if it accurately describes how const x is.
 
2142
          Focus on what's really useful to know: in this case,
 
2143
          <code>const int** x</code> is probably sufficient.
 
2144
        </p>
 
2145
        <p>
 
2146
          The <code>mutable</code> keyword is allowed but is unsafe
 
2147
          when used with threads, so thread safety should be carefully
 
2148
          considered first.
 
2149
        </p>
 
2150
      </DECISION>
 
2151
      <SUBSECTION title="Where to put the const">
 
2152
        <p>
 
2153
          Some people favor the form <code>int const *foo</code> to
 
2154
          <code>const int* foo</code>.  They argue that this is more
 
2155
          readable because it's more consistent: it keeps the rule
 
2156
          that <code>const</code> always follows the object it's
 
2157
          describing.  However, this consistency argument doesn't
 
2158
          apply in this case, because the "don't go crazy" dictum
 
2159
          eliminates most of the uses you'd have to be consistent with.
 
2160
 
 
2161
          Putting the <code>const</code> first is arguably more readable,
 
2162
          since it follows English in putting the "adjective"
 
2163
          (<code>const</code>) before the "noun" (<code>int</code>).
 
2164
        </p>
 
2165
        <p>
 
2166
          That said, while we encourage putting <code>const</code> first,
 
2167
          we do not require it.  But be consistent with the code around
 
2168
          you!
 
2169
        </p>
 
2170
      </SUBSECTION>
 
2171
    </BODY>
 
2172
  </STYLEPOINT>
 
2173
 
 
2174
  <STYLEPOINT title="Integer Types">
 
2175
    <SUMMARY>
 
2176
      Of the built-in C++ integer types, the only one used
 
2177
 
 
2178
      is <code>int</code>.  If a program needs a variable of a different
 
2179
      size, use
 
2180
 
 
2181
      a precise-width integer type from
 
2182
      <code>&lt;stdint.h&gt;</code>, such as <code>int16_t</code>.
 
2183
    </SUMMARY>
 
2184
    <BODY>
 
2185
      <DEFINITION>
 
2186
        C++ does not specify the sizes of its integer types. Typically
 
2187
        people assume that <code>short</code> is 16 bits,
 
2188
        <code>int</code> is 32 bits, <code>long</code> is 32 bits and
 
2189
        <code>long long</code> is 64 bits.
 
2190
      </DEFINITION>
 
2191
      <PROS>
 
2192
        Uniformity of declaration.
 
2193
      </PROS>
 
2194
      <CONS>
 
2195
        The sizes of integral types in C++ can vary based on compiler
 
2196
        and architecture.
 
2197
      </CONS>
 
2198
      <DECISION>
 
2199
        <p>
 
2200
 
 
2201
          <code>&lt;stdint.h&gt;</code> defines
 
2202
          types like <code>int16_t</code>, <code>uint32_t</code>,
 
2203
          <code>int64_t</code>, etc.
 
2204
          You should always use those in preference to
 
2205
          <code>short</code>, <code>unsigned long long</code> and the
 
2206
          like, when you need a guarantee on the size of an integer.
 
2207
          Of the C integer types, only <code>int</code> should be
 
2208
          used.  When appropriate, you are welcome to use standard
 
2209
          types like <code>size_t</code> and <code>ptrdiff_t</code>.
 
2210
        </p>
 
2211
        <p>
 
2212
          We use <code>int</code> very often, for integers we know are not
 
2213
          going to be too big, e.g., loop counters. Use plain old
 
2214
          <code>int</code> for such things. You should assume that an
 
2215
          <code>int</code> is
 
2216
 
 
2217
          at least 32 bits,
 
2218
          but don't assume that it has more than 32 bits.
 
2219
          If you need a 64-bit integer type, use
 
2220
          <code>int64_t</code> or
 
2221
          <code>uint64_t</code>.
 
2222
        </p>
 
2223
        <p>
 
2224
          For integers we know can be "big",
 
2225
           use
 
2226
          <code>int64_t</code>.
 
2227
 
 
2228
        </p>
 
2229
        <p>
 
2230
          You should not use the unsigned integer types such as
 
2231
          <code>uint32_t</code>,
 
2232
          unless the quantity you are representing is really a bit pattern
 
2233
          rather than a number, or unless you need defined
 
2234
          twos-complement overflow. In particular, do not use unsigned
 
2235
          types to say a number will never be negative.  Instead, use
 
2236
 
 
2237
          assertions for this.
 
2238
        </p>
 
2239
 
 
2240
      </DECISION>
 
2241
 
 
2242
      <SUBSECTION title="On Unsigned Integers">
 
2243
        <p>
 
2244
          Some people, including some textbook authors, recommend
 
2245
          using unsigned types to represent numbers that are never
 
2246
          negative.  This is intended as a form of self-documentation.
 
2247
          However, in C, the advantages of such documentation are
 
2248
          outweighed by the real bugs it can introduce.  Consider:
 
2249
        </p>
 
2250
        <CODE_SNIPPET>
 
2251
          for (unsigned int i = foo.Length()-1; i &gt;= 0; --i) ...
 
2252
        </CODE_SNIPPET>
 
2253
        <p>
 
2254
          This code will never terminate!  Sometimes gcc will notice
 
2255
          this bug and warn you, but often it will not.  Equally bad
 
2256
          bugs can occur when comparing signed and unsigned
 
2257
          variables.  Basically, C's type-promotion scheme causes
 
2258
          unsigned types to behave differently than one might expect.
 
2259
        </p>
 
2260
        <p>
 
2261
          So, document that a variable is non-negative using
 
2262
          assertions.
 
2263
          Don't use an unsigned type.
 
2264
        </p>
 
2265
      </SUBSECTION>
 
2266
    </BODY>
 
2267
  </STYLEPOINT>
 
2268
 
 
2269
  <STYLEPOINT title="64-bit Portability">
 
2270
    <SUMMARY>
 
2271
      Code should be 64-bit and 32-bit friendly.  Bear in mind problems of
 
2272
      printing, comparisons, and structure alignment.
 
2273
    </SUMMARY>
 
2274
    <BODY>
 
2275
      <ul>
 
2276
        <li>
 
2277
          <p>
 
2278
            <code>printf()</code> specifiers for some types are
 
2279
            not cleanly portable between 32-bit and 64-bit
 
2280
            systems. C99 defines some portable format
 
2281
            specifiers. Unfortunately, MSVC 7.1 does not
 
2282
            understand some of these specifiers and the
 
2283
            standard is missing a few, so we have to define our
 
2284
            own ugly versions in some cases (in the style of the
 
2285
            standard include file <code>inttypes.h</code>):
 
2286
          </p>
 
2287
          <CODE_SNIPPET>
 
2288
            // printf macros for size_t, in the style of inttypes.h
 
2289
            #ifdef _LP64
 
2290
            #define __PRIS_PREFIX "z"
 
2291
            #else
 
2292
            #define __PRIS_PREFIX
 
2293
            #endif
 
2294
 
 
2295
            // Use these macros after a % in a printf format string
 
2296
            // to get correct 32/64 bit behavior, like this:
 
2297
            // size_t size = records.size();
 
2298
            // printf("%"PRIuS"\n", size);
 
2299
 
 
2300
            #define PRIdS __PRIS_PREFIX "d"
 
2301
            #define PRIxS __PRIS_PREFIX "x"
 
2302
            #define PRIuS __PRIS_PREFIX "u"
 
2303
            #define PRIXS __PRIS_PREFIX "X"
 
2304
            #define PRIoS __PRIS_PREFIX "o"
 
2305
          </CODE_SNIPPET>
 
2306
          <table border="1" summary="portable printf specifiers">
 
2307
            <TBODY>
 
2308
              <tr align="center">
 
2309
                <th>Type</th>
 
2310
                <th>DO NOT use</th>
 
2311
                <th>DO use</th>
 
2312
                <th>Notes</th>
 
2313
              </tr>
 
2314
              <tr align="center">
 
2315
                <td><code>void *</code> (or any pointer)</td>
 
2316
                <td><code>%lx</code></td>
 
2317
                <td><code>%p</code></td>
 
2318
                <td> </td>
 
2319
              </tr>
 
2320
 
 
2321
              <tr align="center">
 
2322
                <td><code>int64_t</code></td>
 
2323
                <td><code>%qd</code>,
 
2324
                     <code>%lld</code></td>
 
2325
                <td><code>%"PRId64"</code></td>
 
2326
                <td/>
 
2327
              </tr>
 
2328
 
 
2329
              <tr align="center">
 
2330
                <td><code>uint64_t</code></td>
 
2331
                <td><code>%qu</code>,
 
2332
                    <code>%llu</code>,
 
2333
                    <code>%llx</code></td>
 
2334
                <td><code>%"PRIu64"</code>,
 
2335
                    <code>%"PRIx64"</code></td>
 
2336
                <td/>
 
2337
              </tr>
 
2338
 
 
2339
              <tr align="center">
 
2340
                <td><code>size_t</code></td>
 
2341
                <td><code>%u</code></td>
 
2342
                <td><code>%"PRIuS"</code>,
 
2343
                    <code>%"PRIxS"</code></td>
 
2344
                <td>C99 specifies <code>%zu</code></td>
 
2345
              </tr>
 
2346
              <tr align="center">
 
2347
                <td><code>ptrdiff_t</code></td>
 
2348
                <td><code>%d</code></td>
 
2349
                <td><code>%"PRIdS"</code></td>
 
2350
                <td>C99 specifies <code>%zd</code></td>
 
2351
              </tr>
 
2352
 
 
2353
            </TBODY>
 
2354
          </table>
 
2355
          <p>
 
2356
            Note that the <code>PRI*</code> macros expand to independent
 
2357
            strings which are concatenated by the compiler. Hence
 
2358
            if you are using a non-constant format string, you
 
2359
            need to insert the value of the macro into the format,
 
2360
            rather than the name. It is still possible, as usual,
 
2361
            to include length specifiers, etc., after the
 
2362
            <code>%</code> when using the <code>PRI*</code>
 
2363
            macros. So, e.g.  <code>printf("x = %30"PRIuS"\n",
 
2364
            x)</code> would expand on 32-bit Linux to
 
2365
            <code>printf("x = %30" "u" "\n", x)</code>, which the
 
2366
            compiler will treat as <code>printf("x = %30u\n",
 
2367
            x)</code>.
 
2368
          </p>
 
2369
 
 
2370
          </li>
 
2371
 
 
2372
        <li> Remember that <code>sizeof(void *)</code> !=
 
2373
             <code>sizeof(int)</code>.  Use <code>intptr_t</code> if
 
2374
             you want a pointer-sized integer.
 
2375
             </li>
 
2376
 
 
2377
        <li> You may need to be careful with structure alignments,
 
2378
             particularly for structures being stored on disk. Any
 
2379
             class/structure with a
 
2380
 
 
2381
             <code>int64_t</code>/<code>uint64_t</code>
 
2382
             member will by default end up being 8-byte aligned on a 64-bit
 
2383
             system. If you have such structures being shared on disk
 
2384
             between 32-bit and 64-bit code, you will need to ensure
 
2385
             that they are packed the same on both architectures.
 
2386
 
 
2387
             Most compilers offer a way to alter
 
2388
             structure alignment.  For gcc, you can use
 
2389
             <code>__attribute__((packed))</code>.  MSVC offers
 
2390
             <code>#pragma pack()</code> and
 
2391
             <code>__declspec(align())</code>.
 
2392
             </li>
 
2393
 
 
2394
        <li>
 
2395
 
 
2396
             Use the <code>LL</code> or <code>ULL</code> suffixes as
 
2397
             needed to create 64-bit constants.  For example:
 
2398
 
 
2399
             <CODE_SNIPPET>
 
2400
             int64_t my_value = 0x123456789LL;
 
2401
             uint64_t my_mask = 3ULL &lt;&lt; 48;
 
2402
             </CODE_SNIPPET>
 
2403
             </li>
 
2404
 
 
2405
        <li> If you really need different code on 32-bit and 64-bit
 
2406
             systems, use <code>#ifdef _LP64</code> to choose between
 
2407
             the code variants. (But please avoid this if
 
2408
             possible, and keep any such changes localized.)
 
2409
             </li>
 
2410
      </ul>
 
2411
    </BODY>
 
2412
  </STYLEPOINT>
 
2413
 
 
2414
  <STYLEPOINT title="Preprocessor Macros">
 
2415
    <SUMMARY>
 
2416
      Be very cautious with macros.  Prefer inline functions, enums,
 
2417
      and <code>const</code> variables to macros.
 
2418
    </SUMMARY>
 
2419
    <BODY>
 
2420
      <p>
 
2421
        Macros mean that the code you see is not the same as the code
 
2422
        the compiler sees.  This can introduce unexpected behavior,
 
2423
        especially since macros have global scope.
 
2424
      </p>
 
2425
      <p>
 
2426
        Luckily, macros are not nearly as necessary in C++ as they are
 
2427
        in C.  Instead of using a macro to inline performance-critical
 
2428
        code, use an inline function.  Instead of using a macro to
 
2429
        store a constant, use a <code>const</code> variable.  Instead of
 
2430
        using a macro to "abbreviate" a long variable name, use a
 
2431
        reference.  Instead of using a macro to conditionally compile code
 
2432
        ... well, don't do that at all (except, of course, for the
 
2433
        <code>#define</code> guards to prevent double inclusion of
 
2434
        header files).  It makes testing much more difficult.
 
2435
      </p>
 
2436
      <p>
 
2437
        Macros can do things these other techniques cannot, and you do
 
2438
        see them in the codebase, especially in the lower-level
 
2439
        libraries.  And some of their special features (like
 
2440
        stringifying, concatenation, and so forth) are not available
 
2441
        through the language proper.  But before using a macro,
 
2442
        consider carefully whether there's a non-macro way to achieve
 
2443
        the same result.
 
2444
      </p>
 
2445
      <p>
 
2446
        The following usage pattern will avoid many problems with
 
2447
        macros; if you use macros, follow it whenever possible:
 
2448
      </p>
 
2449
      <ul>
 
2450
        <li> Don't define macros in a <code>.h</code> file.
 
2451
             </li>
 
2452
        <li> <code>#define</code> macros right before you use them,
 
2453
             and <code>#undef</code> them right after.
 
2454
             </li>
 
2455
        <li> Do not just <code>#undef</code> an existing macro before
 
2456
             replacing it with your own; instead, pick a name that's
 
2457
             likely to be unique.
 
2458
             </li>
 
2459
        <li> Try not to use macros that expand to unbalanced C++
 
2460
             constructs, or at least document that behavior well.
 
2461
             </li>
 
2462
        <li> Prefer not using <code>##</code> to generate function/class/variable
 
2463
             names.
 
2464
             </li>
 
2465
      </ul>
 
2466
    </BODY>
 
2467
  </STYLEPOINT>
 
2468
 
 
2469
  <STYLEPOINT title="0 and NULL">
 
2470
  <SUMMARY>
 
2471
    Use <code>0</code> for integers, <code>0.0</code> for reals,
 
2472
    <code>NULL</code> for pointers, and <code>'\0'</code> for chars.
 
2473
  </SUMMARY>
 
2474
  <BODY>
 
2475
    <p>
 
2476
      Use <code>0</code> for integers and <code>0.0</code> for reals.
 
2477
      This is not controversial.
 
2478
    </p>
 
2479
    <p>
 
2480
      For pointers (address values), there is a choice between <code>0</code>
 
2481
      and <code>NULL</code>.  Bjarne Stroustrup prefers an unadorned
 
2482
      <code>0</code>.  We prefer <code>NULL</code> because it looks like a
 
2483
      pointer.  In fact, some C++ compilers, such as gcc 4.1.0, provide special
 
2484
      definitions of <code>NULL</code> which enable them to give useful
 
2485
      warnings, particularly in situations where <code>sizeof(NULL)</code>
 
2486
      is not equal to <code>sizeof(0)</code>.
 
2487
    </p>
 
2488
    <p>
 
2489
      Use <code>'\0'</code> for chars.
 
2490
      This is the correct type and also makes code more readable.
 
2491
    </p>
 
2492
  </BODY>
 
2493
  </STYLEPOINT>
 
2494
 
 
2495
  <STYLEPOINT title="sizeof">
 
2496
  <SUMMARY>
 
2497
    Use <code>sizeof(<var>varname</var>)</code> instead of
 
2498
    <code>sizeof(<var>type</var>)</code> whenever possible.
 
2499
  </SUMMARY>
 
2500
  <BODY>
 
2501
    <p>
 
2502
      Use <code>sizeof(<var>varname</var>)</code> because it will update
 
2503
      appropriately if the type of the variable changes.
 
2504
      <code>sizeof(<var>type</var>)</code> may make sense in some cases,
 
2505
      but should generally be avoided because it can fall out of sync if
 
2506
      the variable's type changes.
 
2507
    </p>
 
2508
    <p>
 
2509
      <CODE_SNIPPET>
 
2510
        Struct data;
 
2511
        memset(&amp;data, 0, sizeof(data));
 
2512
      </CODE_SNIPPET>
 
2513
      <BAD_CODE_SNIPPET>
 
2514
        memset(&amp;data, 0, sizeof(Struct));
 
2515
      </BAD_CODE_SNIPPET>
 
2516
    </p>
 
2517
  </BODY>
 
2518
  </STYLEPOINT>
 
2519
 
 
2520
  <STYLEPOINT title="Boost">
 
2521
  <SUMMARY>
 
2522
    Use only approved libraries from the Boost library collection.
 
2523
  </SUMMARY>
 
2524
  <BODY>
 
2525
    <DEFINITION>
 
2526
      The <a href="http://www.boost.org/">Boost library collection</a> is
 
2527
      a popular collection of peer-reviewed, free, open-source C++ libraries.
 
2528
    </DEFINITION>
 
2529
    <PROS>
 
2530
      Boost code is generally very high-quality, is widely portable, and fills
 
2531
      many important gaps in the C++ standard library, such as type traits,
 
2532
      better binders, and better smart pointers. It also provides an
 
2533
      implementation of the TR1 extension to the standard library.
 
2534
    </PROS>
 
2535
    <CONS>
 
2536
      Some Boost libraries encourage coding practices which can hamper
 
2537
      readability, such as metaprogramming and other advanced template
 
2538
      techniques, and an excessively "functional" style of programming.
 
2539
 
 
2540
    </CONS>
 
2541
    <DECISION>
 
2542
 
 
2543
      <div>
 
2544
 
 
2545
        In order to maintain a high level of readability for all contributors
 
2546
        who might read and maintain code, we only allow an approved subset of
 
2547
        Boost features.  Currently, the following libraries are permitted:
 
2548
        <ul>
 
2549
          <li> <a href="http://www.boost.org/libs/utility/call_traits.htm">
 
2550
               Call Traits</a> from <code>boost/call_traits.hpp</code>
 
2551
               </li>
 
2552
          <li> <a href="http://www.boost.org/libs/utility/compressed_pair.htm">
 
2553
               Compressed Pair</a> from <code>boost/compressed_pair.hpp</code>
 
2554
               </li>
 
2555
          <li> <a href="http://www.boost.org/libs/ptr_container/">
 
2556
               Pointer Container</a> from <code>boost/ptr_container</code> except
 
2557
               serialization and wrappers for containers not in the C++03
 
2558
               standard (<code>ptr_circular_buffer.hpp</code> and
 
2559
               <code>ptr_unordered*</code>)
 
2560
               </li>
 
2561
          <li> <a href="http://www.boost.org/libs/array/">
 
2562
               Array</a> from <code>boost/array.hpp</code>
 
2563
               </li>
 
2564
          <li> <a href="http://www.boost.org/libs/graph/">
 
2565
               The Boost Graph Library (BGL)</a> from <code>boost/graph</code>,
 
2566
               except serialization (<code>adj_list_serialize.hpp</code>) and
 
2567
               parallel/distributed algorithms and data structures
 
2568
               (<code>boost/graph/parallel/*</code> and
 
2569
               <code>boost/graph/distributed/*</code>).
 
2570
               </li>
 
2571
          <li> <a href="http://www.boost.org/libs/property_map/">
 
2572
               Property Map</a> from <code>boost/property_map</code>, except
 
2573
               parallel/distributed property maps
 
2574
               (<code>boost/property_map/parallel/*</code>).
 
2575
               </li>
 
2576
          <li> The part of
 
2577
               <a href="http://www.boost.org/libs/iterator/">
 
2578
               Iterator</a> that deals with defining iterators:
 
2579
               <code>boost/iterator/iterator_adaptor.hpp</code>,
 
2580
               <code>boost/iterator/iterator_facade.hpp</code>, and
 
2581
               <code>boost/function_output_iterator.hpp</code></li>
 
2582
        </ul>
 
2583
        We are actively considering adding other Boost features to the list, so
 
2584
        this rule may be relaxed in the future.
 
2585
      </div>
 
2586
    </DECISION>
 
2587
  </BODY>
 
2588
  </STYLEPOINT>
 
2589
 
 
2590
  <STYLEPOINT title="C++0x">
 
2591
  <SUMMARY>
 
2592
    Use only approved libraries and language extensions from C++0x.
 
2593
    Currently, none are approved.
 
2594
  </SUMMARY>
 
2595
  <BODY>
 
2596
    <DEFINITION>
 
2597
      C++0x is the next ISO C++ standard, currently in
 
2598
      <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf">final
 
2599
      committee draft</a> form.  It contains
 
2600
      <a href="http://en.wikipedia.org/wiki/C%2B%2B0x">significant
 
2601
      changes</a> both to the language and libraries.
 
2602
    </DEFINITION>
 
2603
    <PROS>
 
2604
      We expect that C++0x will become the next standard, and eventually will
 
2605
      be supported by most C++ compilers.  It standardizes some common C++
 
2606
      extensions that we use already, allows shorthands for some operations,
 
2607
      and has some safety improvements.
 
2608
    </PROS>
 
2609
    <CONS>
 
2610
      <p>
 
2611
        The C++0x standard is substantialy more complex than its predecessor
 
2612
        (1,300 pages versus 800 pages), and is
 
2613
        unfamilar to many developers.  The long-term effects of some
 
2614
        features on code readability and maintenance are unknown.  We cannot
 
2615
        predict when its various features will be implemented uniformly by
 
2616
        tools that may be of interest (gcc, icc, clang, Eclipse, etc.).
 
2617
      </p>
 
2618
      <p>
 
2619
        As with <a href="#Boost">Boost</a>, some C++0x extensions encourage
 
2620
        coding practices that hamper readability&#8212;for example by removing
 
2621
        checked redundancy (such as type names) that may be helpful to readers,
 
2622
        or by encouraging template metaprogramming.  Other extensions
 
2623
        duplicate functionality available through existing
 
2624
        mechanisms, which may lead to
 
2625
        confusion and conversion costs.
 
2626
      </p>
 
2627
    </CONS>
 
2628
    <DECISION>
 
2629
      Use only C++0x libraries and language features that have been approved
 
2630
      for use.  Currently, no such features are approved.
 
2631
      Features will be approved individually as appropriate.
 
2632
    </DECISION>
 
2633
  </BODY>
 
2634
  </STYLEPOINT>
 
2635
 
 
2636
</CATEGORY>
 
2637
 
 
2638
<CATEGORY title="Naming">
 
2639
  <p>
 
2640
    The most important consistency rules are those that govern
 
2641
    naming. The style of a name immediately informs us what sort of
 
2642
    thing the named entity is: a type, a variable, a function, a
 
2643
    constant, a macro, etc., without requiring us to search for the
 
2644
    declaration of that entity. The pattern-matching engine in our
 
2645
    brains relies a great deal on these naming rules.
 
2646
 
 
2647
  </p>
 
2648
  <p>
 
2649
    Naming rules are pretty arbitrary, but
 
2650
 
 
2651
    we feel that consistency is more important than individual preferences
 
2652
    in this area, so regardless of whether you find them sensible or not,
 
2653
    the rules are the rules.
 
2654
  </p>
 
2655
 
 
2656
  <STYLEPOINT title="General Naming Rules">
 
2657
    <SUMMARY>
 
2658
      Function names, variable names, and filenames should be
 
2659
      descriptive; eschew abbreviation.  Types and variables should be
 
2660
      nouns, while functions should be "command" verbs.
 
2661
    </SUMMARY>
 
2662
    <BODY>
 
2663
      <SUBSECTION title="How to Name">
 
2664
        <p>
 
2665
          Give as descriptive a name as possible, within reason. Do
 
2666
          not worry about saving horizontal space as it is far more
 
2667
          important to make your code immediately understandable by a
 
2668
          new reader. Examples of well-chosen names:
 
2669
        </p>
 
2670
        <CODE_SNIPPET>
 
2671
          int num_errors;                  // Good.
 
2672
          int num_completed_connections;   // Good.
 
2673
        </CODE_SNIPPET>
 
2674
        <p>
 
2675
          Poorly-chosen names use ambiguous abbreviations or arbitrary
 
2676
          characters that do not convey meaning:
 
2677
        </p>
 
2678
        <BAD_CODE_SNIPPET>
 
2679
          int n;                           // Bad - meaningless.
 
2680
          int nerr;                        // Bad - ambiguous abbreviation.
 
2681
          int n_comp_conns;                // Bad - ambiguous abbreviation.
 
2682
        </BAD_CODE_SNIPPET>
 
2683
        <p>
 
2684
          Type and variable names should typically be nouns: e.g.,
 
2685
          <code>FileOpener</code>,
 
2686
 
 
2687
          <code>num_errors</code>.
 
2688
        </p>
 
2689
        <p>
 
2690
          Function names should typically be imperative (that is they
 
2691
          should be commands): e.g., <code>OpenFile()</code>,
 
2692
          <code>set_num_errors()</code>.  There is an exception for
 
2693
          accessors, which, described more completely in <a HREF="#Function_Names">Function Names</a>, should be named
 
2694
          the same as the variable they access.
 
2695
        </p>
 
2696
      </SUBSECTION>
 
2697
 
 
2698
      <SUBSECTION title="Abbreviations">
 
2699
        <p>
 
2700
          Do not use abbreviations unless they are extremely well
 
2701
          known outside your project. For example:
 
2702
        </p>
 
2703
        <CODE_SNIPPET>
 
2704
          // Good
 
2705
          // These show proper names with no abbreviations.
 
2706
          int num_dns_connections;  // Most people know what "DNS" stands for.
 
2707
          int price_count_reader;   // OK, price count. Makes sense.
 
2708
        </CODE_SNIPPET>
 
2709
        <BAD_CODE_SNIPPET>
 
2710
          // Bad!
 
2711
          // Abbreviations can be confusing or ambiguous outside a small group.
 
2712
          int wgc_connections;  // Only your group knows what this stands for.
 
2713
          int pc_reader;        // Lots of things can be abbreviated "pc".
 
2714
        </BAD_CODE_SNIPPET>
 
2715
        <p>
 
2716
          Never abbreviate by leaving out letters:
 
2717
        </p>
 
2718
        <CODE_SNIPPET>
 
2719
          int error_count;  // Good.
 
2720
        </CODE_SNIPPET>
 
2721
        <BAD_CODE_SNIPPET>
 
2722
          int error_cnt;    // Bad.
 
2723
        </BAD_CODE_SNIPPET>
 
2724
      </SUBSECTION>
 
2725
    </BODY>
 
2726
  </STYLEPOINT>
 
2727
 
 
2728
  <STYLEPOINT title="File Names">
 
2729
    <SUMMARY>
 
2730
      Filenames should be all lowercase and can include underscores
 
2731
      (<code>_</code>) or dashes (<code>-</code>).  Follow the
 
2732
      convention that your
 
2733
 
 
2734
      project
 
2735
      uses. If there is no consistent local pattern to follow, prefer "_".
 
2736
    </SUMMARY>
 
2737
    <BODY>
 
2738
      <p>
 
2739
        Examples of acceptable file names:
 
2740
      </p>
 
2741
      <p>
 
2742
        <code>
 
2743
          my_useful_class.cpp<br/>
 
2744
          my-useful-class.cpp<br/>
 
2745
          myusefulclass.cpp<br/>
 
2746
          myusefulclass_test.cpp  // _unittest and _regtest are deprecated.<br/>
 
2747
        </code>
 
2748
      </p>
 
2749
      <p>
 
2750
        C++ files should end in <code>.cpp</code> and header files
 
2751
        should end in <code>.h</code>.
 
2752
      </p>
 
2753
      <p>
 
2754
        Do not use filenames that already exist
 
2755
        in <code>/usr/include</code>, such as <code>db.h</code>.
 
2756
      </p>
 
2757
      <p>
 
2758
        In general, make your filenames very specific.  For example,
 
2759
        use <code>http_server_logs.h</code> rather
 
2760
        than <code>logs.h</code>.  A very common case is to have a
 
2761
        pair of files called, e.g., <code>foo_bar.h</code>
 
2762
        and <code>foo_bar.cpp</code>, defining a class
 
2763
        called <code>FooBar</code>.
 
2764
      </p>
 
2765
      <p>
 
2766
        Inline functions must be in a <code>.h</code> file. If your
 
2767
        inline functions are very short, they should go directly into your
 
2768
        <code>.h</code> file. However, if your inline functions
 
2769
        include a lot of code, they may go into a third file that
 
2770
        ends in <code>-inl.h</code>.  In a class with a lot of inline
 
2771
        code, your class could have three files:
 
2772
      </p>
 
2773
      <CODE_SNIPPET>
 
2774
        url_table.h      // The class declaration.
 
2775
        url_table.cpp     // The class definition.
 
2776
        url_table-inl.h  // Inline functions that include lots of code.
 
2777
      </CODE_SNIPPET>
 
2778
      <p>
 
2779
        See also the section <a href="#The_-inl.h_Files">-inl.h Files</a>
 
2780
      </p>
 
2781
    </BODY>
 
2782
  </STYLEPOINT>
 
2783
 
 
2784
  <STYLEPOINT title="Type Names">
 
2785
    <SUMMARY>
 
2786
      Type names start with a capital letter and have a capital
 
2787
      letter for each new word, with no underscores:
 
2788
      <code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.
 
2789
    </SUMMARY>
 
2790
    <BODY>
 
2791
      <p>
 
2792
        The names of all types &#8212; classes, structs, typedefs, and enums
 
2793
        &#8212; have the same naming convention.  Type names should start
 
2794
        with a capital letter and have a capital letter for each new
 
2795
        word.  No underscores.  For example:
 
2796
      </p>
 
2797
      <CODE_SNIPPET>
 
2798
        // classes and structs
 
2799
        class UrlTable { ...
 
2800
        class UrlTableTester { ...
 
2801
        struct UrlTableProperties { ...
 
2802
 
 
2803
        // typedefs
 
2804
        typedef hash_map&lt;UrlTableProperties *, string&gt; PropertiesMap;
 
2805
 
 
2806
        // enums
 
2807
        enum UrlTableErrors { ...
 
2808
      </CODE_SNIPPET>
 
2809
    </BODY>
 
2810
  </STYLEPOINT>
 
2811
 
 
2812
  <STYLEPOINT title="Variable Names">
 
2813
    <SUMMARY>
 
2814
      Variable names are all lowercase, with underscores between
 
2815
      words.  Class member variables have trailing underscores.  For
 
2816
      instance: <code>my_exciting_local_variable</code>,
 
2817
      <code>my_exciting_member_variable_</code>.
 
2818
    </SUMMARY>
 
2819
    <BODY>
 
2820
      <SUBSECTION title="Common Variable names">
 
2821
        <p>
 
2822
          For example:
 
2823
        </p>
 
2824
        <CODE_SNIPPET>
 
2825
          string table_name;  // OK - uses underscore.
 
2826
          string tablename;   // OK - all lowercase.
 
2827
        </CODE_SNIPPET>
 
2828
        <BAD_CODE_SNIPPET>
 
2829
          string tableName;   // Bad - mixed case.
 
2830
        </BAD_CODE_SNIPPET>
 
2831
      </SUBSECTION>
 
2832
 
 
2833
      <SUBSECTION title="Class Data Members">
 
2834
        <p>
 
2835
          Data members (also called instance variables or member
 
2836
          variables) are lowercase with optional underscores like
 
2837
          regular variable names, but always end with a trailing
 
2838
          underscore.
 
2839
        </p>
 
2840
        <CODE_SNIPPET>
 
2841
          string table_name_;  // OK - underscore at end.
 
2842
          string tablename_;   // OK.
 
2843
        </CODE_SNIPPET>
 
2844
      </SUBSECTION>
 
2845
 
 
2846
      <SUBSECTION title="Struct Variables">
 
2847
        <p>
 
2848
          Data members in structs should be named like regular
 
2849
          variables without the trailing underscores that data members
 
2850
          in classes have.
 
2851
        </p>
 
2852
        <CODE_SNIPPET>
 
2853
          struct UrlTableProperties {
 
2854
            string name;
 
2855
            int num_entries;
 
2856
          }
 
2857
        </CODE_SNIPPET>
 
2858
        <p>
 
2859
          See <a HREF="#Structs_vs._Classes">Structs vs. Classes</a> for a
 
2860
          discussion of when to use a struct versus a class.
 
2861
        </p>
 
2862
      </SUBSECTION>
 
2863
 
 
2864
      <SUBSECTION title="Global Variables">
 
2865
        <p>
 
2866
          There are no special requirements for global variables,
 
2867
          which should be rare in any case, but if you use one,
 
2868
          consider prefixing it with <code>g_</code> or some other
 
2869
          marker to easily distinguish it from local variables.
 
2870
        </p>
 
2871
      </SUBSECTION>
 
2872
    </BODY>
 
2873
  </STYLEPOINT>
 
2874
 
 
2875
  <STYLEPOINT title="Constant Names">
 
2876
    <SUMMARY>
 
2877
      Use upper-case with underscores between words:
 
2878
      <code>DAYS_IN_A_WEEK</code>.
 
2879
    </SUMMARY>
 
2880
    <BODY>
 
2881
      <p>
 
2882
        All compile-time constants, whether they are declared locally,
 
2883
        globally, or as part of a class, follow a slightly different naming
 
2884
        convention from other variables. Use upper-case with underscores.
 
2885
      </p>
 
2886
      <CODE_SNIPPET>
 
2887
        const int DAYS_IN_A_WEEK = 7;
 
2888
      </CODE_SNIPPET>
 
2889
    </BODY>
 
2890
  </STYLEPOINT>
 
2891
 
 
2892
  <STYLEPOINT title="Function Names">
 
2893
    <SUMMARY>
 
2894
      Regular functions have mixed case; accessors and mutators match
 
2895
      the name of the variable: <code>MyExcitingFunction()</code>,
 
2896
      <code>MyExcitingMethod()</code>,
 
2897
      <code>my_exciting_member_variable()</code>,
 
2898
      <code>set_my_exciting_member_variable()</code>.
 
2899
    </SUMMARY>
 
2900
    <BODY>
 
2901
      <SUBSECTION title="Regular Functions">
 
2902
        <p>
 
2903
          Functions should start with a capital letter and have a
 
2904
          capital letter for each new word. No underscores.
 
2905
        </p>
 
2906
        <p>
 
2907
          If your function crashes upon an error, you should append OrDie to
 
2908
          the function name. This only applies to functions which could be
 
2909
          used by production code and to errors that are reasonably
 
2910
          likely to occur during normal operation.
 
2911
        </p>
 
2912
        <CODE_SNIPPET>
 
2913
          AddTableEntry()
 
2914
          DeleteUrl()
 
2915
          OpenFileOrDie()
 
2916
        </CODE_SNIPPET>
 
2917
      </SUBSECTION>
 
2918
 
 
2919
      <SUBSECTION title="Accessors and Mutators">
 
2920
        <p>
 
2921
          Accessors and mutators (get and set functions) should match
 
2922
          the name of the variable they are getting and setting.  This
 
2923
          shows an excerpt of a class whose instance variable is
 
2924
          <code>num_entries_</code>.
 
2925
        </p>
 
2926
        <CODE_SNIPPET>
 
2927
          class MyClass {
 
2928
           public:
 
2929
            ...
 
2930
            int num_entries() const { return num_entries_; }
 
2931
            void set_num_entries(int num_entries) { num_entries_ = num_entries; }
 
2932
 
 
2933
           private:
 
2934
            int num_entries_;
 
2935
          };
 
2936
        </CODE_SNIPPET>
 
2937
        <p>
 
2938
          You may also use lowercase letters for other very short
 
2939
          inlined functions. For example if a function were so cheap
 
2940
          you would not cache the value if you were calling it in a
 
2941
          loop, then lowercase naming would be acceptable.
 
2942
        </p>
 
2943
      </SUBSECTION>
 
2944
    </BODY>
 
2945
  </STYLEPOINT>
 
2946
 
 
2947
  <STYLEPOINT title="Namespace Names">
 
2948
 
 
2949
    <SUMMARY>
 
2950
      Namespace names are all lower-case, and based on project names and
 
2951
      possibly their directory structure:
 
2952
      <code>my_awesome_project</code>.
 
2953
    </SUMMARY>
 
2954
    <BODY>
 
2955
      <p>
 
2956
        See <a HREF="#Namespaces">Namespaces</a> for a discussion of
 
2957
        namespaces and how to name them.
 
2958
      </p>
 
2959
    </BODY>
 
2960
  </STYLEPOINT>
 
2961
 
 
2962
  <STYLEPOINT title="Enumerator Names">
 
2963
    <SUMMARY>
 
2964
      Enumerators should be named <i>either</i> like
 
2965
      <A HREF="#Constant_Names">constants</A> and
 
2966
      <A HREF="#Macro_Names">macros</A>: <code>ENUM_NAME</code>.
 
2967
    </SUMMARY>
 
2968
    <BODY>
 
2969
      <p>
 
2970
        Preferably, the individual enumerators should be named like
 
2971
        <A HREF="#Constant_Names">constants</A>.  The enumeration name,
 
2972
        <code>UrlTableErrors</code>, is a type, and
 
2973
        therefore mixed case.
 
2974
      </p>
 
2975
      <CODE_SNIPPET>
 
2976
        enum UrlTableErrors {
 
2977
          OK,
 
2978
          OUT_OF_MEMORY,
 
2979
          MALFORMED_INPUT,
 
2980
        };
 
2981
      </CODE_SNIPPET>
 
2982
    </BODY>
 
2983
  </STYLEPOINT>
 
2984
 
 
2985
  <STYLEPOINT title="Macro Names">
 
2986
    <SUMMARY>
 
2987
      You're not really going to <A HREF="#Preprocessor_Macros">define
 
2988
      a macro</A>, are you?  If you do, they're like this:
 
2989
      <code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.
 
2990
    </SUMMARY>
 
2991
    <BODY>
 
2992
      <p>
 
2993
        Please see the <a href="#Preprocessor_Macros">description of
 
2994
        macros</a>; in general macros should <em>not</em> be used.
 
2995
        However, if they are absolutely needed, then they should be
 
2996
        named with all capitals and underscores.
 
2997
      </p>
 
2998
      <CODE_SNIPPET>
 
2999
        #define ROUND(x) ...
 
3000
        #define PI_ROUNDED 3.0
 
3001
      </CODE_SNIPPET>
 
3002
    </BODY>
 
3003
  </STYLEPOINT>
 
3004
 
 
3005
  <STYLEPOINT title="Exceptions to Naming Rules">
 
3006
    <SUMMARY>
 
3007
      If you are naming something that is analogous to an existing C
 
3008
      or C++ entity then you can follow the existing naming convention
 
3009
      scheme.
 
3010
    </SUMMARY>
 
3011
    <BODY>
 
3012
      <p>
 
3013
        <dl>
 
3014
          <dt> <code>bigopen()</code> </dt>
 
3015
          <dd>   function name, follows form of <code>open()</code> </dd>
 
3016
          <dt> <code>uint</code> </dt>
 
3017
          <dd>   <code>typedef</code> </dd>
 
3018
          <dt> <code>bigpos</code> </dt>
 
3019
          <dd>   <code>struct</code> or <code>class</code>, follows form of
 
3020
                 <code>pos</code> </dd>
 
3021
          <dt> <code>sparse_hash_map</code> </dt>
 
3022
          <dd>   STL-like entity; follows STL naming conventions </dd>
 
3023
          <dt> <code>LONGLONG_MAX</code> </dt>
 
3024
          <dd>   a constant, as in <code>INT_MAX</code> </dd>
 
3025
        </dl>
 
3026
      </p>
 
3027
    </BODY>
 
3028
  </STYLEPOINT>
 
3029
</CATEGORY>
 
3030
 
 
3031
<CATEGORY title="Comments">
 
3032
  <p>
 
3033
    Though a pain to write, comments are absolutely vital to keeping our
 
3034
    code readable.  The following rules describe what you should
 
3035
    comment and where.  But remember: while comments are very
 
3036
    important, the best code is self-documenting.  Giving sensible
 
3037
    names to types and variables is much better than using obscure
 
3038
    names that you must then explain through comments.
 
3039
  </p>
 
3040
  <p>
 
3041
    When writing your comments, write for your audience: the next contributor
 
3042
    who will need to understand your code.  Be generous &#8212; the next one
 
3043
    may be you!
 
3044
  </p>
 
3045
 
 
3046
  <STYLEPOINT title="Comment Style">
 
3047
    <SUMMARY>
 
3048
      Use either the <code>//</code> or <code>/* */</code> syntax, as long
 
3049
      as you are consistent.
 
3050
    </SUMMARY>
 
3051
    <BODY>
 
3052
      <p>
 
3053
        You can use either the <code>//</code> or the <code>/* */</code>
 
3054
        syntax; however, <code>//</code> is <em>much</em> more common.
 
3055
        Be consistent with how you comment and what style you use where.
 
3056
      </p>
 
3057
    </BODY>
 
3058
  </STYLEPOINT>
 
3059
 
 
3060
  <STYLEPOINT title="File Comments">
 
3061
    <SUMMARY>
 
3062
      Start each file with a copyright notice, followed by a
 
3063
      description of the contents of the file.
 
3064
    </SUMMARY>
 
3065
    <BODY>
 
3066
      <SUBSECTION title="Legal Notice and Author Line">
 
3067
        <p>
 
3068
          Every file should contain the following items, in order:
 
3069
          <ul>
 
3070
            <li>a optional mode line,
 
3071
            <code>// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-</code></li>
 
3072
            <li>a copyright statement (for example,
 
3073
                <code>Copyright (C) 2011 Canonical Ltd</code>)</li>
 
3074
            <li>the license boilerplate.</li>
 
3075
            <li>an author line to identify the original author of the
 
3076
                file</li>
 
3077
          </ul>
 
3078
        </p>
 
3079
        <p>
 
3080
          If you make significant changes to a file that someone else
 
3081
          originally wrote, add yourself to the author line. This can be very
 
3082
          helpful when another contributor has questions about the file and
 
3083
          needs to know whom to contact about it.
 
3084
        </p>
 
3085
      </SUBSECTION>
 
3086
 
 
3087
      <SUBSECTION title="File Contents">
 
3088
        <p>
 
3089
          Every file should have a comment at the top, below the copyright
 
3090
          notice and author line, that describes the contents of the file.
 
3091
        </p>
 
3092
        <p>
 
3093
          Generally a <code>.h</code> file will describe the classes
 
3094
          that are declared in the file with an overview of what they
 
3095
          are for and how they are used. A <code>.cpp</code> file
 
3096
          should contain more information about implementation details
 
3097
          or discussions of tricky algorithms. If you feel the
 
3098
          implementation details or a discussion of the algorithms
 
3099
          would be useful for someone reading the <code>.h</code>,
 
3100
          feel free to put it there instead, but mention in the
 
3101
          <code>.cpp</code> that the documentation is in the
 
3102
          <code>.h</code> file.
 
3103
        </p>
 
3104
        <p>
 
3105
          Do not duplicate comments in both the <code>.h</code> and
 
3106
          the <code>.cpp</code>. Duplicated comments diverge.
 
3107
        </p>
 
3108
      </SUBSECTION>
 
3109
    </BODY>
 
3110
  </STYLEPOINT>
 
3111
 
 
3112
  <STYLEPOINT title="Class Comments">
 
3113
    <SUMMARY>
 
3114
      Every class definition should have an accompanying comment that
 
3115
      describes what it is for and how it should be used.
 
3116
    </SUMMARY>
 
3117
    <BODY>
 
3118
      <CODE_SNIPPET>
 
3119
        // Iterates over the contents of a GargantuanTable.  Sample usage:
 
3120
        //    GargantuanTableIterator* iter = table-&gt;NewIterator();
 
3121
        //    for (iter-&gt;Seek("foo"); !iter-&gt;done(); iter-&gt;Next()) {
 
3122
        //      process(iter-&gt;key(), iter-&gt;value());
 
3123
        //    }
 
3124
        //    delete iter;
 
3125
        class GargantuanTableIterator {
 
3126
          ...
 
3127
        };
 
3128
      </CODE_SNIPPET>
 
3129
      <p>
 
3130
        If you have already described a class in detail in the
 
3131
        comments at the top of your file feel free to simply state
 
3132
        "See comment at top of file for a complete description", but
 
3133
        be sure to have some sort of comment.
 
3134
      </p>
 
3135
      <p>
 
3136
        Document the synchronization assumptions the class makes, if
 
3137
        any.  If an instance of the class can be accessed by multiple
 
3138
        threads, take extra care to document the rules and invariants
 
3139
        surrounding multithreaded use.
 
3140
      </p>
 
3141
    </BODY>
 
3142
  </STYLEPOINT>
 
3143
 
 
3144
  <STYLEPOINT title="Function Comments">
 
3145
    <SUMMARY>
 
3146
      Declaration comments describe use of the function; comments at
 
3147
      the definition of a function describe operation.
 
3148
    </SUMMARY>
 
3149
    <BODY>
 
3150
      <SUBSECTION title="Function Declarations">
 
3151
        <p>
 
3152
          Every function declaration should have comments immediately
 
3153
          preceding it that describe what the function does and how to
 
3154
          use it.  These comments should be descriptive ("Opens the
 
3155
          file") rather than imperative ("Open the file"); the comment
 
3156
          describes the function, it does not tell the function what
 
3157
          to do.  In general, these comments do not describe how the
 
3158
          function performs its task.  Instead, that should be left to
 
3159
          comments in the function definition.
 
3160
        </p>
 
3161
        <p>
 
3162
          Types of things to mention in comments at the function
 
3163
          declaration:
 
3164
        </p>
 
3165
        <ul>
 
3166
          <li> What the inputs and outputs are.
 
3167
               </li>
 
3168
          <li> For class member functions:  whether the object
 
3169
               remembers reference arguments beyond the
 
3170
               duration of the method call, and whether it will
 
3171
               free them or not.
 
3172
               </li>
 
3173
          <li> If the function allocates memory that the caller
 
3174
               must free.
 
3175
               </li>
 
3176
          <li> Whether any of the arguments can be <code>NULL</code>.
 
3177
               </li>
 
3178
          <li> If there are any performance implications of how a
 
3179
               function is used.
 
3180
               </li>
 
3181
          <li> If the function is re-entrant.  What are its
 
3182
               synchronization assumptions?
 
3183
               </li>
 
3184
        </ul>
 
3185
        <p>
 
3186
          Here is an example:
 
3187
        </p>
 
3188
        <CODE_SNIPPET>
 
3189
          // Returns an iterator for this table.  It is the client's
 
3190
          // responsibility to delete the iterator when it is done with it,
 
3191
          // and it must not use the iterator once the GargantuanTable object
 
3192
          // on which the iterator was created has been deleted.
 
3193
          //
 
3194
          // The iterator is initially positioned at the beginning of the table.
 
3195
          //
 
3196
          // This method is equivalent to:
 
3197
          //    Iterator* iter = table-&gt;NewIterator();
 
3198
          //    iter-&gt;Seek("");
 
3199
          //    return iter;
 
3200
          // If you are going to immediately seek to another place in the
 
3201
          // returned iterator, it will be faster to use NewIterator()
 
3202
          // and avoid the extra seek.
 
3203
          Iterator* GetIterator() const;
 
3204
        </CODE_SNIPPET>
 
3205
        <p>
 
3206
          However, do not be unnecessarily verbose or state the
 
3207
          completely obvious.  Notice below that it is not necessary
 
3208
          to say "returns false otherwise" because this is implied.
 
3209
        </p>
 
3210
        <CODE_SNIPPET>
 
3211
          // Returns true if the table cannot hold any more entries.
 
3212
          bool IsTableFull();
 
3213
        </CODE_SNIPPET>
 
3214
        <p>
 
3215
          When commenting constructors and destructors, remember that
 
3216
          the person reading your code knows what constructors and
 
3217
          destructors are for, so comments that just say something like
 
3218
          "destroys this object" are not useful.  Document what
 
3219
          constructors do with their arguments (for example, if they
 
3220
          take ownership of pointers), and what cleanup the destructor
 
3221
          does.  If this is trivial, just skip the comment.  It is
 
3222
          quite common for destructors not to have a header comment.
 
3223
        </p>
 
3224
      </SUBSECTION>
 
3225
 
 
3226
      <SUBSECTION title="Function Definitions">
 
3227
        <p>
 
3228
          Each function definition should have a comment describing
 
3229
          what the function does if there's anything tricky about how it does
 
3230
          its job.  For example, in the definition comment you might
 
3231
          describe any coding tricks you use, give an overview of the
 
3232
          steps you go through, or explain why you chose to implement
 
3233
          the function in the way you did rather than using a viable
 
3234
          alternative.  For instance, you might mention why it must
 
3235
          acquire a lock for the first half of the function but why it
 
3236
          is not needed for the second half.
 
3237
        </p>
 
3238
        <p>
 
3239
          Note you should <em>not</em> just repeat the comments given
 
3240
          with the function declaration, in the <code>.h</code> file or
 
3241
          wherever.  It's okay to recapitulate briefly what the function
 
3242
          does, but the focus of the comments should be on how it does it.
 
3243
        </p>
 
3244
      </SUBSECTION>
 
3245
    </BODY>
 
3246
  </STYLEPOINT>
 
3247
 
 
3248
  <STYLEPOINT title="Variable Comments">
 
3249
    <SUMMARY>
 
3250
      In general the actual name of the variable should be descriptive
 
3251
      enough to give a good idea of what the variable is used for.  In
 
3252
      certain cases, more comments are required.
 
3253
    </SUMMARY>
 
3254
    <BODY>
 
3255
      <SUBSECTION title="Class Data Members">
 
3256
        <p>
 
3257
          Each class data member (also called an instance variable or
 
3258
          member variable) should have a comment describing what it is
 
3259
          used for.  If the variable can take sentinel values with
 
3260
          special meanings, such as <code>NULL</code> or -1, document this.
 
3261
          For example:
 
3262
        </p>
 
3263
        <CODE_SNIPPET>
 
3264
          private:
 
3265
           // Keeps track of the total number of entries in the table.
 
3266
           // Used to ensure we do not go over the limit. -1 means
 
3267
           // that we don't yet know how many entries the table has.
 
3268
           int num_total_entries_;
 
3269
        </CODE_SNIPPET>
 
3270
      </SUBSECTION>
 
3271
 
 
3272
      <SUBSECTION title="Global Variables">
 
3273
        <p>
 
3274
          As with data members, all global variables should have a
 
3275
          comment describing what they are and what they are used for.
 
3276
          For example:
 
3277
        </p>
 
3278
        <CODE_SNIPPET>
 
3279
          // The total number of tests cases that we run through in this regression test.
 
3280
          const int kNumTestCases = 6;
 
3281
        </CODE_SNIPPET>
 
3282
      </SUBSECTION>
 
3283
    </BODY>
 
3284
  </STYLEPOINT>
 
3285
 
 
3286
  <STYLEPOINT title="Implementation Comments">
 
3287
    <SUMMARY>
 
3288
      In your implementation you should have comments in tricky,
 
3289
      non-obvious, interesting, or important parts of your code.
 
3290
    </SUMMARY>
 
3291
    <BODY>
 
3292
      <SUBSECTION title="Class Data Members">
 
3293
        <p>
 
3294
          Tricky or complicated code blocks should have comments
 
3295
          before them. Example:
 
3296
        </p>
 
3297
        <CODE_SNIPPET>
 
3298
          // Divide result by two, taking into account that x
 
3299
          // contains the carry from the add.
 
3300
          for (int i = 0; i &lt; result-&gt;size(); i++) {
 
3301
            x = (x &lt;&lt; 8) + (*result)[i];
 
3302
            (*result)[i] = x &gt;&gt; 1;
 
3303
            x &amp;= 1;
 
3304
          }
 
3305
        </CODE_SNIPPET>
 
3306
      </SUBSECTION>
 
3307
      <SUBSECTION title="Line Comments">
 
3308
        <p>
 
3309
          Also, lines that are non-obvious should get a comment at the
 
3310
          end of the line. These end-of-line comments should be
 
3311
          separated from the code by 2 spaces.  Example:
 
3312
        </p>
 
3313
        <CODE_SNIPPET>
 
3314
          // If we have enough memory, mmap the data portion too.
 
3315
          mmap_budget = max&lt;int64&gt;(0, mmap_budget - index_-&gt;length());
 
3316
          if (mmap_budget &gt;= data_size_ &amp;&amp; !MmapData(mmap_chunk_bytes, mlock))
 
3317
            return;  // Error already logged.
 
3318
        </CODE_SNIPPET>
 
3319
        <p>
 
3320
          Note that there are both comments that describe what the
 
3321
          code is doing, and comments that mention that an error has
 
3322
          already been logged when the function returns.
 
3323
        </p>
 
3324
        <p>
 
3325
          If you have several comments on subsequent lines, it can
 
3326
          often be more readable to line them up:
 
3327
        </p>
 
3328
        <CODE_SNIPPET>
 
3329
          DoSomething();                  // Comment here so the comments line up.
 
3330
          DoSomethingElseThatIsLonger();  // Comment here so there are two spaces between
 
3331
                                          // the code and the comment.
 
3332
          { // One space before comment when opening a new scope is allowed,
 
3333
            // thus the comment lines up with the following comments and code.
 
3334
            DoSomethingElse();  // Two spaces before line comments normally.
 
3335
          }
 
3336
        </CODE_SNIPPET>
 
3337
      </SUBSECTION>
 
3338
      <SUBSECTION title="NULL, true/false, 1, 2, 3...">
 
3339
        <p>
 
3340
          When you pass in <code>NULL</code>, boolean, or literal integer
 
3341
          values to functions, you should consider adding a comment about
 
3342
          what they are, or make your code self-documenting by using
 
3343
          constants. For example, compare:
 
3344
        </p>
 
3345
        <BAD_CODE_SNIPPET>
 
3346
          bool success = CalculateSomething(interesting_value,
 
3347
                                            10,
 
3348
                                            false,
 
3349
                                            NULL);  // What are these arguments??
 
3350
        </BAD_CODE_SNIPPET>
 
3351
        <p>
 
3352
          versus:
 
3353
        </p>
 
3354
        <CODE_SNIPPET>
 
3355
          bool success = CalculateSomething(interesting_value,
 
3356
                                            10,     // Default base value.
 
3357
                                            false,  // Not the first time we're calling this.
 
3358
                                            NULL);  // No callback.
 
3359
        </CODE_SNIPPET>
 
3360
        <p>
 
3361
          Or alternatively, constants or self-describing variables:
 
3362
        </p>
 
3363
        <CODE_SNIPPET>
 
3364
          const int kDefaultBaseValue = 10;
 
3365
          const bool kFirstTimeCalling = false;
 
3366
          Callback *null_callback = NULL;
 
3367
          bool success = CalculateSomething(interesting_value,
 
3368
                                            kDefaultBaseValue,
 
3369
                                            kFirstTimeCalling,
 
3370
                                            null_callback);
 
3371
        </CODE_SNIPPET>
 
3372
      </SUBSECTION>
 
3373
 
 
3374
      <SUBSECTION title="Don'ts">
 
3375
        <p>
 
3376
          Note that you should <em>never</em> describe the code
 
3377
          itself. Assume that the person reading the code knows C++
 
3378
          better than you do, even though he or she does not know what
 
3379
          you are trying to do:
 
3380
        </p>
 
3381
        <BAD_CODE_SNIPPET>
 
3382
           // Now go through the b array and make sure that if i occurs,
 
3383
           // the next element is i+1.
 
3384
           ...        // Geez.  What a useless comment.
 
3385
        </BAD_CODE_SNIPPET>
 
3386
      </SUBSECTION>
 
3387
    </BODY>
 
3388
  </STYLEPOINT>
 
3389
 
 
3390
  <STYLEPOINT title="Punctuation, Spelling and Grammar">
 
3391
    <SUMMARY>
 
3392
      Pay attention to punctuation, spelling, and grammar; it is
 
3393
      easier to read well-written comments than badly written ones.
 
3394
    </SUMMARY>
 
3395
    <BODY>
 
3396
      <p>
 
3397
        Comments should usually be written as complete
 
3398
        sentences with proper capitalization and periods at the end.
 
3399
        Shorter comments, such as comments at the end of a line of
 
3400
        code, can sometimes be less formal, but you should be
 
3401
        consistent with your style.  Complete sentences are more
 
3402
        readable, and they provide some assurance that the comment is
 
3403
        complete and not an unfinished thought.
 
3404
      </p>
 
3405
      <p>
 
3406
        Although it can be frustrating to have a code reviewer point
 
3407
        out that you are using a comma when you should be using a
 
3408
        semicolon, it is very important that source code maintain a
 
3409
        high level of clarity and readability.  Proper punctuation,
 
3410
        spelling, and grammar help with that goal.
 
3411
      </p>
 
3412
    </BODY>
 
3413
  </STYLEPOINT>
 
3414
 
 
3415
  <STYLEPOINT title="TODO Comments">
 
3416
    <SUMMARY>
 
3417
      Use <code>TODO</code> comments for code that is temporary, a
 
3418
      short-term solution, or good-enough but not perfect.
 
3419
    </SUMMARY>
 
3420
    <BODY>
 
3421
      <p>
 
3422
        <code>TODO</code>s should include the string <code>TODO</code> in
 
3423
        all caps, followed by the
 
3424
 
 
3425
        name, e-mail address, or other
 
3426
        identifier
 
3427
        of the person who can best provide context about the problem
 
3428
        referenced by the <code>TODO</code>.  A colon is optional.  The main
 
3429
        purpose is to have a consistent <code>TODO</code> format that can be
 
3430
        searched to find the person who can provide more details upon request.
 
3431
        A <code>TODO</code> is not a commitment that the person referenced
 
3432
        will fix the problem.  Thus when you create a <code>TODO</code>, it is
 
3433
        almost always your
 
3434
 
 
3435
        name
 
3436
        that is given.
 
3437
      </p>
 
3438
 
 
3439
      <CODE_SNIPPET>
 
3440
        // TODO(kl@gmail.com): Use a "*" here for concatenation operator.
 
3441
        // TODO(Zeke) change this to use relations.
 
3442
      </CODE_SNIPPET>
 
3443
      <p>
 
3444
        If your <code>TODO</code> is of the form "At a future date do
 
3445
        something" make sure that you either include a very specific
 
3446
        date ("Fix by November 2005") or a very specific event
 
3447
        ("Remove this code when all clients can handle XML responses.").
 
3448
      </p>
 
3449
    </BODY>
 
3450
  </STYLEPOINT>
 
3451
 
 
3452
  <STYLEPOINT title="Deprecation Comments">
 
3453
    <SUMMARY>
 
3454
      Mark deprecated interface points with <code>DEPRECATED</code> comments.
 
3455
    </SUMMARY>
 
3456
    <BODY>
 
3457
      <p>
 
3458
      You can mark an interface as deprecated by writing a comment containing
 
3459
      the word <code>DEPRECATED</code> in all caps.  The comment goes either
 
3460
      before the declaration of the interface or on the same line as the
 
3461
      declaration.
 
3462
      </p>
 
3463
 
 
3464
      <p>
 
3465
      After the word <code>DEPRECATED</code>, write your name, e-mail address,
 
3466
      or other identifier in parentheses.
 
3467
      </p>
 
3468
      <p>
 
3469
      A deprecation comment must include simple, clear directions for people to
 
3470
      fix their callsites.  In C++, you can implement a deprecated function as
 
3471
      an inline function that calls the new interface point.
 
3472
      </p>
 
3473
      <p>
 
3474
      Marking an interface point <code>DEPRECATED</code> will not magically
 
3475
      cause any callsites to change.  If you want people to actually stop using
 
3476
      the deprecated facility, you will have to fix the callsites yourself or
 
3477
      recruit a crew to help you.
 
3478
      </p>
 
3479
      <p>
 
3480
      New code should not contain calls to deprecated interface points.  Use
 
3481
      the new interface point instead.  If you cannot understand the
 
3482
      directions, find the person who created the deprecation and ask them for
 
3483
      help using the new interface point.
 
3484
      </p>
 
3485
 
 
3486
    </BODY>
 
3487
  </STYLEPOINT>
 
3488
 
 
3489
</CATEGORY>
 
3490
 
 
3491
<CATEGORY title="Formatting">
 
3492
  <p>
 
3493
    Coding style and formatting are pretty arbitrary, but a
 
3494
 
 
3495
    project
 
3496
    is much easier to follow if everyone uses the same style. Individuals
 
3497
    may not agree with every aspect of the formatting rules, and some of
 
3498
    the rules may take some getting used to, but it is important that all
 
3499
 
 
3500
    project contributors
 
3501
    follow the style rules so that
 
3502
 
 
3503
    they
 
3504
    can all read and understand everyone's code easily.
 
3505
  </p>
 
3506
 
 
3507
  <p>
 
3508
    To help you format code correctly, we've created a <A HREF="http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el">settings
 
3509
    file for emacs</A>.
 
3510
  </p>
 
3511
 
 
3512
  <STYLEPOINT title="Line Length">
 
3513
    <SUMMARY>
 
3514
      Each line of text in your code should be at most 80 characters
 
3515
      long.
 
3516
    </SUMMARY>
 
3517
    <BODY>
 
3518
 
 
3519
      <p>
 
3520
        We recognize that this rule is controversial, but so much existing
 
3521
        code already adheres to it, and we feel that consistency is
 
3522
        important.
 
3523
      </p>
 
3524
      <PROS>
 
3525
          Those who favor
 
3526
 
 
3527
          this rule argue
 
3528
          that it is rude to force them to resize their windows and there
 
3529
          is no need for anything longer.  Some folks are used to having
 
3530
          several code windows side-by-side, and thus don't have room to
 
3531
          widen their windows in any case.  People set up their work
 
3532
          environment assuming a particular maximum window width, and 80
 
3533
          columns has been the traditional standard.  Why change it?
 
3534
      </PROS>
 
3535
      <CONS>
 
3536
          Proponents of change argue that a wider line can make code
 
3537
          more readable.  The 80-column limit is an hidebound
 
3538
          throwback to 1960s mainframes;
 
3539
 
 
3540
          modern equipment has
 
3541
          wide screens that can easily show longer lines.
 
3542
      </CONS>
 
3543
      <DECISION>
 
3544
        <p>
 
3545
 
 
3546
          80 characters is the maximum.
 
3547
        </p>
 
3548
        <p>
 
3549
          Exception: if a comment line contains an example command or
 
3550
          a literal URL longer than 80 characters, that line may be
 
3551
          longer than 80 characters for ease of cut and paste.
 
3552
        </p>
 
3553
        <p>
 
3554
          Exception: an <code>#include</code> statement with a long
 
3555
          path may exceed 80 columns.  Try to avoid situations where this
 
3556
          becomes necessary.
 
3557
        </p>
 
3558
        <p>
 
3559
          Exception:  you needn't be concerned about
 
3560
          <a href="#The__define_Guard">header guards</a>
 
3561
          that exceed the maximum length.
 
3562
 
 
3563
        </p>
 
3564
      </DECISION>
 
3565
    </BODY>
 
3566
  </STYLEPOINT>
 
3567
 
 
3568
  <STYLEPOINT title="Non-ASCII Characters">
 
3569
    <SUMMARY>
 
3570
      Non-ASCII characters should be rare, and must use UTF-8 formatting.
 
3571
    </SUMMARY>
 
3572
    <BODY>
 
3573
      <p>
 
3574
        You shouldn't hard-code user-facing text in source, even English,
 
3575
        so use of non-ASCII characters should be rare.  However, in certain
 
3576
        cases it is appropriate to include such words in your code.  For
 
3577
        example, if your code parses data files from foreign sources,
 
3578
        it may be appropriate to hard-code the non-ASCII string(s) used in
 
3579
        those data files as delimiters.  More commonly, unittest code
 
3580
        (which does not
 
3581
 
 
3582
        need to be localized) might contain non-ASCII strings.  In such
 
3583
        cases, you should use UTF-8, since that is
 
3584
 
 
3585
        an encoding understood by most tools able
 
3586
        to handle more than just ASCII.
 
3587
        Hex encoding is also OK, and encouraged where it enhances
 
3588
        readability &#8212; for example, <code>"\xEF\xBB\xBF"</code> is the
 
3589
        Unicode zero-width no-break space character, which would be
 
3590
        invisible if included in the source as straight UTF-8.
 
3591
      </p>
 
3592
    </BODY>
 
3593
  </STYLEPOINT>
 
3594
 
 
3595
  <STYLEPOINT title="Spaces vs. Tabs">
 
3596
    <SUMMARY>
 
3597
      Use only spaces, and indent 2 spaces at a time.
 
3598
    </SUMMARY>
 
3599
    <BODY>
 
3600
      <p>
 
3601
        We use spaces for indentation. Do not use tabs in your code.
 
3602
        You should set your editor to emit spaces when you hit the tab
 
3603
        key.
 
3604
      </p>
 
3605
    </BODY>
 
3606
  </STYLEPOINT>
 
3607
 
 
3608
  <STYLEPOINT title="Function Declarations and Definitions">
 
3609
    <SUMMARY>
 
3610
      Return type on the same line as function name, parameters on the
 
3611
      same line if they fit.
 
3612
    </SUMMARY>
 
3613
    <BODY>
 
3614
      <p>
 
3615
        Functions look like this:
 
3616
      </p>
 
3617
      <CODE_SNIPPET>
 
3618
        ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
 
3619
          DoSomething();
 
3620
          ...
 
3621
        }
 
3622
      </CODE_SNIPPET>
 
3623
      <p>
 
3624
        If you have too much text to fit on one line:
 
3625
      </p>
 
3626
      <CODE_SNIPPET>
 
3627
        ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,
 
3628
                                                     Type par_name3) {
 
3629
          DoSomething();
 
3630
          ...
 
3631
        }
 
3632
      </CODE_SNIPPET>
 
3633
      <p>
 
3634
        or if you cannot fit even the first parameter:
 
3635
      </p>
 
3636
      <CODE_SNIPPET>
 
3637
        ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
 
3638
            Type par_name1,  // 4 space indent
 
3639
            Type par_name2,
 
3640
            Type par_name3) {
 
3641
          DoSomething();  // 2 space indent
 
3642
          ...
 
3643
        }
 
3644
      </CODE_SNIPPET>
 
3645
      <p>
 
3646
        Some points to note:
 
3647
      </p>
 
3648
      <ul>
 
3649
        <li> The return type is always on the same line as the
 
3650
             function name.
 
3651
             </li>
 
3652
        <li> The open parenthesis is always on the same line as the
 
3653
             function name.
 
3654
             </li>
 
3655
        <li> There is never a space between the function name and the
 
3656
             open parenthesis.
 
3657
             </li>
 
3658
        <li> There is never a space between the parentheses and the
 
3659
             parameters.
 
3660
             </li>
 
3661
        <li> The open curly brace is always at the end of the same
 
3662
             line as the last parameter.
 
3663
             </li>
 
3664
        <li> The close curly brace is either on the last line by itself
 
3665
             or (if other style rules permit) on the same line as the
 
3666
             open curly brace.
 
3667
             </li>
 
3668
        <li> There should be a space between the close parenthesis and
 
3669
             the open curly brace.
 
3670
             </li>
 
3671
        <li> All parameters should be named, with identical names in the
 
3672
             declaration and implementation.
 
3673
             </li>
 
3674
        <li> All parameters should be aligned if possible.
 
3675
             </li>
 
3676
        <li> Default indentation is 2 spaces.
 
3677
             </li>
 
3678
        <li> Wrapped parameters have a 4 space indent.
 
3679
             </li>
 
3680
      </ul>
 
3681
      <p>
 
3682
        If your function is <code>const</code>, the <code>const</code>
 
3683
        keyword should be on the same line as the last parameter:
 
3684
      </p>
 
3685
      <CODE_SNIPPET>
 
3686
        // Everything in this function signature fits on a single line
 
3687
        ReturnType FunctionName(Type par) const {
 
3688
          ...
 
3689
        }
 
3690
 
 
3691
        // This function signature requires multiple lines, but
 
3692
        // the const keyword is on the line with the last parameter.
 
3693
        ReturnType ReallyLongFunctionName(Type par1,
 
3694
                                          Type par2) const {
 
3695
          ...
 
3696
        }
 
3697
      </CODE_SNIPPET>
 
3698
      <p>
 
3699
        If some parameters are unused, comment out the variable name in the
 
3700
        function definition:
 
3701
      </p>
 
3702
      <CODE_SNIPPET>
 
3703
        // Always have named parameters in interfaces.
 
3704
        class Shape {
 
3705
         public:
 
3706
          virtual void Rotate(double radians) = 0;
 
3707
        }
 
3708
 
 
3709
        // Always have named parameters in the declaration.
 
3710
        class Circle : public Shape {
 
3711
         public:
 
3712
          virtual void Rotate(double radians);
 
3713
        }
 
3714
 
 
3715
        // Comment out unused named parameters in definitions.
 
3716
        void Circle::Rotate(double /*radians*/) {}
 
3717
      </CODE_SNIPPET>
 
3718
      <BAD_CODE_SNIPPET>
 
3719
        // Bad - if someone wants to implement later, it's not clear what the
 
3720
        // variable means.
 
3721
        void Circle::Rotate(double) {}
 
3722
      </BAD_CODE_SNIPPET>
 
3723
    </BODY>
 
3724
  </STYLEPOINT>
 
3725
 
 
3726
  <STYLEPOINT title="Function Calls">
 
3727
    <SUMMARY>
 
3728
      On one line if it fits; otherwise, wrap arguments at the
 
3729
      parenthesis.
 
3730
    </SUMMARY>
 
3731
    <BODY>
 
3732
      <p>
 
3733
        Function calls have the following format:
 
3734
      </p>
 
3735
      <CODE_SNIPPET>
 
3736
        bool retval = DoSomething(argument1, argument2, argument3);
 
3737
      </CODE_SNIPPET>
 
3738
      <p>
 
3739
        If the arguments do not all fit on one line, they should be
 
3740
        broken up onto multiple lines, with each subsequent line
 
3741
        aligned with the first argument.  Do not add spaces after the
 
3742
        open paren or before the close paren:
 
3743
      </p>
 
3744
      <CODE_SNIPPET>
 
3745
        bool retval = DoSomething(averyveryveryverylongargument1,
 
3746
                                  argument2, argument3);
 
3747
      </CODE_SNIPPET>
 
3748
      <p>
 
3749
        If the function has many arguments, consider having one per
 
3750
        line if this makes the code more readable:
 
3751
      </p>
 
3752
      <CODE_SNIPPET>
 
3753
        bool retval = DoSomething(argument1,
 
3754
                                  argument2,
 
3755
                                  argument3,
 
3756
                                  argument4);
 
3757
      </CODE_SNIPPET>
 
3758
      <p>
 
3759
        If the function signature is so long that it cannot fit within
 
3760
        the maximum <a href="#Line_Length">line length</a>, you may
 
3761
        place all arguments on subsequent lines:
 
3762
      </p>
 
3763
      <CODE_SNIPPET>
 
3764
        if (...) {
 
3765
          ...
 
3766
          ...
 
3767
          if (...) {
 
3768
            DoSomethingThatRequiresALongFunctionName(
 
3769
                very_long_argument1,  // 4 space indent
 
3770
                argument2,
 
3771
                argument3,
 
3772
                argument4);
 
3773
          }
 
3774
      </CODE_SNIPPET>
 
3775
    </BODY>
 
3776
  </STYLEPOINT>
 
3777
 
 
3778
  <STYLEPOINT title="Conditionals">
 
3779
    <SUMMARY>
 
3780
      Prefer no spaces inside parentheses.  The <code>else</code>
 
3781
      keyword belongs on a new line.
 
3782
    </SUMMARY>
 
3783
    <BODY>
 
3784
      <p>
 
3785
        There are two acceptable formats for a basic conditional
 
3786
        statement. One includes spaces between the parentheses and the
 
3787
        condition, and one does not.
 
3788
      </p>
 
3789
      <p>
 
3790
        The most common form is without spaces.  Either is fine, but
 
3791
        <em>be consistent</em>. If you are modifying a file, use the
 
3792
        format that is already present. If you are writing new code,
 
3793
        use the format that the other files in that directory or
 
3794
        project use. If in doubt and you have no personal preference,
 
3795
        do not add the spaces.
 
3796
      </p>
 
3797
      <CODE_SNIPPET>
 
3798
        if (condition) {  // no spaces inside parentheses
 
3799
          ...  // 2 space indent.
 
3800
        } else {  // The else goes on the same line as the closing brace.
 
3801
          ...
 
3802
        }
 
3803
      </CODE_SNIPPET>
 
3804
      <p>
 
3805
        If you prefer you may add spaces inside the
 
3806
        parentheses:
 
3807
      </p>
 
3808
      <CODE_SNIPPET>
 
3809
        if ( condition ) {  // spaces inside parentheses - rare
 
3810
          ...  // 2 space indent.
 
3811
        } else {  // The else goes on the same line as the closing brace.
 
3812
          ...
 
3813
        }
 
3814
      </CODE_SNIPPET>
 
3815
      <p>
 
3816
        Note that in all cases you must have a space between the
 
3817
        <code>if</code> and the open parenthesis.  You must also have
 
3818
        a space between the close parenthesis and the curly brace, if
 
3819
        you're using one.
 
3820
      </p>
 
3821
      <BAD_CODE_SNIPPET>
 
3822
        if(condition)     // Bad - space missing after IF.
 
3823
        if (condition){   // Bad - space missing before {.
 
3824
        if(condition){    // Doubly bad.
 
3825
      </BAD_CODE_SNIPPET>
 
3826
      <CODE_SNIPPET>
 
3827
        if (condition) {  // Good - proper space after IF and before {.
 
3828
      </CODE_SNIPPET>
 
3829
      <p>
 
3830
        Short conditional statements may be written on one line if
 
3831
        this enhances readability.  You may use this only when the
 
3832
        line is brief and the statement does not use the
 
3833
        <code>else</code> clause.
 
3834
      </p>
 
3835
      <CODE_SNIPPET>
 
3836
        if (x == kFoo) return new Foo();
 
3837
        if (x == kBar) return new Bar();
 
3838
      </CODE_SNIPPET>
 
3839
      <p>
 
3840
        This is not allowed when the if statement has an
 
3841
        <code>else</code>:
 
3842
      </p>
 
3843
      <BAD_CODE_SNIPPET>
 
3844
        // Not allowed - IF statement on one line when there is an ELSE clause
 
3845
        if (x) DoThis();
 
3846
        else DoThat();
 
3847
      </BAD_CODE_SNIPPET>
 
3848
      <p>
 
3849
        In general, curly braces are not required for single-line
 
3850
        statements, but they are allowed if you like them;
 
3851
        conditional or loop statements with complex conditions or
 
3852
        statements may be more readable with curly braces. Some
 
3853
 
 
3854
        projects
 
3855
        require that an <CODE>if</CODE> must always always have an
 
3856
        accompanying brace.
 
3857
      </p>
 
3858
      <CODE_SNIPPET>
 
3859
        if (condition)
 
3860
          DoSomething();  // 2 space indent.
 
3861
 
 
3862
        if (condition) {
 
3863
          DoSomething();  // 2 space indent.
 
3864
        }
 
3865
      </CODE_SNIPPET>
 
3866
      <p>
 
3867
        However, if one part of an <code>if</code>-<code>else</code>
 
3868
        statement uses curly braces, the other part must too:
 
3869
      </p>
 
3870
      <BAD_CODE_SNIPPET>
 
3871
        // Not allowed - curly on IF but not ELSE
 
3872
        if (condition) {
 
3873
          foo;
 
3874
        } else
 
3875
          bar;
 
3876
 
 
3877
        // Not allowed - curly on ELSE but not IF
 
3878
        if (condition)
 
3879
          foo;
 
3880
        else {
 
3881
          bar;
 
3882
        }
 
3883
      </BAD_CODE_SNIPPET>
 
3884
      <CODE_SNIPPET>
 
3885
        // Curly braces around both IF and ELSE required because
 
3886
        // one of the clauses used braces.
 
3887
        if (condition) {
 
3888
          foo;
 
3889
        } else {
 
3890
          bar;
 
3891
        }
 
3892
      </CODE_SNIPPET>
 
3893
    </BODY>
 
3894
  </STYLEPOINT>
 
3895
 
 
3896
  <STYLEPOINT title="Loops and Switch Statements">
 
3897
    <SUMMARY>
 
3898
      Switch statements may use braces for blocks.  Empty loop bodies should use
 
3899
      <code>{}</code> or <code>continue</code>.
 
3900
    </SUMMARY>
 
3901
    <BODY>
 
3902
      <p>
 
3903
        <code>case</code> blocks in <code>switch</code> statements can have
 
3904
        curly braces or not, depending on your preference.  If you do
 
3905
        include curly braces they should be placed as shown below.
 
3906
      </p>
 
3907
      <p>
 
3908
        If not conditional on an enumerated value, switch statements
 
3909
        should always have a <code>default</code> case (in the case of
 
3910
        an enumerated value, the compiler will warn you if any values
 
3911
        are not handled).  If the default case should never execute,
 
3912
        simply
 
3913
        <code>assert</code>:
 
3914
      </p>
 
3915
 
 
3916
      <CODE_SNIPPET>
 
3917
        switch (var) {
 
3918
          case 0: {  // 2 space indent
 
3919
            ...      // 4 space indent
 
3920
            break;
 
3921
          }
 
3922
          case 1: {
 
3923
            ...
 
3924
            break;
 
3925
          }
 
3926
          default: {
 
3927
            assert(false);
 
3928
          }
 
3929
        }
 
3930
      </CODE_SNIPPET>
 
3931
      <p>
 
3932
        Empty loop bodies should use <code>{}</code> or
 
3933
        <code>continue</code>, but not a single semicolon.
 
3934
      </p>
 
3935
      <CODE_SNIPPET>
 
3936
        while (condition) {
 
3937
          // Repeat test until it returns false.
 
3938
        }
 
3939
        for (int i = 0; i &lt; kSomeNumber; ++i) {}  // Good - empty body.
 
3940
        while (condition) continue;  // Good - continue indicates no logic.
 
3941
      </CODE_SNIPPET>
 
3942
      <BAD_CODE_SNIPPET>
 
3943
        while (condition);  // Bad - looks like part of do/while loop.
 
3944
      </BAD_CODE_SNIPPET>
 
3945
    </BODY>
 
3946
  </STYLEPOINT>
 
3947
 
 
3948
  <STYLEPOINT title="Pointer and Reference Expressions">
 
3949
    <SUMMARY>
 
3950
      No spaces around period or arrow.  Pointer operators do not have
 
3951
      trailing spaces.
 
3952
    </SUMMARY>
 
3953
    <BODY>
 
3954
      <p>
 
3955
        The following are examples of correctly-formatted pointer and
 
3956
        reference expressions:
 
3957
      </p>
 
3958
      <CODE_SNIPPET>
 
3959
        x = *p;
 
3960
        p = &amp;x;
 
3961
        x = r.y;
 
3962
        x = r-&gt;y;
 
3963
      </CODE_SNIPPET>
 
3964
      <p>
 
3965
        Note that:
 
3966
      </p>
 
3967
      <ul>
 
3968
        <li> There are no spaces around the period or arrow when
 
3969
             accessing a member.
 
3970
             </li>
 
3971
        <li> Pointer operators have no space after the <code>*</code> or
 
3972
             <code>&amp;</code>.
 
3973
             </li>
 
3974
      </ul>
 
3975
      <p>
 
3976
        When declaring a pointer variable or argument, you may place
 
3977
        the asterisk adjacent to either the type or to the variable
 
3978
        name:
 
3979
      </p>
 
3980
      <CODE_SNIPPET>
 
3981
        // These are fine, space preceding.
 
3982
        char *c;
 
3983
        const string &amp;str;
 
3984
 
 
3985
        // These are fine, space following.
 
3986
        char* c;    // but remember to do "char* c, *d, *e, ...;"!
 
3987
        const string&amp; str;
 
3988
      </CODE_SNIPPET>
 
3989
      <BAD_CODE_SNIPPET>
 
3990
        char * c;  // Bad - spaces on both sides of *
 
3991
        const string &amp; str;  // Bad - spaces on both sides of &amp;
 
3992
      </BAD_CODE_SNIPPET>
 
3993
      <p>
 
3994
        You should do this consistently within a single
 
3995
        file,
 
3996
        so, when modifying an existing file, use the style in that
 
3997
        file.
 
3998
      </p>
 
3999
    </BODY>
 
4000
  </STYLEPOINT>
 
4001
 
 
4002
  <STYLEPOINT title="Boolean Expressions">
 
4003
    <SUMMARY>
 
4004
      When you have a boolean expression that is longer than the <a href="#Line_Length">standard line length</a>, be consistent in
 
4005
      how you break up the lines.
 
4006
    </SUMMARY>
 
4007
    <BODY>
 
4008
      <p>
 
4009
        In this example, the logical AND operator is always at the end
 
4010
        of the lines:
 
4011
      </p>
 
4012
      <CODE_SNIPPET>
 
4013
        if (this_one_thing &gt; this_other_thing &amp;&amp;
 
4014
            a_third_thing == a_fourth_thing &amp;&amp;
 
4015
            yet_another &amp;&amp; last_one) {
 
4016
          ...
 
4017
        }
 
4018
      </CODE_SNIPPET>
 
4019
      <p>
 
4020
        Note that when the code wraps in this example, both of
 
4021
        the <code>&amp;&amp;</code> logical AND operators are at the
 
4022
        end of the line.  Feel free to insert extra parentheses judiciously,
 
4023
        because they can be very helpful in increasing readability
 
4024
        when used appropriately.  Also note that you should always use the
 
4025
        punctuation operators, such as <code>&amp;&amp;</code> and
 
4026
        <code>~</code>, rather than the word operators, such as <code>and</code>
 
4027
        and <code>compl</code>.
 
4028
      </p>
 
4029
    </BODY>
 
4030
  </STYLEPOINT>
 
4031
 
 
4032
  <STYLEPOINT title="Return Values">
 
4033
    <SUMMARY>
 
4034
      Do not needlessly surround the <code>return</code> expression with
 
4035
      parentheses.
 
4036
    </SUMMARY>
 
4037
    <BODY>
 
4038
      <p>
 
4039
        Use parentheses in <code>return expr;</code> only where you would use
 
4040
        them in <code>x = expr;</code>.
 
4041
      </p>
 
4042
      <CODE_SNIPPET>
 
4043
        return result;                  // No parentheses in the simple case.
 
4044
        return (some_long_condition &amp;&amp;  // Parentheses ok to make a complex
 
4045
                another_condition);     //     expression more readable.
 
4046
      </CODE_SNIPPET>
 
4047
      <BAD_CODE_SNIPPET>
 
4048
        return (value);                // You wouldn't write var = (value);
 
4049
        return(result);                // return is not a function!
 
4050
      </BAD_CODE_SNIPPET>
 
4051
    </BODY>
 
4052
  </STYLEPOINT>
 
4053
 
 
4054
 
 
4055
 
 
4056
  <STYLEPOINT title="Variable and Array Initialization">
 
4057
    <SUMMARY>
 
4058
      Your choice of <code>=</code> or <code>()</code>.
 
4059
    </SUMMARY>
 
4060
    <BODY>
 
4061
      <p>
 
4062
        You may choose between <code>=</code> and <code>()</code>; the
 
4063
        following are all correct:
 
4064
      </p>
 
4065
      <CODE_SNIPPET>
 
4066
        int x = 3;
 
4067
        int x(3);
 
4068
        string name("Some Name");
 
4069
        string name = "Some Name";
 
4070
      </CODE_SNIPPET>
 
4071
    </BODY>
 
4072
  </STYLEPOINT>
 
4073
 
 
4074
  <STYLEPOINT title="Preprocessor Directives">
 
4075
    <SUMMARY>
 
4076
      The hash mark that starts a preprocessor directive should
 
4077
      always be at the beginning of the line.
 
4078
    </SUMMARY>
 
4079
    <BODY>
 
4080
      <p>
 
4081
        Even when preprocessor directives are within the body of
 
4082
        indented code, the directives should start at the beginning of
 
4083
        the line.
 
4084
      </p>
 
4085
      <CODE_SNIPPET>
 
4086
        // Good - directives at beginning of line
 
4087
          if (lopsided_score) {
 
4088
        #if DISASTER_PENDING      // Correct -- Starts at beginning of line
 
4089
            DropEverything();
 
4090
        # if NOTIFY               // OK but not required -- Spaces after #
 
4091
            NotifyClient();
 
4092
        # endif
 
4093
        #endif
 
4094
            BackToNormal();
 
4095
          }
 
4096
      </CODE_SNIPPET>
 
4097
      <BAD_CODE_SNIPPET>
 
4098
        // Bad - indented directives
 
4099
          if (lopsided_score) {
 
4100
            #if DISASTER_PENDING  // Wrong!  The "#if" should be at beginning of line
 
4101
            DropEverything();
 
4102
            #endif                // Wrong!  Do not indent "#endif"
 
4103
            BackToNormal();
 
4104
          }
 
4105
      </BAD_CODE_SNIPPET>
 
4106
    </BODY>
 
4107
  </STYLEPOINT>
 
4108
 
 
4109
  <STYLEPOINT title="Class Format">
 
4110
    <SUMMARY>
 
4111
      Sections in <code>public</code>, <code>protected</code> and
 
4112
      <code>private</code> order, each indented one space.
 
4113
    </SUMMARY>
 
4114
    <BODY>
 
4115
      <p>
 
4116
        The basic format for a class declaration (lacking the
 
4117
        comments, see <a HREF="#Class_Comments">Class Comments</a> for
 
4118
        a discussion of what comments are needed) is:
 
4119
      </p>
 
4120
      <CODE_SNIPPET>
 
4121
        class MyClass : public OtherClass {
 
4122
         public:      // Note the 1 space indent!
 
4123
          MyClass();  // Regular 2 space indent.
 
4124
          explicit MyClass(int var);
 
4125
          ~MyClass() {}
 
4126
 
 
4127
          void SomeFunction();
 
4128
          void SomeFunctionThatDoesNothing() {
 
4129
          }
 
4130
 
 
4131
          void set_some_var(int var) { some_var_ = var; }
 
4132
          int some_var() const { return some_var_; }
 
4133
 
 
4134
         private:
 
4135
          bool SomeInternalFunction();
 
4136
 
 
4137
          int some_var_;
 
4138
          int some_other_var_;
 
4139
          DISALLOW_COPY_AND_ASSIGN(MyClass);
 
4140
        };
 
4141
      </CODE_SNIPPET>
 
4142
      <p>
 
4143
        Things to note:
 
4144
      </p>
 
4145
      <ul>
 
4146
        <li> Any base class name should be on the same line as the
 
4147
             subclass name, subject to the 80-column limit.
 
4148
             </li>
 
4149
        <li> The <code>public:</code>, <code>protected:</code>, and
 
4150
             <code>private:</code> keywords should be indented one
 
4151
             space.
 
4152
             </li>
 
4153
        <li> Except for the first instance, these keywords should be preceded
 
4154
             by a blank line. This rule is optional in small classes.
 
4155
             </li>
 
4156
        <li> Do not leave a blank line after these keywords.
 
4157
             </li>
 
4158
        <li> The <code>public</code> section should be first, followed by
 
4159
             the <code>protected</code> and finally the
 
4160
             <code>private</code> section.
 
4161
             </li>
 
4162
        <li> See <a HREF="#Declaration_Order">Declaration Order</a> for
 
4163
             rules on ordering declarations within each of these sections.
 
4164
             </li>
 
4165
      </ul>
 
4166
    </BODY>
 
4167
  </STYLEPOINT>
 
4168
 
 
4169
  <STYLEPOINT title="Constructor Initializer Lists">
 
4170
    <SUMMARY>
 
4171
      Constructor initializer lists can be all on one line or with
 
4172
      subsequent lines indented four spaces.
 
4173
    </SUMMARY>
 
4174
    <BODY>
 
4175
      <p>
 
4176
        There are two acceptable formats for initializer lists:
 
4177
      </p>
 
4178
      <CODE_SNIPPET>
 
4179
        // When it all fits on one line:
 
4180
        MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {}
 
4181
      </CODE_SNIPPET>
 
4182
      <p>
 
4183
        or
 
4184
      </p>
 
4185
      <CODE_SNIPPET>
 
4186
        // When it requires multiple lines, indent 4 spaces, putting the colon on
 
4187
        // the first initializer line:
 
4188
        MyClass::MyClass(int var)
 
4189
            : some_var_(var),             // 4 space indent
 
4190
              some_other_var_(var + 1) {  // lined up
 
4191
          ...
 
4192
          DoSomething();
 
4193
          ...
 
4194
        }
 
4195
      </CODE_SNIPPET>
 
4196
    </BODY>
 
4197
  </STYLEPOINT>
 
4198
 
 
4199
  <STYLEPOINT title="Namespace Formatting">
 
4200
    <SUMMARY>
 
4201
      The contents of namespaces are not indented.
 
4202
    </SUMMARY>
 
4203
    <BODY>
 
4204
      <p>
 
4205
        <a href="#Namespaces">Namespaces</a> do not add an extra level of
 
4206
        indentation. For example, use:
 
4207
      </p>
 
4208
      <CODE_SNIPPET>
 
4209
        namespace {
 
4210
 
 
4211
        void foo() {  // Correct.  No extra indentation within namespace.
 
4212
          ...
 
4213
        }
 
4214
 
 
4215
        }  // namespace
 
4216
      </CODE_SNIPPET>
 
4217
      <p>
 
4218
        Do not indent within a namespace:
 
4219
      </p>
 
4220
      <BAD_CODE_SNIPPET>
 
4221
        namespace {
 
4222
 
 
4223
          // Wrong.  Indented when it should not be.
 
4224
          void foo() {
 
4225
            ...
 
4226
          }
 
4227
 
 
4228
        }  // namespace
 
4229
      </BAD_CODE_SNIPPET>
 
4230
      <p>
 
4231
        When declaring nested namespaces, put each namespace on its own line.
 
4232
      </p>
 
4233
      <CODE_SNIPPET>
 
4234
        namespace foo {
 
4235
        namespace bar {
 
4236
      </CODE_SNIPPET>
 
4237
    </BODY>
 
4238
  </STYLEPOINT>
 
4239
 
 
4240
  <STYLEPOINT title="Horizontal Whitespace">
 
4241
    <SUMMARY>
 
4242
      Use of horizontal whitespace depends on location.  Never put trailing
 
4243
      whitespace at the end of a line.
 
4244
    </SUMMARY>
 
4245
    <BODY>
 
4246
      <SUBSECTION title="General">
 
4247
        <CODE_SNIPPET>
 
4248
        void f(bool b) {  // Open braces should always have a space before them.
 
4249
          ...
 
4250
        int i = 0;  // Semicolons usually have no space before them.
 
4251
        int x[] = { 0 };  // Spaces inside braces for array initialization are
 
4252
        int x[] = {0};    // optional.  If you use them, put them on both sides!
 
4253
        // Spaces around the colon in inheritance and initializer lists.
 
4254
        class Foo : public Bar {
 
4255
         public:
 
4256
          // For inline function implementations, put spaces between the braces
 
4257
          // and the implementation itself.
 
4258
          Foo(int b) : Bar(), baz_(b) {}  // No spaces inside empty braces.
 
4259
          void Reset() { baz_ = 0; }  // Spaces separating braces from implementation.
 
4260
          ...
 
4261
        </CODE_SNIPPET>
 
4262
        <p>
 
4263
          Adding trailing whitespace can cause extra work for others editing
 
4264
          the same file, when they merge, as can removing existing trailing
 
4265
          whitespace.  So:  Don't introduce trailing whitespace.  Remove it
 
4266
          if you're already changing that line, or do it in a separate
 
4267
          clean-up
 
4268
 
 
4269
          operation (preferably when no-one else
 
4270
          is working on the file).
 
4271
        </p>
 
4272
      </SUBSECTION>
 
4273
      <SUBSECTION title="Loops and Conditionals">
 
4274
        <CODE_SNIPPET>
 
4275
        if (b) {          // Space after the keyword in conditions and loops.
 
4276
        } else {          // Spaces around else.
 
4277
        }
 
4278
        while (test) {}   // There is usually no space inside parentheses.
 
4279
        switch (i) {
 
4280
        for (int i = 0; i &lt; 5; ++i) {
 
4281
        switch ( i ) {    // Loops and conditions may have spaces inside
 
4282
        if ( test ) {     // parentheses, but this is rare.  Be consistent.
 
4283
        for ( int i = 0; i &lt; 5; ++i ) {
 
4284
        for ( ; i &lt; 5 ; ++i) {  // For loops always have a space after the
 
4285
          ...                   // semicolon, and may have a space before the
 
4286
                                // semicolon.
 
4287
        switch (i) {
 
4288
          case 1:         // No space before colon in a switch case.
 
4289
            ...
 
4290
          case 2: break;  // Use a space after a colon if there's code after it.
 
4291
        </CODE_SNIPPET>
 
4292
      </SUBSECTION>
 
4293
      <SUBSECTION title="Operators">
 
4294
        <CODE_SNIPPET>
 
4295
        x = 0;              // Assignment operators always have spaces around
 
4296
                            // them.
 
4297
        x = -5;             // No spaces separating unary operators and their
 
4298
        ++x;                // arguments.
 
4299
        if (x &amp;&amp; !y)
 
4300
          ...
 
4301
        v = w * x + y / z;  // Binary operators usually have spaces around them,
 
4302
        v = w*x + y/z;      // but it's okay to remove spaces around factors.
 
4303
        v = w * (x + z);    // Parentheses should have no spaces inside them.
 
4304
        </CODE_SNIPPET>
 
4305
      </SUBSECTION>
 
4306
      <SUBSECTION title="Templates and Casts">
 
4307
        <CODE_SNIPPET>
 
4308
        vector&lt;string&gt; x;           // No spaces inside the angle
 
4309
        y = static_cast&lt;char*&gt;(x);  // brackets (&lt; and &gt;), before
 
4310
                                    // &lt;, or between &gt;( in a cast.
 
4311
        vector&lt;char *&gt; x;           // Spaces between type and pointer are
 
4312
                                    // okay, but be consistent.
 
4313
        set&lt;list&lt;string&gt; &gt; x;       // C++ requires a space in &gt; &gt;.
 
4314
        set&lt; list&lt;string&gt; &gt; x;      // You may optionally use
 
4315
                                    // symmetric spacing in &lt; &lt;.
 
4316
        </CODE_SNIPPET>
 
4317
      </SUBSECTION>
 
4318
    </BODY>
 
4319
  </STYLEPOINT>
 
4320
 
 
4321
 
 
4322
  <STYLEPOINT title="Vertical Whitespace">
 
4323
    <SUMMARY>
 
4324
      Minimize use of vertical whitespace.
 
4325
    </SUMMARY>
 
4326
    <BODY>
 
4327
      <p>
 
4328
        This is more a principle than a rule: don't use blank lines
 
4329
        when you don't have to.  In particular, don't put more than
 
4330
        one or two blank lines between functions, resist starting
 
4331
        functions with a blank line, don't end functions with a blank
 
4332
        line, and be discriminating with your use of blank lines
 
4333
        inside functions.
 
4334
      </p>
 
4335
      <p>
 
4336
        The basic principle is: The more code that fits on one screen,
 
4337
        the easier it is to follow and understand the control flow of
 
4338
        the program.  Of course, readability can suffer from code
 
4339
        being too dense as well as too spread out, so use your
 
4340
        judgement.  But in general, minimize use of vertical
 
4341
        whitespace.
 
4342
      </p>
 
4343
      <p>
 
4344
        Some rules of thumb to help when blank lines may be useful:
 
4345
      </p>
 
4346
      <ul>
 
4347
        <li> Blank lines at the beginning or end of a function very
 
4348
             rarely help readability.
 
4349
             </li>
 
4350
        <li> Blank lines inside a chain of if-else blocks may well
 
4351
             help readability.
 
4352
             </li>
 
4353
      </ul>
 
4354
    </BODY>
 
4355
  </STYLEPOINT>
 
4356
</CATEGORY>
 
4357
 
 
4358
<CATEGORY title="Exceptions to the Rules">
 
4359
  <p>
 
4360
    The coding conventions described above are mandatory.  However,
 
4361
    like all good rules, these sometimes have exceptions, which we
 
4362
    discuss here.
 
4363
  </p>
 
4364
 
 
4365
 
 
4366
 
 
4367
  <STYLEPOINT title="Existing Non-conformant Code">
 
4368
    <SUMMARY>
 
4369
      You may diverge from the rules when dealing with code that does not
 
4370
      conform to this style guide.
 
4371
    </SUMMARY>
 
4372
    <BODY>
 
4373
      <p>
 
4374
        If you find yourself modifying code that was written to
 
4375
        specifications other than those presented by this guide, you may
 
4376
        have to diverge from these rules in order to stay consistent with
 
4377
        the local conventions in that code.  If you are in doubt about
 
4378
        how to do this, ask the original author or the person currently
 
4379
        responsible for the code.  Remember that <em>consistency</em>
 
4380
        includes local consistency, too.
 
4381
      </p>
 
4382
    </BODY>
 
4383
  </STYLEPOINT>
 
4384
 
 
4385
</CATEGORY>
 
4386
 
 
4387
<PARTING_WORDS>
 
4388
  <p>
 
4389
    Use common sense and <em>BE CONSISTENT</em>.
 
4390
  </p>
 
4391
  <p>
 
4392
    If you are editing code, take a few minutes to look at the
 
4393
    code around you and determine its style. If they use spaces
 
4394
    around their <code>if</code> clauses, you should, too. If
 
4395
    their comments have little boxes of stars around them, make
 
4396
    your comments have little boxes of stars around them too.
 
4397
  </p>
 
4398
  <p>
 
4399
    The point of having style guidelines is to have a common
 
4400
    vocabulary of coding so people can concentrate on what you are
 
4401
    saying, rather than on how you are saying it.  We present
 
4402
    global style rules here so people know the vocabulary. But
 
4403
    local style is also important.  If code you add to a file
 
4404
    looks drastically different from the existing code around it,
 
4405
    the discontinuity throws readers out of their rhythm when they
 
4406
    go to read it. Try to avoid this.
 
4407
  </p>
 
4408
 
 
4409
  <p>
 
4410
    OK, enough writing about writing code; the code itself is much
 
4411
    more interesting. Have fun!
 
4412
  </p>
 
4413
</PARTING_WORDS>
 
4414
 
 
4415
</GUIDE>