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