Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1 | <!DOCTYPE html> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2 | <html lang="en"> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3 | <head> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4 | <meta charset="utf-8"> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5 | <title>Google C++ Style Guide</title> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 6 | <link rel="stylesheet" href="include/styleguide.css"> |
| 7 | <script src="include/styleguide.js"></script> |
| 8 | <link rel="shortcut icon" href="https://www.google.com/favicon.ico"> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 9 | </head> |
| 10 | <body onload="initStyleGuide();"> |
| 11 | <div id="content"> |
| 12 | <h1>Google C++ Style Guide</h1> |
Tom Manshreck | 63107a1 | 2018-08-14 16:12:59 -0400 | [diff] [blame] | 13 | <div class="horizontal_toc" id="tocDiv"></div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 14 | <div class="main_body"> |
| 15 | |
| 16 | <h2 class="ignoreLink" id="Background">Background</h2> |
| 17 | |
| 18 | <p>C++ is one of the main development languages used by |
| 19 | many of Google's open-source projects. As every C++ |
| 20 | programmer knows, the language has many powerful features, but |
| 21 | this power brings with it complexity, which in turn can make |
| 22 | code more bug-prone and harder to read and maintain.</p> |
| 23 | |
| 24 | <p>The goal of this guide is to manage this complexity by |
| 25 | describing in detail the dos and don'ts of writing C++ code. |
| 26 | These rules exist to |
| 27 | keep the code base manageable while still allowing |
| 28 | coders to use C++ language features productively.</p> |
| 29 | |
| 30 | <p><em>Style</em>, also known as readability, is what we call |
| 31 | the conventions that govern our C++ code. The term Style is a |
| 32 | bit of a misnomer, since these conventions cover far more than |
| 33 | just source file formatting.</p> |
| 34 | |
| 35 | <p> |
| 36 | Most open-source projects developed by |
| 37 | Google conform to the requirements in this guide. |
| 38 | </p> |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | <p>Note that this guide is not a C++ tutorial: we assume that |
| 45 | the reader is familiar with the language. </p> |
| 46 | |
| 47 | <h3 id="Goals">Goals of the Style Guide</h3> |
| 48 | <div class="stylebody"> |
| 49 | <p>Why do we have this document?</p> |
| 50 | |
| 51 | <p>There are a few core goals that we believe this guide should |
| 52 | serve. These are the fundamental <b>why</b>s that |
| 53 | underlie all of the individual rules. By bringing these ideas to |
| 54 | the fore, we hope to ground discussions and make it clearer to our |
| 55 | broader community why the rules are in place and why particular |
| 56 | decisions have been made. If you understand what goals each rule is |
| 57 | serving, it should be clearer to everyone when a rule may be waived |
| 58 | (some can be), and what sort of argument or alternative would be |
| 59 | necessary to change a rule in the guide.</p> |
| 60 | |
| 61 | <p>The goals of the style guide as we currently see them are as follows:</p> |
| 62 | <dl> |
| 63 | <dt>Style rules should pull their weight</dt> |
| 64 | <dd>The benefit of a style rule |
| 65 | must be large enough to justify asking all of our engineers to |
| 66 | remember it. The benefit is measured relative to the codebase we would |
| 67 | get without the rule, so a rule against a very harmful practice may |
| 68 | still have a small benefit if people are unlikely to do it |
| 69 | anyway. This principle mostly explains the rules we don’t have, rather |
| 70 | than the rules we do: for example, <code>goto</code> contravenes many |
| 71 | of the following principles, but is already vanishingly rare, so the Style |
| 72 | Guide doesn’t discuss it.</dd> |
| 73 | |
| 74 | <dt>Optimize for the reader, not the writer</dt> |
| 75 | <dd>Our codebase (and most individual components submitted to it) is |
| 76 | expected to continue for quite some time. As a result, more time will |
| 77 | be spent reading most of our code than writing it. We explicitly |
| 78 | choose to optimize for the experience of our average software engineer |
| 79 | reading, maintaining, and debugging code in our codebase rather than |
| 80 | ease when writing said code. "Leave a trace for the reader" is a |
| 81 | particularly common sub-point of this principle: When something |
| 82 | surprising or unusual is happening in a snippet of code (for example, |
| 83 | transfer of pointer ownership), leaving textual hints for the reader |
| 84 | at the point of use is valuable (<code>std::unique_ptr</code> |
| 85 | demonstrates the ownership transfer unambiguously at the call |
| 86 | site). </dd> |
| 87 | |
| 88 | <dt>Be consistent with existing code</dt> |
| 89 | <dd>Using one style consistently through our codebase lets us focus on |
| 90 | other (more important) issues. Consistency also allows for |
| 91 | automation: tools that format your code or adjust |
| 92 | your <code>#include</code>s only work properly when your code is |
| 93 | consistent with the expectations of the tooling. In many cases, rules |
| 94 | that are attributed to "Be Consistent" boil down to "Just pick one and |
| 95 | stop worrying about it"; the potential value of allowing flexibility |
| 96 | on these points is outweighed by the cost of having people argue over |
| 97 | them. </dd> |
| 98 | |
| 99 | <dt>Be consistent with the broader C++ community when appropriate</dt> |
| 100 | <dd>Consistency with the way other organizations use C++ has value for |
| 101 | the same reasons as consistency within our code base. If a feature in |
| 102 | the C++ standard solves a problem, or if some idiom is widely known |
| 103 | and accepted, that's an argument for using it. However, sometimes |
| 104 | standard features and idioms are flawed, or were just designed without |
| 105 | our codebase's needs in mind. In those cases (as described below) it's |
| 106 | appropriate to constrain or ban standard features. In some cases we |
| 107 | prefer a homegrown or third-party library over a library defined in |
| 108 | the C++ Standard, either out of perceived superiority or insufficient |
| 109 | value to transition the codebase to the standard interface.</dd> |
| 110 | |
| 111 | <dt>Avoid surprising or dangerous constructs</dt> |
| 112 | <dd>C++ has features that are more surprising or dangerous than one |
| 113 | might think at a glance. Some style guide restrictions are in place to |
| 114 | prevent falling into these pitfalls. There is a high bar for style |
| 115 | guide waivers on such restrictions, because waiving such rules often |
| 116 | directly risks compromising program correctness. |
| 117 | </dd> |
| 118 | |
| 119 | <dt>Avoid constructs that our average C++ programmer would find tricky |
| 120 | or hard to maintain</dt> |
| 121 | <dd>C++ has features that may not be generally appropriate because of |
| 122 | the complexity they introduce to the code. In widely used |
| 123 | code, it may be more acceptable to use |
| 124 | trickier language constructs, because any benefits of more complex |
| 125 | implementation are multiplied widely by usage, and the cost in understanding |
| 126 | the complexity does not need to be paid again when working with new |
| 127 | portions of the codebase. When in doubt, waivers to rules of this type |
| 128 | can be sought by asking |
| 129 | your project leads. This is specifically |
| 130 | important for our codebase because code ownership and team membership |
| 131 | changes over time: even if everyone that works with some piece of code |
| 132 | currently understands it, such understanding is not guaranteed to hold a |
| 133 | few years from now.</dd> |
| 134 | |
| 135 | <dt>Be mindful of our scale</dt> |
| 136 | <dd>With a codebase of 100+ million lines and thousands of engineers, |
| 137 | some mistakes and simplifications for one engineer can become costly |
| 138 | for many. For instance it's particularly important to |
| 139 | avoid polluting the global namespace: name collisions across a |
| 140 | codebase of hundreds of millions of lines are difficult to work with |
| 141 | and hard to avoid if everyone puts things into the global |
| 142 | namespace.</dd> |
| 143 | |
| 144 | <dt>Concede to optimization when necessary</dt> |
| 145 | <dd>Performance optimizations can sometimes be necessary and |
| 146 | appropriate, even when they conflict with the other principles of this |
| 147 | document.</dd> |
| 148 | </dl> |
| 149 | |
| 150 | <p>The intent of this document is to provide maximal guidance with |
| 151 | reasonable restriction. As always, common sense and good taste should |
| 152 | prevail. By this we specifically refer to the established conventions |
| 153 | of the entire Google C++ community, not just your personal preferences |
| 154 | or those of your team. Be skeptical about and reluctant to use |
| 155 | clever or unusual constructs: the absence of a prohibition is not the |
| 156 | same as a license to proceed. Use your judgment, and if you are |
| 157 | unsure, please don't hesitate to ask your project leads to get additional |
| 158 | input.</p> |
| 159 | |
| 160 | </div> |
| 161 | |
| 162 | |
| 163 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 164 | <h2 id="C++_Version">C++ Version</h2> |
| 165 | |
| 166 | <p> |
| 167 | Currently, code should target C++11, i.e., should not use C++14 or |
| 168 | C++17 features. The C++ version targeted by this guide will advance |
| 169 | (aggressively) over time.</p> |
| 170 | |
| 171 | <p> |
| 172 | Code should avoid features that have been removed from |
| 173 | the latest language version (currently C++17), as well as the rare |
| 174 | cases where code has a different meaning in that latest version. |
| 175 | Use of some C++ features is restricted or disallowed. Do not use |
| 176 | <a href="#Nonstandard_Extensions">non-standard extensions</a>.</p> |
| 177 | |
| 178 | |
| 179 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 180 | <h2 id="Header_Files">Header Files</h2> |
| 181 | |
| 182 | <p>In general, every <code>.cc</code> file should have an |
| 183 | associated <code>.h</code> file. There are some common |
| 184 | exceptions, such as unittests and |
| 185 | small <code>.cc</code> files containing just a |
| 186 | <code>main()</code> function.</p> |
| 187 | |
| 188 | <p>Correct use of header files can make a huge difference to |
| 189 | the readability, size and performance of your code.</p> |
| 190 | |
| 191 | <p>The following rules will guide you through the various |
| 192 | pitfalls of using header files.</p> |
| 193 | |
| 194 | <a id="The_-inl.h_Files"></a> |
| 195 | <h3 id="Self_contained_Headers">Self-contained Headers</h3> |
| 196 | |
| 197 | <div class="summary"> |
| 198 | <p>Header files should be self-contained (compile on their own) and |
| 199 | end in <code>.h</code>. Non-header files that are meant for inclusion |
| 200 | should end in <code>.inc</code> and be used sparingly.</p> |
| 201 | </div> |
| 202 | |
| 203 | <div class="stylebody"> |
| 204 | <p>All header files should be self-contained. Users and refactoring |
| 205 | tools should not have to adhere to special conditions to include the |
| 206 | header. Specifically, a header should |
| 207 | have <a href="#The__define_Guard">header guards</a> and include all |
| 208 | other headers it needs.</p> |
| 209 | |
| 210 | <p>Prefer placing the definitions for template and inline functions in |
| 211 | the same file as their declarations. The definitions of these |
| 212 | constructs must be included into every <code>.cc</code> file that uses |
| 213 | them, or the program may fail to link in some build configurations. If |
| 214 | declarations and definitions are in different files, including the |
| 215 | former should transitively include the latter. Do not move these |
| 216 | definitions to separately included header files (<code>-inl.h</code>); |
| 217 | this practice was common in the past, but is no longer allowed.</p> |
| 218 | |
| 219 | <p>As an exception, a template that is explicitly instantiated for |
| 220 | all relevant sets of template arguments, or that is a private |
| 221 | implementation detail of a class, is allowed to be defined in the one |
| 222 | and only <code>.cc</code> file that instantiates the template.</p> |
| 223 | |
| 224 | <p>There are rare cases where a file designed to be included is not |
| 225 | self-contained. These are typically intended to be included at unusual |
| 226 | locations, such as the middle of another file. They might not |
| 227 | use <a href="#The__define_Guard">header guards</a>, and might not include |
| 228 | their prerequisites. Name such files with the <code>.inc</code> |
| 229 | extension. Use sparingly, and prefer self-contained headers when |
| 230 | possible.</p> |
| 231 | |
| 232 | </div> |
| 233 | |
| 234 | <h3 id="The__define_Guard">The #define Guard</h3> |
| 235 | |
| 236 | <div class="summary"> |
| 237 | <p>All header files should have <code>#define</code> guards to |
| 238 | prevent multiple inclusion. The format of the symbol name |
| 239 | should be |
| 240 | <code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.</p> |
| 241 | </div> |
| 242 | |
| 243 | <div class="stylebody"> |
| 244 | |
| 245 | |
| 246 | |
| 247 | <p>To guarantee uniqueness, they should |
| 248 | be based on the full path in a project's source tree. For |
| 249 | example, the file <code>foo/src/bar/baz.h</code> in |
| 250 | project <code>foo</code> should have the following |
| 251 | guard:</p> |
| 252 | |
| 253 | <pre>#ifndef FOO_BAR_BAZ_H_ |
| 254 | #define FOO_BAR_BAZ_H_ |
| 255 | |
| 256 | ... |
| 257 | |
| 258 | #endif // FOO_BAR_BAZ_H_ |
| 259 | </pre> |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | </div> |
| 265 | |
| 266 | <h3 id="Forward_Declarations">Forward Declarations</h3> |
| 267 | |
| 268 | <div class="summary"> |
| 269 | <p>Avoid using forward declarations where possible. |
| 270 | Just <code>#include</code> the headers you need.</p> |
| 271 | </div> |
| 272 | |
| 273 | <div class="stylebody"> |
| 274 | |
| 275 | <div class="definition"> |
| 276 | <p>A "forward declaration" is a declaration of a class, |
| 277 | function, or template without an associated definition.</p> |
| 278 | </div> |
| 279 | |
| 280 | <div class="pros"> |
| 281 | <ul> |
| 282 | <li>Forward declarations can save compile time, as |
| 283 | <code>#include</code>s force the compiler to open |
| 284 | more files and process more input.</li> |
| 285 | |
| 286 | <li>Forward declarations can save on unnecessary |
| 287 | recompilation. <code>#include</code>s can force |
| 288 | your code to be recompiled more often, due to unrelated |
| 289 | changes in the header.</li> |
| 290 | </ul> |
| 291 | </div> |
| 292 | |
| 293 | <div class="cons"> |
| 294 | <ul> |
| 295 | <li>Forward declarations can hide a dependency, allowing |
| 296 | user code to skip necessary recompilation when headers |
| 297 | change.</li> |
| 298 | |
| 299 | <li>A forward declaration may be broken by subsequent |
| 300 | changes to the library. Forward declarations of functions |
| 301 | and templates can prevent the header owners from making |
| 302 | otherwise-compatible changes to their APIs, such as |
| 303 | widening a parameter type, adding a template parameter |
| 304 | with a default value, or migrating to a new namespace.</li> |
| 305 | |
| 306 | <li>Forward declaring symbols from namespace |
| 307 | <code>std::</code> yields undefined behavior.</li> |
| 308 | |
| 309 | <li>It can be difficult to determine whether a forward |
| 310 | declaration or a full <code>#include</code> is needed. |
| 311 | Replacing an <code>#include</code> with a forward |
| 312 | declaration can silently change the meaning of |
| 313 | code: |
| 314 | <pre> // b.h: |
| 315 | struct B {}; |
| 316 | struct D : B {}; |
| 317 | |
| 318 | // good_user.cc: |
| 319 | #include "b.h" |
| 320 | void f(B*); |
| 321 | void f(void*); |
| 322 | void test(D* x) { f(x); } // calls f(B*) |
| 323 | </pre> |
| 324 | If the <code>#include</code> was replaced with forward |
| 325 | decls for <code>B</code> and <code>D</code>, |
| 326 | <code>test()</code> would call <code>f(void*)</code>. |
| 327 | </li> |
| 328 | |
| 329 | <li>Forward declaring multiple symbols from a header |
| 330 | can be more verbose than simply |
| 331 | <code>#include</code>ing the header.</li> |
| 332 | |
| 333 | <li>Structuring code to enable forward declarations |
| 334 | (e.g. using pointer members instead of object members) |
| 335 | can make the code slower and more complex.</li> |
| 336 | |
| 337 | |
| 338 | </ul> |
| 339 | </div> |
| 340 | |
| 341 | <div class="decision"> |
| 342 | <ul> |
| 343 | <li>Try to avoid forward declarations of entities |
| 344 | defined in another project.</li> |
| 345 | |
| 346 | <li>When using a function declared in a header file, |
| 347 | always <code>#include</code> that header.</li> |
| 348 | |
| 349 | <li>When using a class template, prefer to |
| 350 | <code>#include</code> its header file.</li> |
| 351 | </ul> |
| 352 | |
| 353 | <p>Please see <a href="#Names_and_Order_of_Includes">Names and Order |
| 354 | of Includes</a> for rules about when to #include a header.</p> |
| 355 | </div> |
| 356 | |
| 357 | </div> |
| 358 | |
| 359 | <h3 id="Inline_Functions">Inline Functions</h3> |
| 360 | |
| 361 | <div class="summary"> |
| 362 | <p>Define functions inline only when they are small, say, 10 |
| 363 | lines or fewer.</p> |
| 364 | </div> |
| 365 | |
| 366 | <div class="stylebody"> |
| 367 | |
| 368 | <div class="definition"> |
| 369 | <p>You can declare functions in a way that allows the compiler to expand |
| 370 | them inline rather than calling them through the usual |
| 371 | function call mechanism.</p> |
| 372 | </div> |
| 373 | |
| 374 | <div class="pros"> |
| 375 | <p>Inlining a function can generate more efficient object |
| 376 | code, as long as the inlined function is small. Feel free |
| 377 | to inline accessors and mutators, and other short, |
| 378 | performance-critical functions.</p> |
| 379 | </div> |
| 380 | |
| 381 | <div class="cons"> |
| 382 | <p>Overuse of inlining can actually make programs slower. |
| 383 | Depending on a function's size, inlining it can cause the |
| 384 | code size to increase or decrease. Inlining a very small |
| 385 | accessor function will usually decrease code size while |
| 386 | inlining a very large function can dramatically increase |
| 387 | code size. On modern processors smaller code usually runs |
| 388 | faster due to better use of the instruction cache.</p> |
| 389 | </div> |
| 390 | |
| 391 | <div class="decision"> |
| 392 | <p>A decent rule of thumb is to not inline a function if |
| 393 | it is more than 10 lines long. Beware of destructors, |
| 394 | which are often longer than they appear because of |
| 395 | implicit member- and base-destructor calls!</p> |
| 396 | |
| 397 | <p>Another useful rule of thumb: it's typically not cost |
| 398 | effective to inline functions with loops or switch |
| 399 | statements (unless, in the common case, the loop or |
| 400 | switch statement is never executed).</p> |
| 401 | |
| 402 | <p>It is important to know that functions are not always |
| 403 | inlined even if they are declared as such; for example, |
| 404 | virtual and recursive functions are not normally inlined. |
| 405 | Usually recursive functions should not be inline. The |
| 406 | main reason for making a virtual function inline is to |
| 407 | place its definition in the class, either for convenience |
| 408 | or to document its behavior, e.g., for accessors and |
| 409 | mutators.</p> |
| 410 | </div> |
| 411 | |
| 412 | </div> |
| 413 | |
| 414 | <h3 id="Names_and_Order_of_Includes">Names and Order of Includes</h3> |
| 415 | |
| 416 | <div class="summary"> |
| 417 | <p>Use standard order for readability and to avoid hidden |
| 418 | dependencies: Related header, C library, C++ library, other libraries' |
| 419 | <code>.h</code>, your project's <code>.h</code>.</p> |
| 420 | </div> |
| 421 | |
| 422 | <div class="stylebody"> |
| 423 | <p> |
| 424 | All of a project's header files should be |
| 425 | listed as descendants of the project's source |
| 426 | directory without use of UNIX directory shortcuts |
| 427 | <code>.</code> (the current directory) or <code>..</code> |
| 428 | (the parent directory). For example, |
| 429 | |
| 430 | <code>google-awesome-project/src/base/logging.h</code> |
| 431 | should be included as:</p> |
| 432 | |
| 433 | <pre>#include "base/logging.h" |
| 434 | </pre> |
| 435 | |
| 436 | <p>In <code><var>dir/foo</var>.cc</code> or |
| 437 | <code><var>dir/foo_test</var>.cc</code>, whose main |
| 438 | purpose is to implement or test the stuff in |
| 439 | <code><var>dir2/foo2</var>.h</code>, order your includes |
| 440 | as follows:</p> |
| 441 | |
| 442 | <ol> |
| 443 | <li><code><var>dir2/foo2</var>.h</code>.</li> |
| 444 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 445 | <li>A blank line</li> |
| 446 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 447 | <li>C system files.</li> |
| 448 | |
| 449 | <li>C++ system files.</li> |
| 450 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 451 | <li>A blank line</li> |
| 452 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 453 | <li>Other libraries' <code>.h</code> |
| 454 | files.</li> |
| 455 | |
| 456 | <li> |
| 457 | Your project's <code>.h</code> |
| 458 | files.</li> |
| 459 | </ol> |
| 460 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 461 | <p>Note that any adjacent blank lines should be collapsed.</p> |
| 462 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 463 | <p>With the preferred ordering, if |
| 464 | <code><var>dir2/foo2</var>.h</code> omits any necessary |
| 465 | includes, the build of <code><var>dir/foo</var>.cc</code> |
| 466 | or <code><var>dir/foo</var>_test.cc</code> will break. |
| 467 | Thus, this rule ensures that build breaks show up first |
| 468 | for the people working on these files, not for innocent |
| 469 | people in other packages.</p> |
| 470 | |
| 471 | <p><code><var>dir/foo</var>.cc</code> and |
| 472 | <code><var>dir2/foo2</var>.h</code> are usually in the same |
| 473 | directory (e.g. <code>base/basictypes_test.cc</code> and |
| 474 | <code>base/basictypes.h</code>), but may sometimes be in different |
| 475 | directories too.</p> |
| 476 | |
| 477 | |
| 478 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 479 | <p>Note that the C compatibility headers such as <code>stddef.h</code> |
| 480 | are essentially interchangeable with their C++ counterparts |
| 481 | (<code>cstddef</code>) |
| 482 | Either style is acceptable, but prefer consistency with existing code.</p> |
| 483 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 484 | <p>Within each section the includes should be ordered |
| 485 | alphabetically. Note that older code might not conform to |
| 486 | this rule and should be fixed when convenient.</p> |
| 487 | |
| 488 | <p>You should include all the headers that define the symbols you rely |
| 489 | upon, except in the unusual case of <a href="#Forward_Declarations">forward |
| 490 | declaration</a>. If you rely on symbols from <code>bar.h</code>, |
| 491 | don't count on the fact that you included <code>foo.h</code> which |
| 492 | (currently) includes <code>bar.h</code>: include <code>bar.h</code> |
| 493 | yourself, unless <code>foo.h</code> explicitly demonstrates its intent |
| 494 | to provide you the symbols of <code>bar.h</code>. However, any |
| 495 | includes present in the related header do not need to be included |
| 496 | again in the related <code>cc</code> (i.e., <code>foo.cc</code> can |
| 497 | rely on <code>foo.h</code>'s includes).</p> |
| 498 | |
| 499 | <p>For example, the includes in |
| 500 | |
| 501 | <code>google-awesome-project/src/foo/internal/fooserver.cc</code> |
| 502 | might look like this:</p> |
| 503 | |
| 504 | |
| 505 | <pre>#include "foo/server/fooserver.h" |
| 506 | |
| 507 | #include <sys/types.h> |
| 508 | #include <unistd.h> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 509 | #include <vector> |
| 510 | |
| 511 | #include "base/basictypes.h" |
| 512 | #include "base/commandlineflags.h" |
| 513 | #include "foo/server/bar.h" |
| 514 | </pre> |
| 515 | |
| 516 | <p class="exception">Sometimes, system-specific code needs |
| 517 | conditional includes. Such code can put conditional |
| 518 | includes after other includes. Of course, keep your |
| 519 | system-specific code small and localized. Example:</p> |
| 520 | |
| 521 | <pre>#include "foo/public/fooserver.h" |
| 522 | |
| 523 | #include "base/port.h" // For LANG_CXX11. |
| 524 | |
| 525 | #ifdef LANG_CXX11 |
| 526 | #include <initializer_list> |
| 527 | #endif // LANG_CXX11 |
| 528 | </pre> |
| 529 | |
| 530 | </div> |
| 531 | |
| 532 | <h2 id="Scoping">Scoping</h2> |
| 533 | |
| 534 | <h3 id="Namespaces">Namespaces</h3> |
| 535 | |
| 536 | <div class="summary"> |
| 537 | <p>With few exceptions, place code in a namespace. Namespaces |
| 538 | should have unique names based on the project name, and possibly |
| 539 | its path. Do not use <i>using-directives</i> (e.g. |
| 540 | <code>using namespace foo</code>). Do not use |
| 541 | inline namespaces. For unnamed namespaces, see |
| 542 | <a href="#Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and |
| 543 | Static Variables</a>. |
| 544 | </p></div> |
| 545 | |
| 546 | <div class="stylebody"> |
| 547 | |
| 548 | <div class="definition"> |
| 549 | <p>Namespaces subdivide the global scope |
| 550 | into distinct, named scopes, and so are useful for preventing |
| 551 | name collisions in the global scope.</p> |
| 552 | </div> |
| 553 | |
| 554 | <div class="pros"> |
| 555 | |
| 556 | <p>Namespaces provide a method for preventing name conflicts |
| 557 | in large programs while allowing most code to use reasonably |
| 558 | short names.</p> |
| 559 | |
| 560 | <p>For example, if two different projects have a class |
| 561 | <code>Foo</code> in the global scope, these symbols may |
| 562 | collide at compile time or at runtime. If each project |
| 563 | places their code in a namespace, <code>project1::Foo</code> |
| 564 | and <code>project2::Foo</code> are now distinct symbols that |
| 565 | do not collide, and code within each project's namespace |
| 566 | can continue to refer to <code>Foo</code> without the prefix.</p> |
| 567 | |
| 568 | <p>Inline namespaces automatically place their names in |
| 569 | the enclosing scope. Consider the following snippet, for |
| 570 | example:</p> |
| 571 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 572 | <pre>namespace outer { |
| 573 | inline namespace inner { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 574 | void foo(); |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 575 | } // namespace inner |
| 576 | } // namespace outer |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 577 | </pre> |
| 578 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 579 | <p>The expressions <code>outer::inner::foo()</code> and |
| 580 | <code>outer::foo()</code> are interchangeable. Inline |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 581 | namespaces are primarily intended for ABI compatibility |
| 582 | across versions.</p> |
| 583 | </div> |
| 584 | |
| 585 | <div class="cons"> |
| 586 | |
| 587 | <p>Namespaces can be confusing, because they complicate |
| 588 | the mechanics of figuring out what definition a name refers |
| 589 | to.</p> |
| 590 | |
| 591 | <p>Inline namespaces, in particular, can be confusing |
| 592 | because names aren't actually restricted to the namespace |
| 593 | where they are declared. They are only useful as part of |
| 594 | some larger versioning policy.</p> |
| 595 | |
| 596 | <p>In some contexts, it's necessary to repeatedly refer to |
| 597 | symbols by their fully-qualified names. For deeply-nested |
| 598 | namespaces, this can add a lot of clutter.</p> |
| 599 | </div> |
| 600 | |
| 601 | <div class="decision"> |
| 602 | |
| 603 | <p>Namespaces should be used as follows:</p> |
| 604 | |
| 605 | <ul> |
| 606 | <li>Follow the rules on <a href="#Namespace_Names">Namespace Names</a>. |
| 607 | </li><li>Terminate namespaces with comments as shown in the given examples. |
| 608 | </li><li> |
| 609 | |
| 610 | <p>Namespaces wrap the entire source file after |
| 611 | includes, |
| 612 | <a href="https://gflags.github.io/gflags/"> |
| 613 | gflags</a> definitions/declarations |
| 614 | and forward declarations of classes from other namespaces.</p> |
| 615 | |
| 616 | <pre>// In the .h file |
| 617 | namespace mynamespace { |
| 618 | |
| 619 | // All declarations are within the namespace scope. |
| 620 | // Notice the lack of indentation. |
| 621 | class MyClass { |
| 622 | public: |
| 623 | ... |
| 624 | void Foo(); |
| 625 | }; |
| 626 | |
| 627 | } // namespace mynamespace |
| 628 | </pre> |
| 629 | |
| 630 | <pre>// In the .cc file |
| 631 | namespace mynamespace { |
| 632 | |
| 633 | // Definition of functions is within scope of the namespace. |
| 634 | void MyClass::Foo() { |
| 635 | ... |
| 636 | } |
| 637 | |
| 638 | } // namespace mynamespace |
| 639 | </pre> |
| 640 | |
| 641 | <p>More complex <code>.cc</code> files might have additional details, |
| 642 | like flags or using-declarations.</p> |
| 643 | |
| 644 | <pre>#include "a.h" |
| 645 | |
| 646 | DEFINE_FLAG(bool, someflag, false, "dummy flag"); |
| 647 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 648 | namespace mynamespace { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 649 | |
| 650 | using ::foo::bar; |
| 651 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 652 | ...code for mynamespace... // Code goes against the left margin. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 653 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 654 | } // namespace mynamespace |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 655 | </pre> |
| 656 | </li> |
| 657 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 658 | <li>To place generated protocol |
| 659 | message code in a namespace, use the |
| 660 | <code>package</code> specifier in the |
| 661 | <code>.proto</code> file. See |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 662 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 663 | <a href="https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#package"> |
| 664 | Protocol Buffer Packages</a> |
| 665 | for details.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 666 | |
| 667 | <li>Do not declare anything in namespace |
| 668 | <code>std</code>, including forward declarations of |
| 669 | standard library classes. Declaring entities in |
| 670 | namespace <code>std</code> is undefined behavior, i.e., |
| 671 | not portable. To declare entities from the standard |
| 672 | library, include the appropriate header file.</li> |
| 673 | |
| 674 | <li><p>You may not use a <i>using-directive</i> |
| 675 | to make all names from a namespace available.</p> |
| 676 | |
| 677 | <pre class="badcode">// Forbidden -- This pollutes the namespace. |
| 678 | using namespace foo; |
| 679 | </pre> |
| 680 | </li> |
| 681 | |
| 682 | <li><p>Do not use <i>Namespace aliases</i> at namespace scope |
| 683 | in header files except in explicitly marked |
| 684 | internal-only namespaces, because anything imported into a namespace |
| 685 | in a header file becomes part of the public |
| 686 | API exported by that file.</p> |
| 687 | |
| 688 | <pre>// Shorten access to some commonly used names in .cc files. |
| 689 | namespace baz = ::foo::bar::baz; |
| 690 | </pre> |
| 691 | |
| 692 | <pre>// Shorten access to some commonly used names (in a .h file). |
| 693 | namespace librarian { |
| 694 | namespace impl { // Internal, not part of the API. |
| 695 | namespace sidetable = ::pipeline_diagnostics::sidetable; |
| 696 | } // namespace impl |
| 697 | |
| 698 | inline void my_inline_function() { |
| 699 | // namespace alias local to a function (or method). |
| 700 | namespace baz = ::foo::bar::baz; |
| 701 | ... |
| 702 | } |
| 703 | } // namespace librarian |
| 704 | </pre> |
| 705 | |
| 706 | </li><li>Do not use inline namespaces.</li> |
| 707 | </ul> |
| 708 | </div> |
| 709 | </div> |
| 710 | |
| 711 | <h3 id="Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and Static |
| 712 | Variables</h3> |
| 713 | |
| 714 | <div class="summary"> |
| 715 | <p>When definitions in a <code>.cc</code> file do not need to be |
| 716 | referenced outside that file, place them in an unnamed |
| 717 | namespace or declare them <code>static</code>. Do not use either |
| 718 | of these constructs in <code>.h</code> files. |
| 719 | </p></div> |
| 720 | |
| 721 | <div class="stylebody"> |
| 722 | |
| 723 | <div class="definition"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 724 | <p>All declarations can be given internal linkage by placing them in unnamed |
| 725 | namespaces. Functions and variables can also be given internal linkage by |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 726 | declaring them <code>static</code>. This means that anything you're declaring |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 727 | can't be accessed from another file. If a different file declares something with |
| 728 | the same name, then the two entities are completely independent.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 729 | </div> |
| 730 | |
| 731 | <div class="decision"> |
| 732 | |
| 733 | <p>Use of internal linkage in <code>.cc</code> files is encouraged |
| 734 | for all code that does not need to be referenced elsewhere. |
| 735 | Do not use internal linkage in <code>.h</code> files.</p> |
| 736 | |
| 737 | <p>Format unnamed namespaces like named namespaces. In the |
| 738 | terminating comment, leave the namespace name empty:</p> |
| 739 | |
| 740 | <pre>namespace { |
| 741 | ... |
| 742 | } // namespace |
| 743 | </pre> |
| 744 | </div> |
| 745 | </div> |
| 746 | |
| 747 | <h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3> |
| 748 | |
| 749 | <div class="summary"> |
| 750 | <p>Prefer placing nonmember functions in a namespace; use completely global |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 751 | functions rarely. Do not use a class simply to group static functions. Static |
| 752 | methods of a class should generally be closely related to instances of the |
| 753 | class or the class's static data.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 754 | </div> |
| 755 | |
| 756 | <div class="stylebody"> |
| 757 | |
| 758 | <div class="pros"> |
| 759 | <p>Nonmember and static member functions can be useful in |
| 760 | some situations. Putting nonmember functions in a |
| 761 | namespace avoids polluting the global namespace.</p> |
| 762 | </div> |
| 763 | |
| 764 | <div class="cons"> |
| 765 | <p>Nonmember and static member functions may make more sense |
| 766 | as members of a new class, especially if they access |
| 767 | external resources or have significant dependencies.</p> |
| 768 | </div> |
| 769 | |
| 770 | <div class="decision"> |
| 771 | <p>Sometimes it is useful to define a |
| 772 | function not bound to a class instance. Such a function |
| 773 | can be either a static member or a nonmember function. |
| 774 | Nonmember functions should not depend on external |
| 775 | variables, and should nearly always exist in a namespace. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 776 | Do not create classes only to group static member functions; |
| 777 | this is no different than just giving the function names a |
| 778 | common prefix, and such grouping is usually unnecessary anyway.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 779 | |
| 780 | <p>If you define a nonmember function and it is only |
| 781 | needed in its <code>.cc</code> file, use |
| 782 | <a href="#Unnamed_Namespaces_and_Static_Variables">internal linkage</a> to limit |
| 783 | its scope.</p> |
| 784 | </div> |
| 785 | |
| 786 | </div> |
| 787 | |
| 788 | <h3 id="Local_Variables">Local Variables</h3> |
| 789 | |
| 790 | <div class="summary"> |
| 791 | <p>Place a function's variables in the narrowest scope |
| 792 | possible, and initialize variables in the declaration.</p> |
| 793 | </div> |
| 794 | |
| 795 | <div class="stylebody"> |
| 796 | |
| 797 | <p>C++ allows you to declare variables anywhere in a |
| 798 | function. We encourage you to declare them in as local a |
| 799 | scope as possible, and as close to the first use as |
| 800 | possible. This makes it easier for the reader to find the |
| 801 | declaration and see what type the variable is and what it |
| 802 | was initialized to. In particular, initialization should |
| 803 | be used instead of declaration and assignment, e.g.:</p> |
| 804 | |
| 805 | <pre class="badcode">int i; |
| 806 | i = f(); // Bad -- initialization separate from declaration. |
| 807 | </pre> |
| 808 | |
| 809 | <pre>int j = g(); // Good -- declaration has initialization. |
| 810 | </pre> |
| 811 | |
| 812 | <pre class="badcode">std::vector<int> v; |
| 813 | v.push_back(1); // Prefer initializing using brace initialization. |
| 814 | v.push_back(2); |
| 815 | </pre> |
| 816 | |
| 817 | <pre>std::vector<int> v = {1, 2}; // Good -- v starts initialized. |
| 818 | </pre> |
| 819 | |
| 820 | <p>Variables needed for <code>if</code>, <code>while</code> |
| 821 | and <code>for</code> statements should normally be declared |
| 822 | within those statements, so that such variables are confined |
| 823 | to those scopes. E.g.:</p> |
| 824 | |
| 825 | <pre>while (const char* p = strchr(str, '/')) str = p + 1; |
| 826 | </pre> |
| 827 | |
| 828 | <p>There is one caveat: if the variable is an object, its |
| 829 | constructor is invoked every time it enters scope and is |
| 830 | created, and its destructor is invoked every time it goes |
| 831 | out of scope.</p> |
| 832 | |
| 833 | <pre class="badcode">// Inefficient implementation: |
| 834 | for (int i = 0; i < 1000000; ++i) { |
| 835 | Foo f; // My ctor and dtor get called 1000000 times each. |
| 836 | f.DoSomething(i); |
| 837 | } |
| 838 | </pre> |
| 839 | |
| 840 | <p>It may be more efficient to declare such a variable |
| 841 | used in a loop outside that loop:</p> |
| 842 | |
| 843 | <pre>Foo f; // My ctor and dtor get called once each. |
| 844 | for (int i = 0; i < 1000000; ++i) { |
| 845 | f.DoSomething(i); |
| 846 | } |
| 847 | </pre> |
| 848 | |
| 849 | </div> |
| 850 | |
| 851 | <h3 id="Static_and_Global_Variables">Static and Global Variables</h3> |
| 852 | |
| 853 | <div class="summary"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 854 | <p>Objects with |
| 855 | <a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration"> |
| 856 | static storage duration</a> are forbidden unless they are |
| 857 | <a href="http://en.cppreference.com/w/cpp/types/is_destructible">trivially |
| 858 | destructible</a>. Informally this means that the destructor does not do |
| 859 | anything, even taking member and base destructors into account. More formally it |
| 860 | means that the type has no user-defined or virtual destructor and that all bases |
| 861 | and non-static members are trivially destructible. |
| 862 | Static function-local variables may use dynamic initialization. |
| 863 | Use of dynamic initialization for static class member variables or variables at |
| 864 | namespace scope is discouraged, but allowed in limited circumstances; see below |
| 865 | for details.</p> |
| 866 | |
| 867 | <p>As a rule of thumb: a global variable satisfies these requirements if its |
| 868 | declaration, considered in isolation, could be <code>constexpr</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 869 | </div> |
| 870 | |
| 871 | <div class="stylebody"> |
| 872 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 873 | <div class="definition"> |
| 874 | <p>Every object has a <dfn>storage duration</dfn>, which correlates with its |
| 875 | lifetime. Objects with static storage duration live from the point of their |
| 876 | initialization until the end of the program. Such objects appear as variables at |
| 877 | namespace scope ("global variables"), as static data members of classes, or as |
| 878 | function-local variables that are declared with the <code>static</code> |
| 879 | specifier. Function-local static variables are initialized when control first |
| 880 | passes through their declaration; all other objects with static storage duration |
| 881 | are initialized as part of program start-up. All objects with static storage |
| 882 | duration are destroyed at program exit (which happens before unjoined threads |
| 883 | are terminated).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 884 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 885 | <p>Initialization may be <dfn>dynamic</dfn>, which means that something |
| 886 | non-trivial happens during initialization. (For example, consider a constructor |
| 887 | that allocates memory, or a variable that is initialized with the current |
| 888 | process ID.) The other kind of initialization is <dfn>static</dfn> |
| 889 | initialization. The two aren't quite opposites, though: static |
| 890 | initialization <em>always</em> happens to objects with static storage duration |
| 891 | (initializing the object either to a given constant or to a representation |
| 892 | consisting of all bytes set to zero), whereas dynamic initialization happens |
| 893 | after that, if required.</p> |
| 894 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 895 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 896 | <div class="pros"> |
| 897 | <p>Global and static variables are very useful for a large number of |
| 898 | applications: named constants, auxiliary data structures internal to some |
| 899 | translation unit, command-line flags, logging, registration mechanisms, |
| 900 | background infrastructure, etc.</p> |
| 901 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 902 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 903 | <div class="cons"> |
| 904 | <p>Global and static variables that use dynamic initialization or have |
| 905 | non-trivial destructors create complexity that can easily lead to hard-to-find |
| 906 | bugs. Dynamic initialization is not ordered across translation units, and |
| 907 | neither is destruction (except that destruction |
| 908 | happens in reverse order of initialization). When one initialization refers to |
| 909 | another variable with static storage duration, it is possible that this causes |
| 910 | an object to be accessed before its lifetime has begun (or after its lifetime |
| 911 | has ended). Moreover, when a program starts threads that are not joined at exit, |
| 912 | those threads may attempt to access objects after their lifetime has ended if |
| 913 | their destructor has already run.</p> |
| 914 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 915 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 916 | <div class="decision"> |
| 917 | <h4>Decision on destruction</h4> |
| 918 | |
| 919 | <p>When destructors are trivial, their execution is not subject to ordering at |
| 920 | all (they are effectively not "run"); otherwise we are exposed to the risk of |
| 921 | accessing objects after the end of their lifetime. Therefore, we only allow |
| 922 | objects with static storage duration if they are trivially destructible. |
| 923 | Fundamental types (like pointers and <code>int</code>) are trivially |
| 924 | destructible, as are arrays of trivially destructible types. Note that |
| 925 | variables marked with <code>constexpr</code> are trivially destructible.</p> |
| 926 | <pre>const int kNum = 10; // allowed |
| 927 | |
| 928 | struct X { int n; }; |
| 929 | const X kX[] = {{1}, {2}, {3}}; // allowed |
| 930 | |
| 931 | void foo() { |
| 932 | static const char* const kMessages[] = {"hello", "world"}; // allowed |
| 933 | } |
| 934 | |
| 935 | // allowed: constexpr guarantees trivial destructor |
| 936 | constexpr std::array<int, 3> kArray = {{1, 2, 3}};</pre> |
| 937 | <pre class="badcode">// bad: non-trivial destructor |
| 938 | const string kFoo = "foo"; |
| 939 | |
| 940 | // bad for the same reason, even though kBar is a reference (the |
| 941 | // rule also applies to lifetime-extended temporary objects) |
| 942 | const string& kBar = StrCat("a", "b", "c"); |
| 943 | |
| 944 | void bar() { |
| 945 | // bad: non-trivial destructor |
| 946 | static std::map<int, int> kData = {{1, 0}, {2, 0}, {3, 0}}; |
| 947 | }</pre> |
| 948 | |
| 949 | <p>Note that references are not objects, and thus they are not subject to the |
| 950 | constraints on destructibility. The constraint on dynamic initialization still |
| 951 | applies, though. In particular, a function-local static reference of the form |
| 952 | <code>static T& t = *new T;</code> is allowed.</p> |
| 953 | |
| 954 | <h4>Decision on initialization</h4> |
| 955 | |
| 956 | <p>Initialization is a more complex topic. This is because we must not only |
| 957 | consider whether class constructors execute, but we must also consider the |
| 958 | evaluation of the initializer:</p> |
| 959 | <pre class="neutralcode">int n = 5; // fine |
| 960 | int m = f(); // ? (depends on f) |
| 961 | Foo x; // ? (depends on Foo::Foo) |
| 962 | Bar y = g(); // ? (depends on g and on Bar::Bar)</pre> |
| 963 | |
| 964 | <p>All but the first statement expose us to indeterminate initialization |
| 965 | ordering.</p> |
| 966 | |
| 967 | <p>The concept we are looking for is called <em>constant initialization</em> in |
| 968 | the formal language of the C++ standard. It means that the initializing |
| 969 | expression is a constant expression, and if the object is initialized by a |
| 970 | constructor call, then the constructor must be specified as |
| 971 | <code>constexpr</code>, too:</p> |
| 972 | <pre>struct Foo { constexpr Foo(int) {} }; |
| 973 | |
| 974 | int n = 5; // fine, 5 is a constant expression |
| 975 | Foo x(2); // fine, 2 is a constant expression and the chosen constructor is constexpr |
| 976 | Foo a[] = { Foo(1), Foo(2), Foo(3) }; // fine</pre> |
| 977 | |
| 978 | <p>Constant initialization is always allowed. Constant initialization of |
| 979 | static storage duration variables should be marked with <code>constexpr</code> |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 980 | or where possible the |
| 981 | |
| 982 | <a href="https://github.com/abseil/abseil-cpp/blob/03c1513538584f4a04d666be5eb469e3979febba/absl/base/attributes.h#L540"> |
| 983 | <code>ABSL_CONST_INIT</code></a> |
| 984 | attribute. Any non-local static storage |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 985 | duration variable that is not so marked should be presumed to have |
| 986 | dynamic initialization, and reviewed very carefully.</p> |
| 987 | |
| 988 | <p>By contrast, the following initializations are problematic:</p> |
| 989 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 990 | <pre class="badcode">// Some declarations used below. |
| 991 | time_t time(time_t*); // not constexpr! |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 992 | int f(); // not constexpr! |
| 993 | struct Bar { Bar() {} }; |
| 994 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 995 | // Problematic initializations. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 996 | time_t m = time(nullptr); // initializing expression not a constant expression |
| 997 | Foo y(f()); // ditto |
| 998 | Bar b; // chosen constructor Bar::Bar() not constexpr</pre> |
| 999 | |
| 1000 | <p>Dynamic initialization of nonlocal variables is discouraged, and in general |
| 1001 | it is forbidden. However, we do permit it if no aspect of the program depends |
| 1002 | on the sequencing of this initialization with respect to all other |
| 1003 | initializations. Under those restrictions, the ordering of the initialization |
| 1004 | does not make an observable difference. For example:</p> |
| 1005 | <pre>int p = getpid(); // allowed, as long as no other static variable |
| 1006 | // uses p in its own initialization</pre> |
| 1007 | |
| 1008 | <p>Dynamic initialization of static local variables is allowed (and common).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1009 | |
| 1010 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1011 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1012 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1013 | <h4>Common patterns</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1014 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1015 | <ul> |
| 1016 | <li>Global strings: if you require a global or static string constant, |
| 1017 | consider using a simple character array, or a char pointer to the first |
| 1018 | element of a string literal. String literals have static storage duration |
| 1019 | already and are usually sufficient.</li> |
| 1020 | <li>Maps, sets, and other dynamic containers: if you require a static, fixed |
| 1021 | collection, such as a set to search against or a lookup table, you cannot |
| 1022 | use the dynamic containers from the standard library as a static variable, |
| 1023 | since they have non-trivial destructors. Instead, consider a simple array of |
| 1024 | trivial types, e.g. an array of arrays of ints (for a "map from int to |
| 1025 | int"), or an array of pairs (e.g. pairs of <code>int</code> and <code>const |
| 1026 | char*</code>). For small collections, linear search is entirely sufficient |
| 1027 | (and efficient, due to memory locality). If necessary, keep the collection in |
| 1028 | sorted order and use a binary search algorithm. If you do really prefer a |
| 1029 | dynamic container from the standard library, consider using a function-local |
| 1030 | static pointer, as described below.</li> |
| 1031 | <li>Smart pointers (<code>unique_ptr</code>, <code>shared_ptr</code>): smart |
| 1032 | pointers execute cleanup during destruction and are therefore forbidden. |
| 1033 | Consider whether your use case fits into one of the other patterns described |
| 1034 | in this section. One simple solution is to use a plain pointer to a |
| 1035 | dynamically allocated object and never delete it (see last item).</li> |
| 1036 | <li>Static variables of custom types: if you require static, constant data of |
| 1037 | a type that you need to define yourself, give the type a trivial destructor |
| 1038 | and a <code>constexpr</code> constructor.</li> |
| 1039 | <li>If all else fails, you can create an object dynamically and never delete |
| 1040 | it by binding the pointer to a function-local static pointer variable: |
| 1041 | <code>static const auto* const impl = new T(args...);</code> (If the |
| 1042 | initialization is more complex, it can be moved into a function or lambda |
| 1043 | expression.)</li> |
| 1044 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1045 | |
| 1046 | </div> |
| 1047 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1048 | <h3 id="thread_local">thread_local Variables</h3> |
| 1049 | |
| 1050 | <div class="summary"> |
| 1051 | <p><code>thread_local</code> variables that aren't declared inside a function |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1052 | must be initialized with a true compile-time constant, |
| 1053 | and this must be enforced by using the |
| 1054 | |
| 1055 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h"> |
| 1056 | <code>ABSL_CONST_INIT</code></a> |
| 1057 | attribute. Prefer |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1058 | <code>thread_local</code> over other ways of defining thread-local data.</p> |
| 1059 | </div> |
| 1060 | |
| 1061 | <div class="stylebody"> |
| 1062 | |
| 1063 | <div class="definition"> |
| 1064 | <p>Starting with C++11, variables can be declared with the |
| 1065 | <code>thread_local</code> specifier:</p> |
| 1066 | <pre>thread_local Foo foo = ...; |
| 1067 | </pre> |
| 1068 | <p>Such a variable is actually a collection of objects, so that when different |
| 1069 | threads access it, they are actually accessing different objects. |
| 1070 | <code>thread_local</code> variables are much like |
| 1071 | <a href="#Static_and_Global_Variables">static storage duration variables</a> |
| 1072 | in many respects. For instance, they can be declared at namespace scope, |
| 1073 | inside functions, or as static class members, but not as ordinary class |
| 1074 | members.</p> |
| 1075 | |
| 1076 | <p><code>thread_local</code> variable instances are initialized much like |
| 1077 | static variables, except that they must be initialized separately for each |
| 1078 | thread, rather than once at program startup. This means that |
| 1079 | <code>thread_local</code> variables declared within a function are safe, but |
| 1080 | other <code>thread_local</code> variables are subject to the same |
| 1081 | initialization-order issues as static variables (and more besides).</p> |
| 1082 | |
| 1083 | <p><code>thread_local</code> variable instances are destroyed when their thread |
| 1084 | terminates, so they do not have the destruction-order issues of static |
| 1085 | variables.</p> |
| 1086 | </div> |
| 1087 | |
| 1088 | <div class="pros"> |
| 1089 | <ul> |
| 1090 | <li>Thread-local data is inherently safe from races (because only one thread |
| 1091 | can ordinarily access it), which makes <code>thread_local</code> useful for |
| 1092 | concurrent programming.</li> |
| 1093 | <li><code>thread_local</code> is the only standard-supported way of creating |
| 1094 | thread-local data.</li> |
| 1095 | </ul> |
| 1096 | </div> |
| 1097 | |
| 1098 | <div class="cons"> |
| 1099 | <ul> |
| 1100 | <li>Accessing a <code>thread_local</code> variable may trigger execution of |
| 1101 | an unpredictable and uncontrollable amount of other code.</li> |
| 1102 | <li><code>thread_local</code> variables are effectively global variables, |
| 1103 | and have all the drawbacks of global variables other than lack of |
| 1104 | thread-safety.</li> |
| 1105 | <li>The memory consumed by a <code>thread_local</code> variable scales with |
| 1106 | the number of running threads (in the worst case), which can be quite large |
| 1107 | in a program.</li> |
| 1108 | <li>An ordinary class member cannot be <code>thread_local</code>.</li> |
| 1109 | <li><code>thread_local</code> may not be as efficient as certain compiler |
| 1110 | intrinsics.</li> |
| 1111 | </ul> |
| 1112 | </div> |
| 1113 | |
| 1114 | <div class="decision"> |
| 1115 | <p><code>thread_local</code> variables inside a function have no safety |
| 1116 | concerns, so they can be used without restriction. Note that you can use |
| 1117 | a function-scope <code>thread_local</code> to simulate a class- or |
| 1118 | namespace-scope <code>thread_local</code> by defining a function or |
| 1119 | static method that exposes it:</p> |
| 1120 | |
| 1121 | <pre>Foo& MyThreadLocalFoo() { |
| 1122 | thread_local Foo result = ComplicatedInitialization(); |
| 1123 | return result; |
| 1124 | } |
| 1125 | </pre> |
| 1126 | |
| 1127 | <p><code>thread_local</code> variables at class or namespace scope must be |
| 1128 | initialized with a true compile-time constant (i.e. they must have no |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1129 | dynamic initialization). To enforce this, |
| 1130 | <code>thread_local</code> variables at class or namespace scope must be |
| 1131 | annotated with |
| 1132 | |
| 1133 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h"> |
| 1134 | <code>ABSL_CONST_INIT</code></a> |
| 1135 | (or <code>constexpr</code>, but that should be rare):</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1136 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1137 | <pre>ABSL_CONST_INIT thread_local Foo foo = ...; |
| 1138 | </pre> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1139 | |
| 1140 | <p><code>thread_local</code> should be preferred over other mechanisms for |
| 1141 | defining thread-local data.</p> |
| 1142 | </div> |
| 1143 | |
| 1144 | </div> |
| 1145 | |
| 1146 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1147 | <h2 id="Classes">Classes</h2> |
| 1148 | |
| 1149 | <p>Classes are the fundamental unit of code in C++. Naturally, |
| 1150 | we use them extensively. This section lists the main dos and |
| 1151 | don'ts you should follow when writing a class.</p> |
| 1152 | |
| 1153 | <h3 id="Doing_Work_in_Constructors">Doing Work in Constructors</h3> |
| 1154 | |
| 1155 | <div class="summary"> |
| 1156 | <p>Avoid virtual method calls in constructors, and avoid |
| 1157 | initialization that can fail if you can't signal an error.</p> |
| 1158 | </div> |
| 1159 | |
| 1160 | <div class="stylebody"> |
| 1161 | |
| 1162 | <div class="definition"> |
| 1163 | <p>It is possible to perform arbitrary initialization in the body |
| 1164 | of the constructor.</p> |
| 1165 | </div> |
| 1166 | |
| 1167 | <div class="pros"> |
| 1168 | <ul> |
| 1169 | <li>No need to worry about whether the class has been initialized or |
| 1170 | not.</li> |
| 1171 | |
| 1172 | <li>Objects that are fully initialized by constructor call can |
| 1173 | be <code>const</code> and may also be easier to use with standard containers |
| 1174 | or algorithms.</li> |
| 1175 | </ul> |
| 1176 | |
| 1177 | </div> |
| 1178 | |
| 1179 | <div class="cons"> |
| 1180 | <ul> |
| 1181 | <li>If the work calls virtual functions, these calls |
| 1182 | will not get dispatched to the subclass |
| 1183 | implementations. Future modification to your class can |
| 1184 | quietly introduce this problem even if your class is |
| 1185 | not currently subclassed, causing much confusion.</li> |
| 1186 | |
| 1187 | <li>There is no easy way for constructors to signal errors, short of |
| 1188 | crashing the program (not always appropriate) or using exceptions |
| 1189 | (which are <a href="#Exceptions">forbidden</a>).</li> |
| 1190 | |
| 1191 | <li>If the work fails, we now have an object whose initialization |
| 1192 | code failed, so it may be an unusual state requiring a <code>bool |
| 1193 | IsValid()</code> state checking mechanism (or similar) which is easy |
| 1194 | to forget to call.</li> |
| 1195 | |
| 1196 | <li>You cannot take the address of a constructor, so whatever work |
| 1197 | is done in the constructor cannot easily be handed off to, for |
| 1198 | example, another thread.</li> |
| 1199 | </ul> |
| 1200 | </div> |
| 1201 | |
| 1202 | |
| 1203 | <div class="decision"> |
| 1204 | <p>Constructors should never call virtual functions. If appropriate |
| 1205 | for your code |
| 1206 | , |
| 1207 | terminating the program may be an appropriate error handling |
| 1208 | response. Otherwise, consider a factory function |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1209 | or <code>Init()</code> method as described in |
| 1210 | |
| 1211 | |
| 1212 | <a href="https://abseil.io/tips/42">TotW #42</a> |
| 1213 | . |
| 1214 | Avoid <code>Init()</code> methods on objects with |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1215 | no other states that affect which public methods may be called |
| 1216 | (semi-constructed objects of this form are particularly hard to work |
| 1217 | with correctly).</p> |
| 1218 | </div> |
| 1219 | |
| 1220 | </div> |
| 1221 | |
| 1222 | <a id="Explicit_Constructors"></a> |
| 1223 | <h3 id="Implicit_Conversions">Implicit Conversions</h3> |
| 1224 | |
| 1225 | <div class="summary"> |
| 1226 | <p>Do not define implicit conversions. Use the <code>explicit</code> |
| 1227 | keyword for conversion operators and single-argument |
| 1228 | constructors.</p> |
| 1229 | </div> |
| 1230 | |
| 1231 | <div class="stylebody"> |
| 1232 | |
| 1233 | <div class="definition"> |
| 1234 | <p>Implicit conversions allow an |
| 1235 | object of one type (called the <dfn>source type</dfn>) to |
| 1236 | be used where a different type (called the <dfn>destination |
| 1237 | type</dfn>) is expected, such as when passing an |
| 1238 | <code>int</code> argument to a function that takes a |
| 1239 | <code>double</code> parameter.</p> |
| 1240 | |
| 1241 | <p>In addition to the implicit conversions defined by the language, |
| 1242 | users can define their own, by adding appropriate members to the |
| 1243 | class definition of the source or destination type. An implicit |
| 1244 | conversion in the source type is defined by a type conversion operator |
| 1245 | named after the destination type (e.g. <code>operator |
| 1246 | bool()</code>). An implicit conversion in the destination |
| 1247 | type is defined by a constructor that can take the source type as |
| 1248 | its only argument (or only argument with no default value).</p> |
| 1249 | |
| 1250 | <p>The <code>explicit</code> keyword can be applied to a constructor |
| 1251 | or (since C++11) a conversion operator, to ensure that it can only be |
| 1252 | used when the destination type is explicit at the point of use, |
| 1253 | e.g. with a cast. This applies not only to implicit conversions, but to |
| 1254 | C++11's list initialization syntax:</p> |
| 1255 | <pre>class Foo { |
| 1256 | explicit Foo(int x, double y); |
| 1257 | ... |
| 1258 | }; |
| 1259 | |
| 1260 | void Func(Foo f); |
| 1261 | </pre> |
| 1262 | <pre class="badcode">Func({42, 3.14}); // Error |
| 1263 | </pre> |
| 1264 | This kind of code isn't technically an implicit conversion, but the |
| 1265 | language treats it as one as far as <code>explicit</code> is concerned. |
| 1266 | </div> |
| 1267 | |
| 1268 | <div class="pros"> |
| 1269 | <ul> |
| 1270 | <li>Implicit conversions can make a type more usable and |
| 1271 | expressive by eliminating the need to explicitly name a type |
| 1272 | when it's obvious.</li> |
| 1273 | <li>Implicit conversions can be a simpler alternative to |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1274 | overloading, such as when a single |
| 1275 | function with a <code>string_view</code> parameter takes the |
| 1276 | place of separate overloads for <code>string</code> and |
| 1277 | <code>const char*</code>.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1278 | <li>List initialization syntax is a concise and expressive |
| 1279 | way of initializing objects.</li> |
| 1280 | </ul> |
| 1281 | </div> |
| 1282 | |
| 1283 | <div class="cons"> |
| 1284 | <ul> |
| 1285 | <li>Implicit conversions can hide type-mismatch bugs, where the |
| 1286 | destination type does not match the user's expectation, or |
| 1287 | the user is unaware that any conversion will take place.</li> |
| 1288 | |
| 1289 | <li>Implicit conversions can make code harder to read, particularly |
| 1290 | in the presence of overloading, by making it less obvious what |
| 1291 | code is actually getting called.</li> |
| 1292 | |
| 1293 | <li>Constructors that take a single argument may accidentally |
| 1294 | be usable as implicit type conversions, even if they are not |
| 1295 | intended to do so.</li> |
| 1296 | |
| 1297 | <li>When a single-argument constructor is not marked |
| 1298 | <code>explicit</code>, there's no reliable way to tell whether |
| 1299 | it's intended to define an implicit conversion, or the author |
| 1300 | simply forgot to mark it.</li> |
| 1301 | |
| 1302 | <li>It's not always clear which type should provide the conversion, |
| 1303 | and if they both do, the code becomes ambiguous.</li> |
| 1304 | |
| 1305 | <li>List initialization can suffer from the same problems if |
| 1306 | the destination type is implicit, particularly if the |
| 1307 | list has only a single element.</li> |
| 1308 | </ul> |
| 1309 | </div> |
| 1310 | |
| 1311 | <div class="decision"> |
| 1312 | <p>Type conversion operators, and constructors that are |
| 1313 | callable with a single argument, must be marked |
| 1314 | <code>explicit</code> in the class definition. As an |
| 1315 | exception, copy and move constructors should not be |
| 1316 | <code>explicit</code>, since they do not perform type |
| 1317 | conversion. Implicit conversions can sometimes be necessary and |
| 1318 | appropriate for types that are designed to transparently wrap other |
| 1319 | types. In that case, contact |
| 1320 | your project leads to request |
| 1321 | a waiver of this rule.</p> |
| 1322 | |
| 1323 | <p>Constructors that cannot be called with a single argument |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1324 | may omit <code>explicit</code>. Constructors that |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1325 | take a single <code>std::initializer_list</code> parameter should |
| 1326 | also omit <code>explicit</code>, in order to support copy-initialization |
| 1327 | (e.g. <code>MyType m = {1, 2};</code>).</p> |
| 1328 | </div> |
| 1329 | |
| 1330 | </div> |
| 1331 | |
| 1332 | <h3 id="Copyable_Movable_Types">Copyable and Movable Types</h3> |
| 1333 | <a id="Copy_Constructors"></a> |
| 1334 | <div class="summary"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1335 | <p>A class's public API should make explicit whether the class is copyable, |
| 1336 | move-only, or neither copyable nor movable. Support copying and/or |
| 1337 | moving if these operations are clear and meaningful for your type.</p> |
| 1338 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1339 | |
| 1340 | <div class="stylebody"> |
| 1341 | |
| 1342 | <div class="definition"> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1343 | <p>A movable type is one that can be initialized and assigned |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1344 | from temporaries.</p> |
| 1345 | |
| 1346 | <p>A copyable type is one that can be initialized or assigned from |
| 1347 | any other object of the same type (so is also movable by definition), with the |
| 1348 | stipulation that the value of the source does not change. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1349 | <code>std::unique_ptr<int></code> is an example of a movable but not |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1350 | copyable type (since the value of the source |
| 1351 | <code>std::unique_ptr<int></code> must be modified during assignment to |
| 1352 | the destination). <code>int</code> and <code>string</code> are examples of |
| 1353 | movable types that are also copyable. (For <code>int</code>, the move and copy |
| 1354 | operations are the same; for <code>string</code>, there exists a move operation |
| 1355 | that is less expensive than a copy.)</p> |
| 1356 | |
| 1357 | <p>For user-defined types, the copy behavior is defined by the copy |
| 1358 | constructor and the copy-assignment operator. Move behavior is defined by the |
| 1359 | move constructor and the move-assignment operator, if they exist, or by the |
| 1360 | copy constructor and the copy-assignment operator otherwise.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1361 | |
| 1362 | <p>The copy/move constructors can be implicitly invoked by the compiler |
| 1363 | in some situations, e.g. when passing objects by value.</p> |
| 1364 | </div> |
| 1365 | |
| 1366 | <div class="pros"> |
| 1367 | <p>Objects of copyable and movable types can be passed and returned by value, |
| 1368 | which makes APIs simpler, safer, and more general. Unlike when passing objects |
| 1369 | by pointer or reference, there's no risk of confusion over ownership, |
| 1370 | lifetime, mutability, and similar issues, and no need to specify them in the |
| 1371 | contract. It also prevents non-local interactions between the client and the |
| 1372 | implementation, which makes them easier to understand, maintain, and optimize by |
| 1373 | the compiler. Further, such objects can be used with generic APIs that |
| 1374 | require pass-by-value, such as most containers, and they allow for additional |
| 1375 | flexibility in e.g., type composition.</p> |
| 1376 | |
| 1377 | <p>Copy/move constructors and assignment operators are usually |
| 1378 | easier to define correctly than alternatives |
| 1379 | like <code>Clone()</code>, <code>CopyFrom()</code> or <code>Swap()</code>, |
| 1380 | because they can be generated by the compiler, either implicitly or |
| 1381 | with <code>= default</code>. They are concise, and ensure |
| 1382 | that all data members are copied. Copy and move |
| 1383 | constructors are also generally more efficient, because they don't |
| 1384 | require heap allocation or separate initialization and assignment |
| 1385 | steps, and they're eligible for optimizations such as |
| 1386 | |
| 1387 | <a href="http://en.cppreference.com/w/cpp/language/copy_elision"> |
| 1388 | copy elision</a>.</p> |
| 1389 | |
| 1390 | <p>Move operations allow the implicit and efficient transfer of |
| 1391 | resources out of rvalue objects. This allows a plainer coding style |
| 1392 | in some cases.</p> |
| 1393 | </div> |
| 1394 | |
| 1395 | <div class="cons"> |
| 1396 | <p>Some types do not need to be copyable, and providing copy |
| 1397 | operations for such types can be confusing, nonsensical, or outright |
| 1398 | incorrect. Types representing singleton objects (<code>Registerer</code>), |
| 1399 | objects tied to a specific scope (<code>Cleanup</code>), or closely coupled to |
| 1400 | object identity (<code>Mutex</code>) cannot be copied meaningfully. |
| 1401 | Copy operations for base class types that are to be used |
| 1402 | polymorphically are hazardous, because use of them can lead to |
| 1403 | <a href="https://en.wikipedia.org/wiki/Object_slicing">object slicing</a>. |
| 1404 | Defaulted or carelessly-implemented copy operations can be incorrect, and the |
| 1405 | resulting bugs can be confusing and difficult to diagnose.</p> |
| 1406 | |
| 1407 | <p>Copy constructors are invoked implicitly, which makes the |
| 1408 | invocation easy to miss. This may cause confusion for programmers used to |
| 1409 | languages where pass-by-reference is conventional or mandatory. It may also |
| 1410 | encourage excessive copying, which can cause performance problems.</p> |
| 1411 | </div> |
| 1412 | |
| 1413 | <div class="decision"> |
| 1414 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1415 | <p>Every class's public interface should make explicit which copy and move |
| 1416 | operations the class supports. This should usually take the form of explicitly |
| 1417 | declaring and/or deleting the appropriate operations in the <code>public</code> |
| 1418 | section of the declaration.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1419 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1420 | <p>Specifically, a copyable class should explicitly declare the copy |
| 1421 | operations, a move-only class should explicitly declare the move operations, |
| 1422 | and a non-copyable/movable class should explicitly delete the copy operations. |
| 1423 | Explicitly declaring or deleting all four copy/move operations is permitted, |
| 1424 | but not required. If you provide a copy or move assignment operator, you |
| 1425 | must also provide the corresponding constructor.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1426 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1427 | <pre>class Copyable { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1428 | public: |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1429 | Copyable(const Copyable& rhs) = default; |
| 1430 | Copyable& operator=(const Copyable& rhs) = default; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1431 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1432 | // The implicit move operations are suppressed by the declarations above. |
| 1433 | }; |
| 1434 | |
| 1435 | class MoveOnly { |
| 1436 | public: |
| 1437 | MoveOnly(MoveOnly&& rhs); |
| 1438 | MoveOnly& operator=(MoveOnly&& rhs); |
| 1439 | |
| 1440 | // The copy operations are implicitly deleted, but you can |
| 1441 | // spell that out explicitly if you want: |
| 1442 | MoveOnly(const MoveOnly&) = delete; |
| 1443 | MoveOnly& operator=(const MoveOnly&) = delete; |
| 1444 | }; |
| 1445 | |
| 1446 | class NotCopyableOrMovable { |
| 1447 | public: |
| 1448 | // Not copyable or movable |
| 1449 | NotCopyableOrMovable(const NotCopyableOrMovable&) = delete; |
| 1450 | NotCopyableOrMovable& operator=(const NotCopyableOrMovable&) |
| 1451 | = delete; |
| 1452 | |
| 1453 | // The move operations are implicitly disabled, but you can |
| 1454 | // spell that out explicitly if you want: |
| 1455 | NotCopyableOrMovable(NotCopyableOrMovable&&) = delete; |
| 1456 | NotCopyableOrMovable& operator=(NotCopyableOrMovable&&) |
| 1457 | = delete; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1458 | }; |
| 1459 | </pre> |
| 1460 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1461 | <p>These declarations/deletions can be omitted only if they are obvious: for |
| 1462 | example, if a base class isn't copyable or movable, derived classes naturally |
| 1463 | won't be either. Similarly, a <a href="#Structs_vs._Classes">struct</a>'s |
| 1464 | copyability/movability is normally determined by the copyability/movability |
| 1465 | of its data members (this does not apply to classes because in Google code |
| 1466 | their data members are not public). Note that if you explicitly declare or |
| 1467 | delete any of the copy/move operations, the others are not obvious, and so |
| 1468 | this paragraph does not apply (in particular, the rules in this section |
| 1469 | that apply to "classes" also apply to structs that declare or delete any |
| 1470 | copy/move operations).</p> |
| 1471 | |
| 1472 | <p>A type should not be copyable/movable if the meaning of |
| 1473 | copying/moving is unclear to a casual user, or if it incurs unexpected |
| 1474 | costs. Move operations for copyable types are strictly a performance |
| 1475 | optimization and are a potential source of bugs and complexity, so |
| 1476 | avoid defining them unless they are significantly more efficient than |
| 1477 | the corresponding copy operations. If your type provides copy operations, it is |
| 1478 | recommended that you design your class so that the default implementation of |
| 1479 | those operations is correct. Remember to review the correctness of any |
| 1480 | defaulted operations as you would any other code.</p> |
| 1481 | |
| 1482 | <p>Due to the risk of slicing, prefer to avoid providing a public assignment |
| 1483 | operator or copy/move constructor for a class that's |
| 1484 | intended to be derived from (and prefer to avoid deriving from a class |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1485 | with such members). If your base class needs to be |
| 1486 | copyable, provide a public virtual <code>Clone()</code> |
| 1487 | method, and a protected copy constructor that derived classes |
| 1488 | can use to implement it.</p> |
| 1489 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1490 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1491 | |
| 1492 | </div> |
| 1493 | </div> |
| 1494 | |
| 1495 | <h3 id="Structs_vs._Classes">Structs vs. Classes</h3> |
| 1496 | |
| 1497 | <div class="summary"> |
| 1498 | <p>Use a <code>struct</code> only for passive objects that |
| 1499 | carry data; everything else is a <code>class</code>.</p> |
| 1500 | </div> |
| 1501 | |
| 1502 | <div class="stylebody"> |
| 1503 | |
| 1504 | <p>The <code>struct</code> and <code>class</code> |
| 1505 | keywords behave almost identically in C++. We add our own |
| 1506 | semantic meanings to each keyword, so you should use the |
| 1507 | appropriate keyword for the data-type you're |
| 1508 | defining.</p> |
| 1509 | |
| 1510 | <p><code>structs</code> should be used for passive |
| 1511 | objects that carry data, and may have associated |
| 1512 | constants, but lack any functionality other than |
| 1513 | access/setting the data members. The accessing/setting of |
| 1514 | fields is done by directly accessing the fields rather |
| 1515 | than through method invocations. Methods should not |
| 1516 | provide behavior but should only be used to set up the |
| 1517 | data members, e.g., constructor, destructor, |
| 1518 | <code>Initialize()</code>, <code>Reset()</code>, |
| 1519 | <code>Validate()</code>.</p> |
| 1520 | |
| 1521 | <p>If more functionality is required, a |
| 1522 | <code>class</code> is more appropriate. If in doubt, make |
| 1523 | it a <code>class</code>.</p> |
| 1524 | |
| 1525 | <p>For consistency with STL, you can use |
| 1526 | <code>struct</code> instead of <code>class</code> for |
| 1527 | functors and traits.</p> |
| 1528 | |
| 1529 | <p>Note that member variables in structs and classes have |
| 1530 | <a href="#Variable_Names">different naming rules</a>.</p> |
| 1531 | |
| 1532 | </div> |
| 1533 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1534 | <a id="Multiple_Inheritance"></a> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1535 | <h3 id="Inheritance">Inheritance</h3> |
| 1536 | |
| 1537 | <div class="summary"> |
| 1538 | <p>Composition is often more appropriate than inheritance. |
| 1539 | When using inheritance, make it <code>public</code>.</p> |
| 1540 | </div> |
| 1541 | |
| 1542 | <div class="stylebody"> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1543 | <div class="definition"> |
| 1544 | <p> When a sub-class |
| 1545 | inherits from a base class, it includes the definitions |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1546 | of all the data and operations that the base class |
| 1547 | defines. "Interface inheritance" is inheritance from a |
| 1548 | pure abstract base class (one with no state or defined |
| 1549 | methods); all other inheritance is "implementation |
| 1550 | inheritance".</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1551 | </div> |
| 1552 | |
| 1553 | <div class="pros"> |
| 1554 | <p>Implementation inheritance reduces code size by re-using |
| 1555 | the base class code as it specializes an existing type. |
| 1556 | Because inheritance is a compile-time declaration, you |
| 1557 | and the compiler can understand the operation and detect |
| 1558 | errors. Interface inheritance can be used to |
| 1559 | programmatically enforce that a class expose a particular |
| 1560 | API. Again, the compiler can detect errors, in this case, |
| 1561 | when a class does not define a necessary method of the |
| 1562 | API.</p> |
| 1563 | </div> |
| 1564 | |
| 1565 | <div class="cons"> |
| 1566 | <p>For implementation inheritance, because the code |
| 1567 | implementing a sub-class is spread between the base and |
| 1568 | the sub-class, it can be more difficult to understand an |
| 1569 | implementation. The sub-class cannot override functions |
| 1570 | that are not virtual, so the sub-class cannot change |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1571 | implementation.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1572 | |
| 1573 | <p>Multiple inheritance is especially problematic, because |
| 1574 | it often imposes a higher performance overhead (in fact, |
| 1575 | the performance drop from single inheritance to multiple |
| 1576 | inheritance can often be greater than the performance |
| 1577 | drop from ordinary to virtual dispatch), and because |
| 1578 | it risks leading to "diamond" inheritance patterns, |
| 1579 | which are prone to ambiguity, confusion, and outright bugs.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1580 | </div> |
| 1581 | |
| 1582 | <div class="decision"> |
| 1583 | |
| 1584 | <p>All inheritance should be <code>public</code>. If you |
| 1585 | want to do private inheritance, you should be including |
| 1586 | an instance of the base class as a member instead.</p> |
| 1587 | |
| 1588 | <p>Do not overuse implementation inheritance. Composition |
| 1589 | is often more appropriate. Try to restrict use of |
| 1590 | inheritance to the "is-a" case: <code>Bar</code> |
| 1591 | subclasses <code>Foo</code> if it can reasonably be said |
| 1592 | that <code>Bar</code> "is a kind of" |
| 1593 | <code>Foo</code>.</p> |
| 1594 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1595 | <p>Limit the use of <code>protected</code> to those |
| 1596 | member functions that might need to be accessed from |
| 1597 | subclasses. Note that <a href="#Access_Control">data |
| 1598 | members should be private</a>.</p> |
| 1599 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1600 | <p>Explicitly annotate overrides of virtual functions or virtual |
| 1601 | destructors with exactly one of an <code>override</code> or (less |
| 1602 | frequently) <code>final</code> specifier. Do not |
| 1603 | use <code>virtual</code> when declaring an override. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1604 | Rationale: A function or destructor marked |
| 1605 | <code>override</code> or <code>final</code> that is |
| 1606 | not an override of a base class virtual function will |
| 1607 | not compile, and this helps catch common errors. The |
| 1608 | specifiers serve as documentation; if no specifier is |
| 1609 | present, the reader has to check all ancestors of the |
| 1610 | class in question to determine if the function or |
| 1611 | destructor is virtual or not.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1612 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1613 | <p>Multiple inheritance is permitted, but multiple <em>implementation</em> |
| 1614 | inheritance is strongly discouraged.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1615 | </div> |
| 1616 | |
| 1617 | </div> |
| 1618 | |
| 1619 | <h3 id="Operator_Overloading">Operator Overloading</h3> |
| 1620 | |
| 1621 | <div class="summary"> |
| 1622 | <p>Overload operators judiciously. Do not create user-defined literals.</p> |
| 1623 | </div> |
| 1624 | |
| 1625 | <div class="stylebody"> |
| 1626 | |
| 1627 | <div class="definition"> |
| 1628 | <p>C++ permits user code to |
| 1629 | <a href="http://en.cppreference.com/w/cpp/language/operators">declare |
| 1630 | overloaded versions of the built-in operators</a> using the |
| 1631 | <code>operator</code> keyword, so long as one of the parameters |
| 1632 | is a user-defined type. The <code>operator</code> keyword also |
| 1633 | permits user code to define new kinds of literals using |
| 1634 | <code>operator""</code>, and to define type-conversion functions |
| 1635 | such as <code>operator bool()</code>.</p> |
| 1636 | </div> |
| 1637 | |
| 1638 | <div class="pros"> |
| 1639 | <p>Operator overloading can make code more concise and |
| 1640 | intuitive by enabling user-defined types to behave the same |
| 1641 | as built-in types. Overloaded operators are the idiomatic names |
| 1642 | for certain operations (e.g. <code>==</code>, <code><</code>, |
| 1643 | <code>=</code>, and <code><<</code>), and adhering to |
| 1644 | those conventions can make user-defined types more readable |
| 1645 | and enable them to interoperate with libraries that expect |
| 1646 | those names.</p> |
| 1647 | |
| 1648 | <p>User-defined literals are a very concise notation for |
| 1649 | creating objects of user-defined types.</p> |
| 1650 | </div> |
| 1651 | |
| 1652 | <div class="cons"> |
| 1653 | <ul> |
| 1654 | <li>Providing a correct, consistent, and unsurprising |
| 1655 | set of operator overloads requires some care, and failure |
| 1656 | to do so can lead to confusion and bugs.</li> |
| 1657 | |
| 1658 | <li>Overuse of operators can lead to obfuscated code, |
| 1659 | particularly if the overloaded operator's semantics |
| 1660 | don't follow convention.</li> |
| 1661 | |
| 1662 | <li>The hazards of function overloading apply just as |
| 1663 | much to operator overloading, if not more so.</li> |
| 1664 | |
| 1665 | <li>Operator overloads can fool our intuition into |
| 1666 | thinking that expensive operations are cheap, built-in |
| 1667 | operations.</li> |
| 1668 | |
| 1669 | <li>Finding the call sites for overloaded operators may |
| 1670 | require a search tool that's aware of C++ syntax, rather |
| 1671 | than e.g. grep.</li> |
| 1672 | |
| 1673 | <li>If you get the argument type of an overloaded operator |
| 1674 | wrong, you may get a different overload rather than a |
| 1675 | compiler error. For example, <code>foo < bar</code> |
| 1676 | may do one thing, while <code>&foo < &bar</code> |
| 1677 | does something totally different.</li> |
| 1678 | |
| 1679 | <li>Certain operator overloads are inherently hazardous. |
| 1680 | Overloading unary <code>&</code> can cause the same |
| 1681 | code to have different meanings depending on whether |
| 1682 | the overload declaration is visible. Overloads of |
| 1683 | <code>&&</code>, <code>||</code>, and <code>,</code> |
| 1684 | (comma) cannot match the evaluation-order semantics of the |
| 1685 | built-in operators.</li> |
| 1686 | |
| 1687 | <li>Operators are often defined outside the class, |
| 1688 | so there's a risk of different files introducing |
| 1689 | different definitions of the same operator. If both |
| 1690 | definitions are linked into the same binary, this results |
| 1691 | in undefined behavior, which can manifest as subtle |
| 1692 | run-time bugs.</li> |
| 1693 | |
| 1694 | <li>User-defined literals allow the creation of new |
| 1695 | syntactic forms that are unfamiliar even to experienced C++ |
| 1696 | programmers.</li> |
| 1697 | </ul> |
| 1698 | </div> |
| 1699 | |
| 1700 | <div class="decision"> |
| 1701 | <p>Define overloaded operators only if their meaning is |
| 1702 | obvious, unsurprising, and consistent with the corresponding |
| 1703 | built-in operators. For example, use <code>|</code> as a |
| 1704 | bitwise- or logical-or, not as a shell-style pipe.</p> |
| 1705 | |
| 1706 | <p>Define operators only on your own types. More precisely, |
| 1707 | define them in the same headers, .cc files, and namespaces |
| 1708 | as the types they operate on. That way, the operators are available |
| 1709 | wherever the type is, minimizing the risk of multiple |
| 1710 | definitions. If possible, avoid defining operators as templates, |
| 1711 | because they must satisfy this rule for any possible template |
| 1712 | arguments. If you define an operator, also define |
| 1713 | any related operators that make sense, and make sure they |
| 1714 | are defined consistently. For example, if you overload |
| 1715 | <code><</code>, overload all the comparison operators, |
| 1716 | and make sure <code><</code> and <code>></code> never |
| 1717 | return true for the same arguments.</p> |
| 1718 | |
| 1719 | <p>Prefer to define non-modifying binary operators as |
| 1720 | non-member functions. If a binary operator is defined as a |
| 1721 | class member, implicit conversions will apply to the |
| 1722 | right-hand argument, but not the left-hand one. It will |
| 1723 | confuse your users if <code>a < b</code> compiles but |
| 1724 | <code>b < a</code> doesn't.</p> |
| 1725 | |
| 1726 | <p>Don't go out of your way to avoid defining operator |
| 1727 | overloads. For example, prefer to define <code>==</code>, |
| 1728 | <code>=</code>, and <code><<</code>, rather than |
| 1729 | <code>Equals()</code>, <code>CopyFrom()</code>, and |
| 1730 | <code>PrintTo()</code>. Conversely, don't define |
| 1731 | operator overloads just because other libraries expect |
| 1732 | them. For example, if your type doesn't have a natural |
| 1733 | ordering, but you want to store it in a <code>std::set</code>, |
| 1734 | use a custom comparator rather than overloading |
| 1735 | <code><</code>.</p> |
| 1736 | |
| 1737 | <p>Do not overload <code>&&</code>, <code>||</code>, |
| 1738 | <code>,</code> (comma), or unary <code>&</code>. Do not overload |
| 1739 | <code>operator""</code>, i.e. do not introduce user-defined |
| 1740 | literals.</p> |
| 1741 | |
| 1742 | <p>Type conversion operators are covered in the section on |
| 1743 | <a href="#Implicit_Conversions">implicit conversions</a>. |
| 1744 | The <code>=</code> operator is covered in the section on |
| 1745 | <a href="#Copy_Constructors">copy constructors</a>. Overloading |
| 1746 | <code><<</code> for use with streams is covered in the |
| 1747 | section on <a href="#Streams">streams</a>. See also the rules on |
| 1748 | <a href="#Function_Overloading">function overloading</a>, which |
| 1749 | apply to operator overloading as well.</p> |
| 1750 | </div> |
| 1751 | |
| 1752 | </div> |
| 1753 | |
| 1754 | <h3 id="Access_Control">Access Control</h3> |
| 1755 | |
| 1756 | <div class="summary"> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1757 | <p>Make classes' data members <code>private</code>, unless they are |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1758 | <code>static const</code> (and follow the <a href="#Constant_Names"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1759 | naming convention for constants</a>).</p> |
| 1760 | </div> |
| 1761 | |
| 1762 | <div class="stylebody"> |
| 1763 | |
| 1764 | <p>For technical |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1765 | reasons, we allow data members of a test fixture class in a .cc file to |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1766 | be <code>protected</code> when using |
| 1767 | |
| 1768 | |
| 1769 | <a href="https://github.com/google/googletest">Google |
| 1770 | Test</a>).</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1771 | |
| 1772 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1773 | |
| 1774 | <h3 id="Declaration_Order">Declaration Order</h3> |
| 1775 | |
| 1776 | <div class="summary"> |
| 1777 | <p>Group similar declarations together, placing public parts |
| 1778 | earlier.</p> |
| 1779 | </div> |
| 1780 | |
| 1781 | <div class="stylebody"> |
| 1782 | |
| 1783 | <p>A class definition should usually start with a |
| 1784 | <code>public:</code> section, followed by |
| 1785 | <code>protected:</code>, then <code>private:</code>. Omit |
| 1786 | sections that would be empty.</p> |
| 1787 | |
| 1788 | <p>Within each section, generally prefer grouping similar |
| 1789 | kinds of declarations together, and generally prefer the |
| 1790 | following order: types (including <code>typedef</code>, |
| 1791 | <code>using</code>, and nested structs and classes), |
| 1792 | constants, factory functions, constructors, assignment |
| 1793 | operators, destructor, all other methods, data members.</p> |
| 1794 | |
| 1795 | <p>Do not put large method definitions inline in the |
| 1796 | class definition. Usually, only trivial or |
| 1797 | performance-critical, and very short, methods may be |
| 1798 | defined inline. See <a href="#Inline_Functions">Inline |
| 1799 | Functions</a> for more details.</p> |
| 1800 | |
| 1801 | </div> |
| 1802 | |
| 1803 | <h2 id="Functions">Functions</h2> |
| 1804 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1805 | <a id="Function_Parameter_Ordering"></a> |
| 1806 | <h3 id="Output_Parameters">Output Parameters</h3> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1807 | |
| 1808 | <div class="summary"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1809 | <p>Prefer using return values rather than output parameters. |
| 1810 | If output-only parameters are used they should appear after |
| 1811 | input parameters.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1812 | </div> |
| 1813 | |
| 1814 | <div class="stylebody"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1815 | <p>The output of a C++ function is naturally provided via |
| 1816 | a return value and sometimes via output parameters.</p> |
| 1817 | |
| 1818 | <p>Prefer using return values instead of output parameters |
| 1819 | since they improve readability and oftentimes provide the same |
| 1820 | or better performance.</p> |
| 1821 | |
| 1822 | <p>Parameters are either input to the function, output from the |
| 1823 | function, or both. Input parameters are usually values or |
| 1824 | <code>const</code> references, while output and input/output |
| 1825 | parameters will be pointers to non-<code>const</code>.</p> |
| 1826 | |
| 1827 | <p>When ordering function parameters, put all input-only |
| 1828 | parameters before any output parameters. In particular, |
| 1829 | do not add new parameters to the end of the function just |
| 1830 | because they are new; place new input-only parameters before |
| 1831 | the output parameters.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1832 | |
| 1833 | <p>This is not a hard-and-fast rule. Parameters that are |
| 1834 | both input and output (often classes/structs) muddy the |
| 1835 | waters, and, as always, consistency with related |
| 1836 | functions may require you to bend the rule.</p> |
| 1837 | |
| 1838 | </div> |
| 1839 | |
| 1840 | <h3 id="Write_Short_Functions">Write Short Functions</h3> |
| 1841 | |
| 1842 | <div class="summary"> |
| 1843 | <p>Prefer small and focused functions.</p> |
| 1844 | </div> |
| 1845 | |
| 1846 | <div class="stylebody"> |
| 1847 | <p>We recognize that long functions are sometimes |
| 1848 | appropriate, so no hard limit is placed on functions |
| 1849 | length. If a function exceeds about 40 lines, think about |
| 1850 | whether it can be broken up without harming the structure |
| 1851 | of the program.</p> |
| 1852 | |
| 1853 | <p>Even if your long function works perfectly now, |
| 1854 | someone modifying it in a few months may add new |
| 1855 | behavior. This could result in bugs that are hard to |
| 1856 | find. Keeping your functions short and simple makes it |
| 1857 | easier for other people to read and modify your code.</p> |
| 1858 | |
| 1859 | <p>You could find long and complicated functions when |
| 1860 | working with |
| 1861 | some code. Do not be |
| 1862 | intimidated by modifying existing code: if working with |
| 1863 | such a function proves to be difficult, you find that |
| 1864 | errors are hard to debug, or you want to use a piece of |
| 1865 | it in several different contexts, consider breaking up |
| 1866 | the function into smaller and more manageable pieces.</p> |
| 1867 | |
| 1868 | </div> |
| 1869 | |
| 1870 | <h3 id="Reference_Arguments">Reference Arguments</h3> |
| 1871 | |
| 1872 | <div class="summary"> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1873 | <p>All parameters passed by lvalue reference must be labeled |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1874 | <code>const</code>.</p> |
| 1875 | </div> |
| 1876 | |
| 1877 | <div class="stylebody"> |
| 1878 | |
| 1879 | <div class="definition"> |
| 1880 | <p>In C, if a |
| 1881 | function needs to modify a variable, the parameter must |
| 1882 | use a pointer, eg <code>int foo(int *pval)</code>. In |
| 1883 | C++, the function can alternatively declare a reference |
| 1884 | parameter: <code>int foo(int &val)</code>.</p> |
| 1885 | </div> |
| 1886 | |
| 1887 | <div class="pros"> |
| 1888 | <p>Defining a parameter as reference avoids ugly code like |
| 1889 | <code>(*pval)++</code>. Necessary for some applications |
| 1890 | like copy constructors. Makes it clear, unlike with |
| 1891 | pointers, that a null pointer is not a possible |
| 1892 | value.</p> |
| 1893 | </div> |
| 1894 | |
| 1895 | <div class="cons"> |
| 1896 | <p>References can be confusing, as they have value syntax |
| 1897 | but pointer semantics.</p> |
| 1898 | </div> |
| 1899 | |
| 1900 | <div class="decision"> |
| 1901 | <p>Within function parameter lists all references must be |
| 1902 | <code>const</code>:</p> |
| 1903 | |
| 1904 | <pre>void Foo(const string &in, string *out); |
| 1905 | </pre> |
| 1906 | |
| 1907 | <p>In fact it is a very strong convention in Google code |
| 1908 | that input arguments are values or <code>const</code> |
| 1909 | references while output arguments are pointers. Input |
| 1910 | parameters may be <code>const</code> pointers, but we |
| 1911 | never allow non-<code>const</code> reference parameters |
| 1912 | except when required by convention, e.g., |
| 1913 | <code>swap()</code>.</p> |
| 1914 | |
| 1915 | <p>However, there are some instances where using |
| 1916 | <code>const T*</code> is preferable to <code>const |
| 1917 | T&</code> for input parameters. For example:</p> |
| 1918 | |
| 1919 | <ul> |
| 1920 | <li>You want to pass in a null pointer.</li> |
| 1921 | |
| 1922 | <li>The function saves a pointer or reference to the |
| 1923 | input.</li> |
| 1924 | </ul> |
| 1925 | |
| 1926 | <p> Remember that most of the time input |
| 1927 | parameters are going to be specified as <code>const |
| 1928 | T&</code>. Using <code>const T*</code> instead |
| 1929 | communicates to the reader that the input is somehow |
| 1930 | treated differently. So if you choose <code>const |
| 1931 | T*</code> rather than <code>const T&</code>, do so |
| 1932 | for a concrete reason; otherwise it will likely confuse |
| 1933 | readers by making them look for an explanation that |
| 1934 | doesn't exist.</p> |
| 1935 | </div> |
| 1936 | |
| 1937 | </div> |
| 1938 | |
| 1939 | <h3 id="Function_Overloading">Function Overloading</h3> |
| 1940 | |
| 1941 | <div class="summary"> |
| 1942 | <p>Use overloaded functions (including constructors) only if a |
| 1943 | reader looking at a call site can get a good idea of what |
| 1944 | is happening without having to first figure out exactly |
| 1945 | which overload is being called.</p> |
| 1946 | </div> |
| 1947 | |
| 1948 | <div class="stylebody"> |
| 1949 | |
| 1950 | <div class="definition"> |
| 1951 | <p>You may write a function that takes a <code>const |
| 1952 | string&</code> and overload it with another that |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1953 | takes <code>const char*</code>. However, in this case consider |
| 1954 | std::string_view |
| 1955 | instead.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1956 | |
| 1957 | <pre>class MyClass { |
| 1958 | public: |
| 1959 | void Analyze(const string &text); |
| 1960 | void Analyze(const char *text, size_t textlen); |
| 1961 | }; |
| 1962 | </pre> |
| 1963 | </div> |
| 1964 | |
| 1965 | <div class="pros"> |
| 1966 | <p>Overloading can make code more intuitive by allowing an |
| 1967 | identically-named function to take different arguments. |
| 1968 | It may be necessary for templatized code, and it can be |
| 1969 | convenient for Visitors.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1970 | <p>Overloading based on const or ref qualification may make utility |
| 1971 | code more usable, more efficient, or both. |
| 1972 | |
| 1973 | (See <a href="http://abseil.io/tips/148">TotW 148</a> for more.) |
| 1974 | </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1975 | </div> |
| 1976 | |
| 1977 | <div class="cons"> |
| 1978 | <p>If a function is overloaded by the argument types alone, |
| 1979 | a reader may have to understand C++'s complex matching |
| 1980 | rules in order to tell what's going on. Also many people |
| 1981 | are confused by the semantics of inheritance if a derived |
| 1982 | class overrides only some of the variants of a |
| 1983 | function.</p> |
| 1984 | </div> |
| 1985 | |
| 1986 | <div class="decision"> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1987 | <p>You may overload a function when there are no semantic differences |
| 1988 | between variants. These overloads may vary in types, qualifiers, or |
| 1989 | argument count. However, a reader of such a call must not need to know |
| 1990 | which member of the overload set is chosen, only that <b>something</b> |
| 1991 | from the set is being called. If you can document all entries in the |
| 1992 | overload set with a single comment in the header, that is a good sign |
| 1993 | that it is a well-designed overload set.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1994 | </div> |
| 1995 | |
| 1996 | </div> |
| 1997 | |
| 1998 | <h3 id="Default_Arguments">Default Arguments</h3> |
| 1999 | |
| 2000 | <div class="summary"> |
| 2001 | <p>Default arguments are allowed on non-virtual functions |
| 2002 | when the default is guaranteed to always have the same |
| 2003 | value. Follow the same restrictions as for <a href="#Function_Overloading">function overloading</a>, and |
| 2004 | prefer overloaded functions if the readability gained with |
| 2005 | default arguments doesn't outweigh the downsides below.</p> |
| 2006 | </div> |
| 2007 | |
| 2008 | <div class="stylebody"> |
| 2009 | |
| 2010 | <div class="pros"> |
| 2011 | <p>Often you have a function that uses default values, but |
| 2012 | occasionally you want to override the defaults. Default |
| 2013 | parameters allow an easy way to do this without having to |
| 2014 | define many functions for the rare exceptions. Compared |
| 2015 | to overloading the function, default arguments have a |
| 2016 | cleaner syntax, with less boilerplate and a clearer |
| 2017 | distinction between 'required' and 'optional' |
| 2018 | arguments.</p> |
| 2019 | </div> |
| 2020 | |
| 2021 | <div class="cons"> |
| 2022 | <p>Defaulted arguments are another way to achieve the |
| 2023 | semantics of overloaded functions, so all the <a href="#Function_Overloading">reasons not to overload |
| 2024 | functions</a> apply.</p> |
| 2025 | |
| 2026 | <p>The defaults for arguments in a virtual function call are |
| 2027 | determined by the static type of the target object, and |
| 2028 | there's no guarantee that all overrides of a given function |
| 2029 | declare the same defaults.</p> |
| 2030 | |
| 2031 | <p>Default parameters are re-evaluated at each call site, |
| 2032 | which can bloat the generated code. Readers may also expect |
| 2033 | the default's value to be fixed at the declaration instead |
| 2034 | of varying at each call.</p> |
| 2035 | |
| 2036 | <p>Function pointers are confusing in the presence of |
| 2037 | default arguments, since the function signature often |
| 2038 | doesn't match the call signature. Adding |
| 2039 | function overloads avoids these problems.</p> |
| 2040 | </div> |
| 2041 | |
| 2042 | <div class="decision"> |
| 2043 | <p>Default arguments are banned on virtual functions, where |
| 2044 | they don't work properly, and in cases where the specified |
| 2045 | default might not evaluate to the same value depending on |
| 2046 | when it was evaluated. (For example, don't write <code>void |
| 2047 | f(int n = counter++);</code>.)</p> |
| 2048 | |
| 2049 | <p>In some other cases, default arguments can improve the |
| 2050 | readability of their function declarations enough to |
| 2051 | overcome the downsides above, so they are allowed. When in |
| 2052 | doubt, use overloads.</p> |
| 2053 | </div> |
| 2054 | |
| 2055 | </div> |
| 2056 | |
| 2057 | <h3 id="trailing_return">Trailing Return Type Syntax</h3> |
| 2058 | <div class="summary"> |
| 2059 | <p>Use trailing return types only where using the ordinary syntax (leading |
| 2060 | return types) is impractical or much less readable.</p> |
| 2061 | </div> |
| 2062 | |
| 2063 | <div class="definition"> |
| 2064 | <p>C++ allows two different forms of function declarations. In the older |
| 2065 | form, the return type appears before the function name. For example:</p> |
| 2066 | <pre>int foo(int x); |
| 2067 | </pre> |
| 2068 | <p>The new form, introduced in C++11, uses the <code>auto</code> |
| 2069 | keyword before the function name and a trailing return type after |
| 2070 | the argument list. For example, the declaration above could |
| 2071 | equivalently be written:</p> |
| 2072 | <pre>auto foo(int x) -> int; |
| 2073 | </pre> |
| 2074 | <p>The trailing return type is in the function's scope. This doesn't |
| 2075 | make a difference for a simple case like <code>int</code> but it matters |
| 2076 | for more complicated cases, like types declared in class scope or |
| 2077 | types written in terms of the function parameters.</p> |
| 2078 | </div> |
| 2079 | |
| 2080 | <div class="stylebody"> |
| 2081 | <div class="pros"> |
| 2082 | <p>Trailing return types are the only way to explicitly specify the |
| 2083 | return type of a <a href="#Lambda_expressions">lambda expression</a>. |
| 2084 | In some cases the compiler is able to deduce a lambda's return type, |
| 2085 | but not in all cases. Even when the compiler can deduce it automatically, |
| 2086 | sometimes specifying it explicitly would be clearer for readers. |
| 2087 | </p> |
| 2088 | <p>Sometimes it's easier and more readable to specify a return type |
| 2089 | after the function's parameter list has already appeared. This is |
| 2090 | particularly true when the return type depends on template parameters. |
| 2091 | For example:</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2092 | <pre> template <typename T, typename U> |
| 2093 | auto add(T t, U u) -> decltype(t + u); |
| 2094 | </pre> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2095 | versus |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2096 | <pre> template <typename T, typename U> |
| 2097 | decltype(declval<T&>() + declval<U&>()) add(T t, U u); |
| 2098 | </pre> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2099 | </div> |
| 2100 | |
| 2101 | <div class="cons"> |
| 2102 | <p>Trailing return type syntax is relatively new and it has no |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2103 | analogue in C++-like languages such as C and Java, so some readers may |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2104 | find it unfamiliar.</p> |
| 2105 | <p>Existing code bases have an enormous number of function |
| 2106 | declarations that aren't going to get changed to use the new syntax, |
| 2107 | so the realistic choices are using the old syntax only or using a mixture |
| 2108 | of the two. Using a single version is better for uniformity of style.</p> |
| 2109 | </div> |
| 2110 | |
| 2111 | <div class="decision"> |
| 2112 | <p>In most cases, continue to use the older style of function |
| 2113 | declaration where the return type goes before the function name. |
| 2114 | Use the new trailing-return-type form only in cases where it's |
| 2115 | required (such as lambdas) or where, by putting the type after the |
| 2116 | function's parameter list, it allows you to write the type in a much |
| 2117 | more readable way. The latter case should be rare; it's mostly an |
| 2118 | issue in fairly complicated template code, which is |
| 2119 | <a href="#Template_metaprogramming">discouraged in most cases</a>.</p> |
| 2120 | |
| 2121 | </div> |
| 2122 | </div> |
| 2123 | |
| 2124 | <h2 id="Google-Specific_Magic">Google-Specific Magic</h2> |
| 2125 | |
| 2126 | |
| 2127 | |
| 2128 | <p>There are various tricks and utilities that |
| 2129 | we use to make C++ code more robust, and various ways we use |
| 2130 | C++ that may differ from what you see elsewhere.</p> |
| 2131 | |
| 2132 | |
| 2133 | |
| 2134 | <h3 id="Ownership_and_Smart_Pointers">Ownership and Smart Pointers</h3> |
| 2135 | |
| 2136 | <div class="summary"> |
| 2137 | <p>Prefer to have single, fixed owners for dynamically |
| 2138 | allocated objects. Prefer to transfer ownership with smart |
| 2139 | pointers.</p> |
| 2140 | </div> |
| 2141 | |
| 2142 | <div class="stylebody"> |
| 2143 | |
| 2144 | <div class="definition"> |
| 2145 | <p>"Ownership" is a bookkeeping technique for managing |
| 2146 | dynamically allocated memory (and other resources). The |
| 2147 | owner of a dynamically allocated object is an object or |
| 2148 | function that is responsible for ensuring that it is |
| 2149 | deleted when no longer needed. Ownership can sometimes be |
| 2150 | shared, in which case the last owner is typically |
| 2151 | responsible for deleting it. Even when ownership is not |
| 2152 | shared, it can be transferred from one piece of code to |
| 2153 | another.</p> |
| 2154 | |
| 2155 | <p>"Smart" pointers are classes that act like pointers, |
| 2156 | e.g. by overloading the <code>*</code> and |
| 2157 | <code>-></code> operators. Some smart pointer types |
| 2158 | can be used to automate ownership bookkeeping, to ensure |
| 2159 | these responsibilities are met. |
| 2160 | <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr"> |
| 2161 | <code>std::unique_ptr</code></a> is a smart pointer type |
| 2162 | introduced in C++11, which expresses exclusive ownership |
| 2163 | of a dynamically allocated object; the object is deleted |
| 2164 | when the <code>std::unique_ptr</code> goes out of scope. |
| 2165 | It cannot be copied, but can be <em>moved</em> to |
| 2166 | represent ownership transfer. |
| 2167 | <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr"> |
| 2168 | <code>std::shared_ptr</code></a> is a smart pointer type |
| 2169 | that expresses shared ownership of |
| 2170 | a dynamically allocated object. <code>std::shared_ptr</code>s |
| 2171 | can be copied; ownership of the object is shared among |
| 2172 | all copies, and the object is deleted when the last |
| 2173 | <code>std::shared_ptr</code> is destroyed. </p> |
| 2174 | </div> |
| 2175 | |
| 2176 | <div class="pros"> |
| 2177 | <ul> |
| 2178 | <li>It's virtually impossible to manage dynamically |
| 2179 | allocated memory without some sort of ownership |
| 2180 | logic.</li> |
| 2181 | |
| 2182 | <li>Transferring ownership of an object can be cheaper |
| 2183 | than copying it (if copying it is even possible).</li> |
| 2184 | |
| 2185 | <li>Transferring ownership can be simpler than |
| 2186 | 'borrowing' a pointer or reference, because it reduces |
| 2187 | the need to coordinate the lifetime of the object |
| 2188 | between the two users.</li> |
| 2189 | |
| 2190 | <li>Smart pointers can improve readability by making |
| 2191 | ownership logic explicit, self-documenting, and |
| 2192 | unambiguous.</li> |
| 2193 | |
| 2194 | <li>Smart pointers can eliminate manual ownership |
| 2195 | bookkeeping, simplifying the code and ruling out large |
| 2196 | classes of errors.</li> |
| 2197 | |
| 2198 | <li>For const objects, shared ownership can be a simple |
| 2199 | and efficient alternative to deep copying.</li> |
| 2200 | </ul> |
| 2201 | </div> |
| 2202 | |
| 2203 | <div class="cons"> |
| 2204 | <ul> |
| 2205 | <li>Ownership must be represented and transferred via |
| 2206 | pointers (whether smart or plain). Pointer semantics |
| 2207 | are more complicated than value semantics, especially |
| 2208 | in APIs: you have to worry not just about ownership, |
| 2209 | but also aliasing, lifetime, and mutability, among |
| 2210 | other issues.</li> |
| 2211 | |
| 2212 | <li>The performance costs of value semantics are often |
| 2213 | overestimated, so the performance benefits of ownership |
| 2214 | transfer might not justify the readability and |
| 2215 | complexity costs.</li> |
| 2216 | |
| 2217 | <li>APIs that transfer ownership force their clients |
| 2218 | into a single memory management model.</li> |
| 2219 | |
| 2220 | <li>Code using smart pointers is less explicit about |
| 2221 | where the resource releases take place.</li> |
| 2222 | |
| 2223 | <li><code>std::unique_ptr</code> expresses ownership |
| 2224 | transfer using C++11's move semantics, which are |
| 2225 | relatively new and may confuse some programmers.</li> |
| 2226 | |
| 2227 | <li>Shared ownership can be a tempting alternative to |
| 2228 | careful ownership design, obfuscating the design of a |
| 2229 | system.</li> |
| 2230 | |
| 2231 | <li>Shared ownership requires explicit bookkeeping at |
| 2232 | run-time, which can be costly.</li> |
| 2233 | |
| 2234 | <li>In some cases (e.g. cyclic references), objects |
| 2235 | with shared ownership may never be deleted.</li> |
| 2236 | |
| 2237 | <li>Smart pointers are not perfect substitutes for |
| 2238 | plain pointers.</li> |
| 2239 | </ul> |
| 2240 | </div> |
| 2241 | |
| 2242 | <div class="decision"> |
| 2243 | <p>If dynamic allocation is necessary, prefer to keep |
| 2244 | ownership with the code that allocated it. If other code |
| 2245 | needs access to the object, consider passing it a copy, |
| 2246 | or passing a pointer or reference without transferring |
| 2247 | ownership. Prefer to use <code>std::unique_ptr</code> to |
| 2248 | make ownership transfer explicit. For example:</p> |
| 2249 | |
| 2250 | <pre>std::unique_ptr<Foo> FooFactory(); |
| 2251 | void FooConsumer(std::unique_ptr<Foo> ptr); |
| 2252 | </pre> |
| 2253 | |
| 2254 | |
| 2255 | |
| 2256 | <p>Do not design your code to use shared ownership |
| 2257 | without a very good reason. One such reason is to avoid |
| 2258 | expensive copy operations, but you should only do this if |
| 2259 | the performance benefits are significant, and the |
| 2260 | underlying object is immutable (i.e. |
| 2261 | <code>std::shared_ptr<const Foo></code>). If you |
| 2262 | do use shared ownership, prefer to use |
| 2263 | <code>std::shared_ptr</code>.</p> |
| 2264 | |
| 2265 | <p>Never use <code>std::auto_ptr</code>. Instead, use |
| 2266 | <code>std::unique_ptr</code>.</p> |
| 2267 | </div> |
| 2268 | |
| 2269 | </div> |
| 2270 | |
| 2271 | <h3 id="cpplint">cpplint</h3> |
| 2272 | |
| 2273 | <div class="summary"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2274 | <p>Use <code>cpplint.py</code> to detect style errors.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2275 | </div> |
| 2276 | |
| 2277 | <div class="stylebody"> |
| 2278 | |
| 2279 | <p><code>cpplint.py</code> |
| 2280 | is a tool that reads a source file and identifies many |
| 2281 | style errors. It is not perfect, and has both false |
| 2282 | positives and false negatives, but it is still a valuable |
| 2283 | tool. False positives can be ignored by putting <code>// |
| 2284 | NOLINT</code> at the end of the line or |
| 2285 | <code>// NOLINTNEXTLINE</code> in the previous line.</p> |
| 2286 | |
| 2287 | |
| 2288 | |
| 2289 | <p>Some projects have instructions on |
| 2290 | how to run <code>cpplint.py</code> from their project |
| 2291 | tools. If the project you are contributing to does not, |
| 2292 | you can download |
| 2293 | <a href="https://raw.githubusercontent.com/google/styleguide/gh-pages/cpplint/cpplint.py"> |
| 2294 | <code>cpplint.py</code></a> separately.</p> |
| 2295 | |
| 2296 | </div> |
| 2297 | |
| 2298 | |
| 2299 | |
| 2300 | <h2 id="Other_C++_Features">Other C++ Features</h2> |
| 2301 | |
| 2302 | <h3 id="Rvalue_references">Rvalue References</h3> |
| 2303 | |
| 2304 | <div class="summary"> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2305 | <p>Use rvalue references to:</p> |
| 2306 | <ul> |
| 2307 | <li>Define move constructors and move assignment operators.</li> |
| 2308 | |
| 2309 | <li>Define <a href="#Function_Overloading">overload sets</a> with |
| 2310 | const& and && variants if you have evidence that this |
| 2311 | provides meaningfully better performance than passing by value, |
| 2312 | or if you're writing low-overhead generic code that needs to support |
| 2313 | arbitrary types. Beware combinatorial overload sets, that is, seldom |
| 2314 | overload more than one parameter.</li> |
| 2315 | |
| 2316 | <li>Support 'perfect forwarding' in generic code.</li> |
| 2317 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2318 | </div> |
| 2319 | |
| 2320 | <div class="stylebody"> |
| 2321 | |
| 2322 | <div class="definition"> |
| 2323 | <p> Rvalue references |
| 2324 | are a type of reference that can only bind to temporary |
| 2325 | objects. The syntax is similar to traditional reference |
| 2326 | syntax. For example, <code>void f(string&& |
| 2327 | s);</code> declares a function whose argument is an |
| 2328 | rvalue reference to a string.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2329 | |
| 2330 | <p id="Forwarding_references"> When the token '&&' is applied to |
| 2331 | an unqualified template argument in a function |
| 2332 | parameter, special template argument deduction |
| 2333 | rules apply. Such a reference is called forwarding reference.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2334 | </div> |
| 2335 | |
| 2336 | <div class="pros"> |
| 2337 | <ul> |
| 2338 | <li>Defining a move constructor (a constructor taking |
| 2339 | an rvalue reference to the class type) makes it |
| 2340 | possible to move a value instead of copying it. If |
| 2341 | <code>v1</code> is a <code>std::vector<string></code>, |
| 2342 | for example, then <code>auto v2(std::move(v1))</code> |
| 2343 | will probably just result in some simple pointer |
| 2344 | manipulation instead of copying a large amount of data. |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2345 | In many cases this can result in a major performance |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2346 | improvement.</li> |
| 2347 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2348 | <li>Rvalue references make it possible to implement |
| 2349 | types that are movable but not copyable, which can be |
| 2350 | useful for types that have no sensible definition of |
| 2351 | copying but where you might still want to pass them as |
| 2352 | function arguments, put them in containers, etc.</li> |
| 2353 | |
| 2354 | <li><code>std::move</code> is necessary to make |
| 2355 | effective use of some standard-library types, such as |
| 2356 | <code>std::unique_ptr</code>.</li> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2357 | |
| 2358 | <li><a href="#Forwarding_references">Forwarding references</a> which |
| 2359 | use the rvalue reference token, make it possible to write a |
| 2360 | generic function wrapper that forwards its arguments to |
| 2361 | another function, and works whether or not its |
| 2362 | arguments are temporary objects and/or const. |
| 2363 | This is called 'perfect forwarding'.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2364 | </ul> |
| 2365 | </div> |
| 2366 | |
| 2367 | <div class="cons"> |
| 2368 | <ul> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2369 | <li>Rvalue references are not yet widely |
| 2370 | understood. Rules like automatic synthesis of move constructors and reference |
| 2371 | collapsing (the latter refers to the special rules that apply to a T&& |
| 2372 | parameter in a function template) are somewhat obscure.</li> |
| 2373 | |
| 2374 | <li>Rvalue references are often misused. Using rvalue |
| 2375 | references is counter-intuitive in signatures where the argument is expected |
| 2376 | to have a valid specified state after the function call, or where no move |
| 2377 | operation is performed.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2378 | </ul> |
| 2379 | </div> |
| 2380 | |
| 2381 | <div class="decision"> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2382 | <p>You may use rvalue references to define move constructors and move |
| 2383 | assignment operators (as described in <a href="#Copyable_Movable_Types">Copyable and Movable Types</a>). See the <a href="primer#copying_moving">C++ Primer</a> for more information about |
| 2384 | move semantics and <code>std::move</code>.</p> |
| 2385 | |
| 2386 | <p>You may use rvalue references to define pairs of overloads, one taking |
| 2387 | Foo&& and the other taking const Foo&. Usually the preferred |
| 2388 | solution is just to pass by value, but an overloaded pair of functions |
| 2389 | sometimes yields better performance and is sometimes necessary in generic code |
| 2390 | that needs to support a wide variety of types. As always: if you're writing |
| 2391 | more complicated code for the sake of performance, make sure you have evidence |
| 2392 | that it actually helps.</p> |
| 2393 | |
| 2394 | <p>You may use forwarding references in conjunction with <code><a href="http://en.cppreference.com/w/cpp/utility/forward">std::forward</a></code>, |
| 2395 | to support perfect forwarding.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2396 | </div> |
| 2397 | |
| 2398 | </div> |
| 2399 | |
| 2400 | <h3 id="Friends">Friends</h3> |
| 2401 | |
| 2402 | <div class="summary"> |
| 2403 | <p>We allow use of <code>friend</code> classes and functions, |
| 2404 | within reason.</p> |
| 2405 | </div> |
| 2406 | |
| 2407 | <div class="stylebody"> |
| 2408 | |
| 2409 | <p>Friends should usually be defined in the same file so |
| 2410 | that the reader does not have to look in another file to |
| 2411 | find uses of the private members of a class. A common use |
| 2412 | of <code>friend</code> is to have a |
| 2413 | <code>FooBuilder</code> class be a friend of |
| 2414 | <code>Foo</code> so that it can construct the inner state |
| 2415 | of <code>Foo</code> correctly, without exposing this |
| 2416 | state to the world. In some cases it may be useful to |
| 2417 | make a unittest class a friend of the class it tests.</p> |
| 2418 | |
| 2419 | <p>Friends extend, but do not break, the encapsulation |
| 2420 | boundary of a class. In some cases this is better than |
| 2421 | making a member public when you want to give only one |
| 2422 | other class access to it. However, most classes should |
| 2423 | interact with other classes solely through their public |
| 2424 | members.</p> |
| 2425 | |
| 2426 | </div> |
| 2427 | |
| 2428 | <h3 id="Exceptions">Exceptions</h3> |
| 2429 | |
| 2430 | <div class="summary"> |
| 2431 | <p>We do not use C++ exceptions.</p> |
| 2432 | </div> |
| 2433 | |
| 2434 | <div class="stylebody"> |
| 2435 | |
| 2436 | <div class="pros"> |
| 2437 | <ul> |
| 2438 | <li>Exceptions allow higher levels of an application to |
| 2439 | decide how to handle "can't happen" failures in deeply |
| 2440 | nested functions, without the obscuring and error-prone |
| 2441 | bookkeeping of error codes.</li> |
| 2442 | |
| 2443 | |
| 2444 | |
| 2445 | <li>Exceptions are used by most other |
| 2446 | modern languages. Using them in C++ would make it more |
| 2447 | consistent with Python, Java, and the C++ that others |
| 2448 | are familiar with.</li> |
| 2449 | |
| 2450 | <li>Some third-party C++ libraries use exceptions, and |
| 2451 | turning them off internally makes it harder to |
| 2452 | integrate with those libraries.</li> |
| 2453 | |
| 2454 | <li>Exceptions are the only way for a constructor to |
| 2455 | fail. We can simulate this with a factory function or |
| 2456 | an <code>Init()</code> method, but these require heap |
| 2457 | allocation or a new "invalid" state, respectively.</li> |
| 2458 | |
| 2459 | <li>Exceptions are really handy in testing |
| 2460 | frameworks.</li> |
| 2461 | </ul> |
| 2462 | </div> |
| 2463 | |
| 2464 | <div class="cons"> |
| 2465 | <ul> |
| 2466 | <li>When you add a <code>throw</code> statement to an |
| 2467 | existing function, you must examine all of its |
| 2468 | transitive callers. Either they must make at least the |
| 2469 | basic exception safety guarantee, or they must never |
| 2470 | catch the exception and be happy with the program |
| 2471 | terminating as a result. For instance, if |
| 2472 | <code>f()</code> calls <code>g()</code> calls |
| 2473 | <code>h()</code>, and <code>h</code> throws an |
| 2474 | exception that <code>f</code> catches, <code>g</code> |
| 2475 | has to be careful or it may not clean up properly.</li> |
| 2476 | |
| 2477 | <li>More generally, exceptions make the control flow of |
| 2478 | programs difficult to evaluate by looking at code: |
| 2479 | functions may return in places you don't expect. This |
| 2480 | causes maintainability and debugging difficulties. You |
| 2481 | can minimize this cost via some rules on how and where |
| 2482 | exceptions can be used, but at the cost of more that a |
| 2483 | developer needs to know and understand.</li> |
| 2484 | |
| 2485 | <li>Exception safety requires both RAII and different |
| 2486 | coding practices. Lots of supporting machinery is |
| 2487 | needed to make writing correct exception-safe code |
| 2488 | easy. Further, to avoid requiring readers to understand |
| 2489 | the entire call graph, exception-safe code must isolate |
| 2490 | logic that writes to persistent state into a "commit" |
| 2491 | phase. This will have both benefits and costs (perhaps |
| 2492 | where you're forced to obfuscate code to isolate the |
| 2493 | commit). Allowing exceptions would force us to always |
| 2494 | pay those costs even when they're not worth it.</li> |
| 2495 | |
| 2496 | <li>Turning on exceptions adds data to each binary |
| 2497 | produced, increasing compile time (probably slightly) |
| 2498 | and possibly increasing address space pressure. |
| 2499 | </li> |
| 2500 | |
| 2501 | <li>The availability of exceptions may encourage |
| 2502 | developers to throw them when they are not appropriate |
| 2503 | or recover from them when it's not safe to do so. For |
| 2504 | example, invalid user input should not cause exceptions |
| 2505 | to be thrown. We would need to make the style guide |
| 2506 | even longer to document these restrictions!</li> |
| 2507 | </ul> |
| 2508 | </div> |
| 2509 | |
| 2510 | <div class="decision"> |
| 2511 | <p>On their face, the benefits of using exceptions |
| 2512 | outweigh the costs, especially in new projects. However, |
| 2513 | for existing code, the introduction of exceptions has |
| 2514 | implications on all dependent code. If exceptions can be |
| 2515 | propagated beyond a new project, it also becomes |
| 2516 | problematic to integrate the new project into existing |
| 2517 | exception-free code. Because most existing C++ code at |
| 2518 | Google is not prepared to deal with exceptions, it is |
| 2519 | comparatively difficult to adopt new code that generates |
| 2520 | exceptions.</p> |
| 2521 | |
| 2522 | <p>Given that Google's existing code is not |
| 2523 | exception-tolerant, the costs of using exceptions are |
| 2524 | somewhat greater than the costs in a new project. The |
| 2525 | conversion process would be slow and error-prone. We |
| 2526 | don't believe that the available alternatives to |
| 2527 | exceptions, such as error codes and assertions, introduce |
| 2528 | a significant burden. </p> |
| 2529 | |
| 2530 | <p>Our advice against using exceptions is not predicated |
| 2531 | on philosophical or moral grounds, but practical ones. |
| 2532 | Because we'd like to use our open-source |
| 2533 | projects at Google and it's difficult to do so if those |
| 2534 | projects use exceptions, we need to advise against |
| 2535 | exceptions in Google open-source projects as well. |
| 2536 | Things would probably be different if we had to do it all |
| 2537 | over again from scratch.</p> |
| 2538 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2539 | <p>This prohibition also applies to the exception handling related |
| 2540 | features added in C++11, such as |
| 2541 | <code>std::exception_ptr</code> and |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2542 | <code>std::nested_exception</code>.</p> |
| 2543 | |
| 2544 | <p>There is an <a href="#Windows_Code">exception</a> to |
| 2545 | this rule (no pun intended) for Windows code.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2546 | |
| 2547 | </div> |
| 2548 | |
| 2549 | </div> |
| 2550 | |
| 2551 | <h3 id="noexcept"><code>noexcept</code></h3> |
| 2552 | |
| 2553 | <div class="summary"> |
| 2554 | <p>Specify <code>noexcept</code> when it is useful and correct.</p> |
| 2555 | </div> |
| 2556 | |
| 2557 | <div class="stylebody"> |
| 2558 | <div class="definition"> |
| 2559 | <p>The <code>noexcept</code> specifier is used to specify whether |
| 2560 | a function will throw exceptions or not. If an exception |
| 2561 | escapes from a function marked <code>noexcept</code>, the program |
| 2562 | crashes via <code>std::terminate</code>.</p> |
| 2563 | |
| 2564 | <p>The <code>noexcept</code> operator performs a compile-time |
| 2565 | check that returns true if an expression is declared to not |
| 2566 | throw any exceptions.</p> |
| 2567 | |
| 2568 | </div> |
| 2569 | |
| 2570 | <div class="pros"> |
| 2571 | <ul> |
| 2572 | <li>Specifying move constructors as <code>noexcept</code> |
| 2573 | improves performance in some cases, e.g. |
| 2574 | <code>std::vector<T>::resize()</code> moves rather than |
| 2575 | copies the objects if T's move constructor is |
| 2576 | <code>noexcept</code>.</li> |
| 2577 | |
| 2578 | <li>Specifying <code>noexcept</code> on a function can |
| 2579 | trigger compiler optimizations in environments where |
| 2580 | exceptions are enabled, e.g. compiler does not have to |
| 2581 | generate extra code for stack-unwinding, if it knows |
| 2582 | that no exceptions can be thrown due to a |
| 2583 | <code>noexcept</code> specifier.</li> |
| 2584 | </ul> |
| 2585 | </div> |
| 2586 | |
| 2587 | <div class="cons"> |
| 2588 | <ul> |
| 2589 | <li> |
| 2590 | |
| 2591 | In projects following this guide |
| 2592 | that have exceptions disabled it is hard |
| 2593 | to ensure that <code>noexcept</code> |
| 2594 | specifiers are correct, and hard to define what |
| 2595 | correctness even means.</li> |
| 2596 | |
| 2597 | <li>It's hard, if not impossible, to undo <code>noexcept</code> |
| 2598 | because it eliminates a guarantee that callers may be relying |
| 2599 | on, in ways that are hard to detect.</li> |
| 2600 | </ul> |
| 2601 | </div> |
| 2602 | |
| 2603 | <div class="decision"> |
| 2604 | <p>You may use <code>noexcept</code> when it is useful for |
| 2605 | performance if it accurately reflects the intended semantics |
| 2606 | of your function, i.e. that if an exception is somehow thrown |
| 2607 | from within the function body then it represents a fatal error. |
| 2608 | You can assume that <code>noexcept</code> on move constructors |
| 2609 | has a meaningful performance benefit. If you think |
| 2610 | there is significant performance benefit from specifying |
| 2611 | <code>noexcept</code> on some other function, please discuss it |
| 2612 | with |
| 2613 | your project leads.</p> |
| 2614 | |
| 2615 | <p>Prefer unconditional <code>noexcept</code> if exceptions are |
| 2616 | completely disabled (i.e. most Google C++ environments). |
| 2617 | Otherwise, use conditional <code>noexcept</code> specifiers |
| 2618 | with simple conditions, in ways that evaluate false only in |
| 2619 | the few cases where the function could potentially throw. |
| 2620 | The tests might include type traits check on whether the |
| 2621 | involved operation might throw (e.g. |
| 2622 | <code>std::is_nothrow_move_constructible</code> for |
| 2623 | move-constructing objects), or on whether allocation can throw |
| 2624 | (e.g. <code>absl::default_allocator_is_nothrow</code> for |
| 2625 | standard default allocation). Note in many cases the only |
| 2626 | possible cause for an exception is allocation failure (we |
| 2627 | believe move constructors should not throw except due to |
| 2628 | allocation failure), and there are many applications where it’s |
| 2629 | appropriate to treat memory exhaustion as a fatal error rather |
| 2630 | than an exceptional condition that your program should attempt |
| 2631 | to recover from. Even for other |
| 2632 | potential failures you should prioritize interface simplicity |
| 2633 | over supporting all possible exception throwing scenarios: |
| 2634 | instead of writing a complicated <code>noexcept</code> clause |
| 2635 | that depends on whether a hash function can throw, for example, |
| 2636 | simply document that your component doesn’t support hash |
| 2637 | functions throwing and make it unconditionally |
| 2638 | <code>noexcept</code>.</p> |
| 2639 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2640 | </div> |
| 2641 | |
| 2642 | </div> |
| 2643 | |
| 2644 | <h3 id="Run-Time_Type_Information__RTTI_">Run-Time Type |
| 2645 | Information (RTTI)</h3> |
| 2646 | |
| 2647 | <div class="summary"> |
| 2648 | <p>Avoid using Run Time Type Information (RTTI).</p> |
| 2649 | </div> |
| 2650 | |
| 2651 | <div class="stylebody"> |
| 2652 | |
| 2653 | <div class="definition"> |
| 2654 | <p> RTTI allows a |
| 2655 | programmer to query the C++ class of an object at run |
| 2656 | time. This is done by use of <code>typeid</code> or |
| 2657 | <code>dynamic_cast</code>.</p> |
| 2658 | </div> |
| 2659 | |
| 2660 | <div class="cons"> |
| 2661 | <p>Querying the type of an object at run-time frequently |
| 2662 | means a design problem. Needing to know the type of an |
| 2663 | object at runtime is often an indication that the design |
| 2664 | of your class hierarchy is flawed.</p> |
| 2665 | |
| 2666 | <p>Undisciplined use of RTTI makes code hard to maintain. |
| 2667 | It can lead to type-based decision trees or switch |
| 2668 | statements scattered throughout the code, all of which |
| 2669 | must be examined when making further changes.</p> |
| 2670 | </div> |
| 2671 | |
| 2672 | <div class="pros"> |
| 2673 | <p>The standard alternatives to RTTI (described below) |
| 2674 | require modification or redesign of the class hierarchy |
| 2675 | in question. Sometimes such modifications are infeasible |
| 2676 | or undesirable, particularly in widely-used or mature |
| 2677 | code.</p> |
| 2678 | |
| 2679 | <p>RTTI can be useful in some unit tests. For example, it |
| 2680 | is useful in tests of factory classes where the test has |
| 2681 | to verify that a newly created object has the expected |
| 2682 | dynamic type. It is also useful in managing the |
| 2683 | relationship between objects and their mocks.</p> |
| 2684 | |
| 2685 | <p>RTTI is useful when considering multiple abstract |
| 2686 | objects. Consider</p> |
| 2687 | |
| 2688 | <pre>bool Base::Equal(Base* other) = 0; |
| 2689 | bool Derived::Equal(Base* other) { |
| 2690 | Derived* that = dynamic_cast<Derived*>(other); |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2691 | if (that == nullptr) |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2692 | return false; |
| 2693 | ... |
| 2694 | } |
| 2695 | </pre> |
| 2696 | </div> |
| 2697 | |
| 2698 | <div class="decision"> |
| 2699 | <p>RTTI has legitimate uses but is prone to abuse, so you |
| 2700 | must be careful when using it. You may use it freely in |
| 2701 | unittests, but avoid it when possible in other code. In |
| 2702 | particular, think twice before using RTTI in new code. If |
| 2703 | you find yourself needing to write code that behaves |
| 2704 | differently based on the class of an object, consider one |
| 2705 | of the following alternatives to querying the type:</p> |
| 2706 | |
| 2707 | <ul> |
| 2708 | <li>Virtual methods are the preferred way of executing |
| 2709 | different code paths depending on a specific subclass |
| 2710 | type. This puts the work within the object itself.</li> |
| 2711 | |
| 2712 | <li>If the work belongs outside the object and instead |
| 2713 | in some processing code, consider a double-dispatch |
| 2714 | solution, such as the Visitor design pattern. This |
| 2715 | allows a facility outside the object itself to |
| 2716 | determine the type of class using the built-in type |
| 2717 | system.</li> |
| 2718 | </ul> |
| 2719 | |
| 2720 | <p>When the logic of a program guarantees that a given |
| 2721 | instance of a base class is in fact an instance of a |
| 2722 | particular derived class, then a |
| 2723 | <code>dynamic_cast</code> may be used freely on the |
| 2724 | object. Usually one |
| 2725 | can use a <code>static_cast</code> as an alternative in |
| 2726 | such situations.</p> |
| 2727 | |
| 2728 | <p>Decision trees based on type are a strong indication |
| 2729 | that your code is on the wrong track.</p> |
| 2730 | |
| 2731 | <pre class="badcode">if (typeid(*data) == typeid(D1)) { |
| 2732 | ... |
| 2733 | } else if (typeid(*data) == typeid(D2)) { |
| 2734 | ... |
| 2735 | } else if (typeid(*data) == typeid(D3)) { |
| 2736 | ... |
| 2737 | </pre> |
| 2738 | |
| 2739 | <p>Code such as this usually breaks when additional |
| 2740 | subclasses are added to the class hierarchy. Moreover, |
| 2741 | when properties of a subclass change, it is difficult to |
| 2742 | find and modify all the affected code segments.</p> |
| 2743 | |
| 2744 | <p>Do not hand-implement an RTTI-like workaround. The |
| 2745 | arguments against RTTI apply just as much to workarounds |
| 2746 | like class hierarchies with type tags. Moreover, |
| 2747 | workarounds disguise your true intent.</p> |
| 2748 | </div> |
| 2749 | |
| 2750 | </div> |
| 2751 | |
| 2752 | <h3 id="Casting">Casting</h3> |
| 2753 | |
| 2754 | <div class="summary"> |
| 2755 | <p>Use C++-style casts |
| 2756 | like <code>static_cast<float>(double_value)</code>, or brace |
| 2757 | initialization for conversion of arithmetic types like |
| 2758 | <code>int64 y = int64{1} << 42</code>. Do not use |
| 2759 | cast formats like |
| 2760 | <code>int y = (int)x</code> or <code>int y = int(x)</code> (but the latter |
| 2761 | is okay when invoking a constructor of a class type).</p> |
| 2762 | </div> |
| 2763 | |
| 2764 | <div class="stylebody"> |
| 2765 | |
| 2766 | <div class="definition"> |
| 2767 | <p> C++ introduced a |
| 2768 | different cast system from C that distinguishes the types |
| 2769 | of cast operations.</p> |
| 2770 | </div> |
| 2771 | |
| 2772 | <div class="pros"> |
| 2773 | <p>The problem with C casts is the ambiguity of the operation; |
| 2774 | sometimes you are doing a <em>conversion</em> |
| 2775 | (e.g., <code>(int)3.5</code>) and sometimes you are doing |
| 2776 | a <em>cast</em> (e.g., <code>(int)"hello"</code>). Brace |
| 2777 | initialization and C++ casts can often help avoid this |
| 2778 | ambiguity. Additionally, C++ casts are more visible when searching for |
| 2779 | them.</p> |
| 2780 | </div> |
| 2781 | |
| 2782 | <div class="cons"> |
| 2783 | <p>The C++-style cast syntax is verbose and cumbersome.</p> |
| 2784 | </div> |
| 2785 | |
| 2786 | <div class="decision"> |
| 2787 | <p>Do not use C-style casts. Instead, use these C++-style casts when |
| 2788 | explicit type conversion is necessary. </p> |
| 2789 | |
| 2790 | <ul> |
| 2791 | <li>Use brace initialization to convert arithmetic types |
| 2792 | (e.g. <code>int64{x}</code>). This is the safest approach because code |
| 2793 | will not compile if conversion can result in information loss. The |
| 2794 | syntax is also concise.</li> |
| 2795 | |
| 2796 | |
| 2797 | |
| 2798 | <li>Use <code>static_cast</code> as the equivalent of a C-style cast |
| 2799 | that does value conversion, when you need to |
| 2800 | explicitly up-cast a pointer from a class to its superclass, or when |
| 2801 | you need to explicitly cast a pointer from a superclass to a |
| 2802 | subclass. In this last case, you must be sure your object is |
| 2803 | actually an instance of the subclass.</li> |
| 2804 | |
| 2805 | |
| 2806 | |
| 2807 | <li>Use <code>const_cast</code> to remove the |
| 2808 | <code>const</code> qualifier (see <a href="#Use_of_const">const</a>).</li> |
| 2809 | |
| 2810 | <li>Use <code>reinterpret_cast</code> to do unsafe |
| 2811 | conversions of pointer types to and from integer and |
| 2812 | other pointer types. Use this only if you know what you |
| 2813 | are doing and you understand the aliasing issues. |
| 2814 | </li> |
| 2815 | |
| 2816 | |
| 2817 | </ul> |
| 2818 | |
| 2819 | <p>See the <a href="#Run-Time_Type_Information__RTTI_"> |
| 2820 | RTTI section</a> for guidance on the use of |
| 2821 | <code>dynamic_cast</code>.</p> |
| 2822 | </div> |
| 2823 | |
| 2824 | </div> |
| 2825 | |
| 2826 | <h3 id="Streams">Streams</h3> |
| 2827 | |
| 2828 | <div class="summary"> |
| 2829 | <p>Use streams where appropriate, and stick to "simple" |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2830 | usages. Overload <code><<</code> for streaming only for types |
| 2831 | representing values, and write only the user-visible value, not any |
| 2832 | implementation details.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2833 | </div> |
| 2834 | |
| 2835 | <div class="stylebody"> |
| 2836 | |
| 2837 | <div class="definition"> |
| 2838 | <p>Streams are the standard I/O abstraction in C++, as |
| 2839 | exemplified by the standard header <code><iostream></code>. |
| 2840 | They are widely used in Google code, but only for debug logging |
| 2841 | and test diagnostics.</p> |
| 2842 | </div> |
| 2843 | |
| 2844 | <div class="pros"> |
| 2845 | <p>The <code><<</code> and <code>>></code> |
| 2846 | stream operators provide an API for formatted I/O that |
| 2847 | is easily learned, portable, reusable, and extensible. |
| 2848 | <code>printf</code>, by contrast, doesn't even support |
| 2849 | <code>string</code>, to say nothing of user-defined types, |
| 2850 | and is very difficult to use portably. |
| 2851 | <code>printf</code> also obliges you to choose among the |
| 2852 | numerous slightly different versions of that function, |
| 2853 | and navigate the dozens of conversion specifiers.</p> |
| 2854 | |
| 2855 | <p>Streams provide first-class support for console I/O |
| 2856 | via <code>std::cin</code>, <code>std::cout</code>, |
| 2857 | <code>std::cerr</code>, and <code>std::clog</code>. |
| 2858 | The C APIs do as well, but are hampered by the need to |
| 2859 | manually buffer the input. </p> |
| 2860 | </div> |
| 2861 | |
| 2862 | <div class="cons"> |
| 2863 | <ul> |
| 2864 | <li>Stream formatting can be configured by mutating the |
| 2865 | state of the stream. Such mutations are persistent, so |
| 2866 | the behavior of your code can be affected by the entire |
| 2867 | previous history of the stream, unless you go out of your |
| 2868 | way to restore it to a known state every time other code |
| 2869 | might have touched it. User code can not only modify the |
| 2870 | built-in state, it can add new state variables and behaviors |
| 2871 | through a registration system.</li> |
| 2872 | |
| 2873 | <li>It is difficult to precisely control stream output, due |
| 2874 | to the above issues, the way code and data are mixed in |
| 2875 | streaming code, and the use of operator overloading (which |
| 2876 | may select a different overload than you expect).</li> |
| 2877 | |
| 2878 | <li>The practice of building up output through chains |
| 2879 | of <code><<</code> operators interferes with |
| 2880 | internationalization, because it bakes word order into the |
| 2881 | code, and streams' support for localization is <a href="http://www.boost.org/doc/libs/1_48_0/libs/locale/doc/html/rationale.html#rationale_why"> |
| 2882 | flawed</a>.</li> |
| 2883 | |
| 2884 | |
| 2885 | |
| 2886 | |
| 2887 | |
| 2888 | <li>The streams API is subtle and complex, so programmers must |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2889 | develop experience with it in order to use it effectively.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2890 | |
| 2891 | <li>Resolving the many overloads of <code><<</code> is |
| 2892 | extremely costly for the compiler. When used pervasively in a |
| 2893 | large code base, it can consume as much as 20% of the parsing |
| 2894 | and semantic analysis time.</li> |
| 2895 | </ul> |
| 2896 | </div> |
| 2897 | |
| 2898 | <div class="decision"> |
| 2899 | <p>Use streams only when they are the best tool for the job. |
| 2900 | This is typically the case when the I/O is ad-hoc, local, |
| 2901 | human-readable, and targeted at other developers rather than |
| 2902 | end-users. Be consistent with the code around you, and with the |
| 2903 | codebase as a whole; if there's an established tool for |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 2904 | your problem, use that tool instead. |
| 2905 | In particular, |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2906 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 2907 | logging libraries are usually a better |
| 2908 | choice than <code>std::cerr</code> or <code>std::clog</code> |
| 2909 | for diagnostic output, and the libraries in |
| 2910 | |
| 2911 | <code>absl/strings</code> |
| 2912 | or the equivalent are usually a |
| 2913 | better choice than <code>std::stringstream</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2914 | |
| 2915 | <p>Avoid using streams for I/O that faces external users or |
| 2916 | handles untrusted data. Instead, find and use the appropriate |
| 2917 | templating libraries to handle issues like internationalization, |
| 2918 | localization, and security hardening.</p> |
| 2919 | |
| 2920 | <p>If you do use streams, avoid the stateful parts of the |
| 2921 | streams API (other than error state), such as <code>imbue()</code>, |
| 2922 | <code>xalloc()</code>, and <code>register_callback()</code>. |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 2923 | Use explicit formatting functions (see e.g. |
| 2924 | |
| 2925 | <code>absl/strings</code>) |
| 2926 | rather than |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2927 | stream manipulators or formatting flags to control formatting |
| 2928 | details such as number base, precision, or padding.</p> |
| 2929 | |
| 2930 | <p>Overload <code><<</code> as a streaming operator |
| 2931 | for your type only if your type represents a value, and |
| 2932 | <code><<</code> writes out a human-readable string |
| 2933 | representation of that value. Avoid exposing implementation |
| 2934 | details in the output of <code><<</code>; if you need to print |
| 2935 | object internals for debugging, use named functions instead |
| 2936 | (a method named <code>DebugString()</code> is the most common |
| 2937 | convention).</p> |
| 2938 | </div> |
| 2939 | |
| 2940 | </div> |
| 2941 | |
| 2942 | <h3 id="Preincrement_and_Predecrement">Preincrement and Predecrement</h3> |
| 2943 | |
| 2944 | <div class="summary"> |
| 2945 | <p>Use prefix form (<code>++i</code>) of the increment and |
| 2946 | decrement operators with iterators and other template |
| 2947 | objects.</p> |
| 2948 | </div> |
| 2949 | |
| 2950 | <div class="stylebody"> |
| 2951 | |
| 2952 | <div class="definition"> |
| 2953 | <p> When a variable |
| 2954 | is incremented (<code>++i</code> or <code>i++</code>) or |
| 2955 | decremented (<code>--i</code> or <code>i--</code>) and |
| 2956 | the value of the expression is not used, one must decide |
| 2957 | whether to preincrement (decrement) or postincrement |
| 2958 | (decrement).</p> |
| 2959 | </div> |
| 2960 | |
| 2961 | <div class="pros"> |
| 2962 | <p>When the return value is ignored, the "pre" form |
| 2963 | (<code>++i</code>) is never less efficient than the |
| 2964 | "post" form (<code>i++</code>), and is often more |
| 2965 | efficient. This is because post-increment (or decrement) |
| 2966 | requires a copy of <code>i</code> to be made, which is |
| 2967 | the value of the expression. If <code>i</code> is an |
| 2968 | iterator or other non-scalar type, copying <code>i</code> |
| 2969 | could be expensive. Since the two types of increment |
| 2970 | behave the same when the value is ignored, why not just |
| 2971 | always pre-increment?</p> |
| 2972 | </div> |
| 2973 | |
| 2974 | <div class="cons"> |
| 2975 | <p>The tradition developed, in C, of using post-increment |
| 2976 | when the expression value is not used, especially in |
| 2977 | <code>for</code> loops. Some find post-increment easier |
| 2978 | to read, since the "subject" (<code>i</code>) precedes |
| 2979 | the "verb" (<code>++</code>), just like in English.</p> |
| 2980 | </div> |
| 2981 | |
| 2982 | <div class="decision"> |
| 2983 | <p> For simple scalar |
| 2984 | (non-object) values there is no reason to prefer one form |
| 2985 | and we allow either. For iterators and other template |
| 2986 | types, use pre-increment.</p> |
| 2987 | </div> |
| 2988 | |
| 2989 | </div> |
| 2990 | |
| 2991 | <h3 id="Use_of_const">Use of const</h3> |
| 2992 | |
| 2993 | <div class="summary"> |
| 2994 | <p>Use <code>const</code> whenever it makes sense. With C++11, |
| 2995 | <code>constexpr</code> is a better choice for some uses of |
| 2996 | const.</p> |
| 2997 | </div> |
| 2998 | |
| 2999 | <div class="stylebody"> |
| 3000 | |
| 3001 | <div class="definition"> |
| 3002 | <p> Declared variables and parameters can be preceded |
| 3003 | by the keyword <code>const</code> to indicate the variables |
| 3004 | are not changed (e.g., <code>const int foo</code>). Class |
| 3005 | functions can have the <code>const</code> qualifier to |
| 3006 | indicate the function does not change the state of the |
| 3007 | class member variables (e.g., <code>class Foo { int |
| 3008 | Bar(char c) const; };</code>).</p> |
| 3009 | </div> |
| 3010 | |
| 3011 | <div class="pros"> |
| 3012 | <p>Easier for people to understand how variables are being |
| 3013 | used. Allows the compiler to do better type checking, |
| 3014 | and, conceivably, generate better code. Helps people |
| 3015 | convince themselves of program correctness because they |
| 3016 | know the functions they call are limited in how they can |
| 3017 | modify your variables. Helps people know what functions |
| 3018 | are safe to use without locks in multi-threaded |
| 3019 | programs.</p> |
| 3020 | </div> |
| 3021 | |
| 3022 | <div class="cons"> |
| 3023 | <p><code>const</code> is viral: if you pass a |
| 3024 | <code>const</code> variable to a function, that function |
| 3025 | must have <code>const</code> in its prototype (or the |
| 3026 | variable will need a <code>const_cast</code>). This can |
| 3027 | be a particular problem when calling library |
| 3028 | functions.</p> |
| 3029 | </div> |
| 3030 | |
| 3031 | <div class="decision"> |
| 3032 | <p><code>const</code> variables, data members, methods |
| 3033 | and arguments add a level of compile-time type checking; |
| 3034 | it is better to detect errors as soon as possible. |
| 3035 | Therefore we strongly recommend that you use |
| 3036 | <code>const</code> whenever it makes sense to do so:</p> |
| 3037 | |
| 3038 | <ul> |
| 3039 | <li>If a function guarantees that it will not modify an argument |
| 3040 | passed by reference or by pointer, the corresponding function parameter |
| 3041 | should be a reference-to-const (<code>const T&</code>) or |
| 3042 | pointer-to-const (<code>const T*</code>), respectively.</li> |
| 3043 | |
| 3044 | <li>Declare methods to be <code>const</code> whenever |
| 3045 | possible. Accessors should almost always be |
| 3046 | <code>const</code>. Other methods should be const if |
| 3047 | they do not modify any data members, do not call any |
| 3048 | non-<code>const</code> methods, and do not return a |
| 3049 | non-<code>const</code> pointer or |
| 3050 | non-<code>const</code> reference to a data member.</li> |
| 3051 | |
| 3052 | <li>Consider making data members <code>const</code> |
| 3053 | whenever they do not need to be modified after |
| 3054 | construction.</li> |
| 3055 | </ul> |
| 3056 | |
| 3057 | <p>The <code>mutable</code> keyword is allowed but is |
| 3058 | unsafe when used with threads, so thread safety should be |
| 3059 | carefully considered first.</p> |
| 3060 | </div> |
| 3061 | |
| 3062 | <div class="stylepoint_subsection"> |
| 3063 | <h4>Where to put the const</h4> |
| 3064 | |
| 3065 | <p>Some people favor the form <code>int const *foo</code> |
| 3066 | to <code>const int* foo</code>. They argue that this is |
| 3067 | more readable because it's more consistent: it keeps the |
| 3068 | rule that <code>const</code> always follows the object |
| 3069 | it's describing. However, this consistency argument |
| 3070 | doesn't apply in codebases with few deeply-nested pointer |
| 3071 | expressions since most <code>const</code> expressions |
| 3072 | have only one <code>const</code>, and it applies to the |
| 3073 | underlying value. In such cases, there's no consistency |
| 3074 | to maintain. Putting the <code>const</code> first is |
| 3075 | arguably more readable, since it follows English in |
| 3076 | putting the "adjective" (<code>const</code>) before the |
| 3077 | "noun" (<code>int</code>).</p> |
| 3078 | |
| 3079 | <p>That said, while we encourage putting |
| 3080 | <code>const</code> first, we do not require it. But be |
| 3081 | consistent with the code around you!</p> |
| 3082 | </div> |
| 3083 | |
| 3084 | </div> |
| 3085 | |
| 3086 | <h3 id="Use_of_constexpr">Use of constexpr</h3> |
| 3087 | |
| 3088 | <div class="summary"> |
| 3089 | <p>In C++11, use <code>constexpr</code> to define true |
| 3090 | constants or to ensure constant initialization.</p> |
| 3091 | </div> |
| 3092 | |
| 3093 | <div class="stylebody"> |
| 3094 | |
| 3095 | <div class="definition"> |
| 3096 | <p> Some variables can be declared <code>constexpr</code> |
| 3097 | to indicate the variables are true constants, i.e. fixed at |
| 3098 | compilation/link time. Some functions and constructors |
| 3099 | can be declared <code>constexpr</code> which enables them |
| 3100 | to be used in defining a <code>constexpr</code> |
| 3101 | variable.</p> |
| 3102 | </div> |
| 3103 | |
| 3104 | <div class="pros"> |
| 3105 | <p>Use of <code>constexpr</code> enables definition of |
| 3106 | constants with floating-point expressions rather than |
| 3107 | just literals; definition of constants of user-defined |
| 3108 | types; and definition of constants with function |
| 3109 | calls.</p> |
| 3110 | </div> |
| 3111 | |
| 3112 | <div class="cons"> |
| 3113 | <p>Prematurely marking something as constexpr may cause |
| 3114 | migration problems if later on it has to be downgraded. |
| 3115 | Current restrictions on what is allowed in constexpr |
| 3116 | functions and constructors may invite obscure workarounds |
| 3117 | in these definitions.</p> |
| 3118 | </div> |
| 3119 | |
| 3120 | <div class="decision"> |
| 3121 | <p><code>constexpr</code> definitions enable a more |
| 3122 | robust specification of the constant parts of an |
| 3123 | interface. Use <code>constexpr</code> to specify true |
| 3124 | constants and the functions that support their |
| 3125 | definitions. Avoid complexifying function definitions to |
| 3126 | enable their use with <code>constexpr</code>. Do not use |
| 3127 | <code>constexpr</code> to force inlining.</p> |
| 3128 | </div> |
| 3129 | |
| 3130 | </div> |
| 3131 | |
| 3132 | <h3 id="Integer_Types">Integer Types</h3> |
| 3133 | |
| 3134 | <div class="summary"> |
| 3135 | <p>Of the built-in C++ integer types, the only one used |
| 3136 | is |
| 3137 | <code>int</code>. If a program needs a variable of a |
| 3138 | different size, use |
| 3139 | a precise-width integer type from |
| 3140 | <code><stdint.h></code>, such as |
| 3141 | <code>int16_t</code>. If your variable represents a |
| 3142 | value that could ever be greater than or equal to 2^31 |
| 3143 | (2GiB), use a 64-bit type such as |
| 3144 | <code>int64_t</code>. |
| 3145 | Keep in mind that even if your value won't ever be too large |
| 3146 | for an <code>int</code>, it may be used in intermediate |
| 3147 | calculations which may require a larger type. When in doubt, |
| 3148 | choose a larger type.</p> |
| 3149 | </div> |
| 3150 | |
| 3151 | <div class="stylebody"> |
| 3152 | |
| 3153 | <div class="definition"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3154 | <p> C++ does not specify the sizes of integer types |
| 3155 | like <code>int</code>. Typically people assume |
| 3156 | that <code>short</code> is 16 bits, |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3157 | <code>int</code> is 32 bits, <code>long</code> is 32 bits |
| 3158 | and <code>long long</code> is 64 bits.</p> |
| 3159 | </div> |
| 3160 | |
| 3161 | <div class="pros"> |
| 3162 | <p>Uniformity of declaration.</p> |
| 3163 | </div> |
| 3164 | |
| 3165 | <div class="cons"> |
| 3166 | <p>The sizes of integral types in C++ can vary based on |
| 3167 | compiler and architecture.</p> |
| 3168 | </div> |
| 3169 | |
| 3170 | <div class="decision"> |
| 3171 | |
| 3172 | <p> |
| 3173 | <code><stdint.h></code> defines types |
| 3174 | like <code>int16_t</code>, <code>uint32_t</code>, |
| 3175 | <code>int64_t</code>, etc. You should always use |
| 3176 | those in preference to <code>short</code>, <code>unsigned |
| 3177 | long long</code> and the like, when you need a guarantee |
| 3178 | on the size of an integer. Of the C integer types, only |
| 3179 | <code>int</code> should be used. When appropriate, you |
| 3180 | are welcome to use standard types like |
| 3181 | <code>size_t</code> and <code>ptrdiff_t</code>.</p> |
| 3182 | |
| 3183 | <p>We use <code>int</code> very often, for integers we |
| 3184 | know are not going to be too big, e.g., loop counters. |
| 3185 | Use plain old <code>int</code> for such things. You |
| 3186 | should assume that an <code>int</code> is |
| 3187 | |
| 3188 | at least 32 bits, but don't |
| 3189 | assume that it has more than 32 bits. If you need a 64-bit |
| 3190 | integer type, use |
| 3191 | <code>int64_t</code> |
| 3192 | or |
| 3193 | <code>uint64_t</code>.</p> |
| 3194 | |
| 3195 | <p>For integers we know can be "big", |
| 3196 | use |
| 3197 | <code>int64_t</code>. |
| 3198 | </p> |
| 3199 | |
| 3200 | <p>You should not use the unsigned integer types such as |
| 3201 | <code>uint32_t</code>, unless there is a valid |
| 3202 | reason such as representing a bit pattern rather than a |
| 3203 | number, or you need defined overflow modulo 2^N. In |
| 3204 | particular, do not use unsigned types to say a number |
| 3205 | will never be negative. Instead, use |
| 3206 | assertions for this.</p> |
| 3207 | |
| 3208 | |
| 3209 | |
| 3210 | <p>If your code is a container that returns a size, be |
| 3211 | sure to use a type that will accommodate any possible |
| 3212 | usage of your container. When in doubt, use a larger type |
| 3213 | rather than a smaller type.</p> |
| 3214 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3215 | <p>Use care when converting integer types. Integer conversions and |
| 3216 | promotions can cause undefined behavior, leading to security bugs and |
| 3217 | other problems.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3218 | </div> |
| 3219 | |
| 3220 | <div class="stylepoint_subsection"> |
| 3221 | |
| 3222 | <h4>On Unsigned Integers</h4> |
| 3223 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3224 | <p>Unsigned integers are good for representing bitfields and modular |
| 3225 | arithmetic. Because of historical accident, the C++ standard also uses |
| 3226 | unsigned integers to represent the size of containers - many members |
| 3227 | of the standards body believe this to be a mistake, but it is |
| 3228 | effectively impossible to fix at this point. The fact that unsigned |
| 3229 | arithmetic doesn't model the behavior of a simple integer, but is |
| 3230 | instead defined by the standard to model modular arithmetic (wrapping |
| 3231 | around on overflow/underflow), means that a significant class of bugs |
| 3232 | cannot be diagnosed by the compiler. In other cases, the defined |
| 3233 | behavior impedes optimization.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3234 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3235 | <p>That said, mixing signedness of integer types is responsible for an |
| 3236 | equally large class of problems. The best advice we can provide: try |
| 3237 | to use iterators and containers rather than pointers and sizes, try |
| 3238 | not to mix signedness, and try to avoid unsigned types (except for |
| 3239 | representing bitfields or modular arithmetic). Do not use an unsigned |
| 3240 | type merely to assert that a variable is non-negative.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3241 | </div> |
| 3242 | |
| 3243 | </div> |
| 3244 | |
| 3245 | <h3 id="64-bit_Portability">64-bit Portability</h3> |
| 3246 | |
| 3247 | <div class="summary"> |
| 3248 | <p>Code should be 64-bit and 32-bit friendly. Bear in mind |
| 3249 | problems of printing, comparisons, and structure alignment.</p> |
| 3250 | </div> |
| 3251 | |
| 3252 | <div class="stylebody"> |
| 3253 | |
| 3254 | <ul> |
| 3255 | <li> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3256 | <p>Correct portable <code>printf()</code> conversion specifiers for |
| 3257 | some integral typedefs rely on macro expansions that we find unpleasant to |
| 3258 | use and impractical to require (the <code>PRI</code> macros from |
| 3259 | <code><cinttypes></code>). Unless there is no reasonable alternative |
| 3260 | for your particular case, try to avoid or even upgrade APIs that rely on the |
| 3261 | <code>printf</code> family. Instead use a library supporting typesafe numeric |
| 3262 | formatting, such as |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 3263 | |
| 3264 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/strings/str_cat.h"><code>StrCat</code></a> |
| 3265 | or |
| 3266 | |
| 3267 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/strings/substitute.h"><code>Substitute</code></a> |
| 3268 | for fast simple conversions, |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3269 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 3270 | or <a href="#Streams"><code>std::ostream</code></a>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3271 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3272 | <p>Unfortunately, the <code>PRI</code> macros are the only portable way to |
| 3273 | specify a conversion for the standard bitwidth typedefs (e.g. |
| 3274 | <code>int64_t</code>, <code>uint64_t</code>, <code>int32_t</code>, |
| 3275 | <code>uint32_t</code>, etc). |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3276 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3277 | Where possible, avoid passing arguments of types specified by bitwidth |
| 3278 | typedefs to <code>printf</code>-based APIs. Note that it is acceptable |
| 3279 | to use typedefs for which printf has dedicated length modifiers, such as |
| 3280 | <code>size_t</code> (<code>z</code>), |
| 3281 | <code>ptrdiff_t</code> (<code>t</code>), and |
| 3282 | <code>maxint_t</code> (<code>j</code>).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3283 | </li> |
| 3284 | |
| 3285 | <li>Remember that <code>sizeof(void *)</code> != |
| 3286 | <code>sizeof(int)</code>. Use <code>intptr_t</code> if |
| 3287 | you want a pointer-sized integer.</li> |
| 3288 | |
| 3289 | <li>You may need to be careful with structure |
| 3290 | alignments, particularly for structures being stored on |
| 3291 | disk. Any class/structure with a |
| 3292 | <code>int64_t</code>/<code>uint64_t</code> |
| 3293 | member will by default end up being 8-byte aligned on a |
| 3294 | 64-bit system. If you have such structures being shared |
| 3295 | on disk between 32-bit and 64-bit code, you will need |
| 3296 | to ensure that they are packed the same on both |
| 3297 | architectures. |
| 3298 | Most compilers offer a way to |
| 3299 | alter structure alignment. For gcc, you can use |
| 3300 | <code>__attribute__((packed))</code>. MSVC offers |
| 3301 | <code>#pragma pack()</code> and |
| 3302 | <code>__declspec(align())</code>.</li> |
| 3303 | |
| 3304 | <li> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3305 | <p>Use <a href="#Casting">braced-initialization</a> as needed to create |
| 3306 | 64-bit constants. For example:</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3307 | |
| 3308 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3309 | <pre>int64_t my_value{0x123456789}; |
| 3310 | uint64_t my_mask{3ULL << 48}; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3311 | </pre> |
| 3312 | </li> |
| 3313 | </ul> |
| 3314 | |
| 3315 | </div> |
| 3316 | |
| 3317 | <h3 id="Preprocessor_Macros">Preprocessor Macros</h3> |
| 3318 | |
| 3319 | <div class="summary"> |
| 3320 | <p>Avoid defining macros, especially in headers; prefer |
| 3321 | inline functions, enums, and <code>const</code> variables. |
| 3322 | Name macros with a project-specific prefix. Do not use |
| 3323 | macros to define pieces of a C++ API.</p> |
| 3324 | </div> |
| 3325 | |
| 3326 | <div class="stylebody"> |
| 3327 | |
| 3328 | <p>Macros mean that the code you see is not the same as |
| 3329 | the code the compiler sees. This can introduce unexpected |
| 3330 | behavior, especially since macros have global scope.</p> |
| 3331 | |
| 3332 | <p>The problems introduced by macros are especially severe |
| 3333 | when they are used to define pieces of a C++ API, |
| 3334 | and still more so for public APIs. Every error message from |
| 3335 | the compiler when developers incorrectly use that interface |
| 3336 | now must explain how the macros formed the interface. |
| 3337 | Refactoring and analysis tools have a dramatically harder |
| 3338 | time updating the interface. As a consequence, we |
| 3339 | specifically disallow using macros in this way. |
| 3340 | For example, avoid patterns like:</p> |
| 3341 | |
| 3342 | <pre class="badcode">class WOMBAT_TYPE(Foo) { |
| 3343 | // ... |
| 3344 | |
| 3345 | public: |
| 3346 | EXPAND_PUBLIC_WOMBAT_API(Foo) |
| 3347 | |
| 3348 | EXPAND_WOMBAT_COMPARISONS(Foo, ==, <) |
| 3349 | }; |
| 3350 | </pre> |
| 3351 | |
| 3352 | <p>Luckily, macros are not nearly as necessary in C++ as |
| 3353 | they are in C. Instead of using a macro to inline |
| 3354 | performance-critical code, use an inline function. |
| 3355 | Instead of using a macro to store a constant, use a |
| 3356 | <code>const</code> variable. Instead of using a macro to |
| 3357 | "abbreviate" a long variable name, use a reference. |
| 3358 | Instead of using a macro to conditionally compile code |
| 3359 | ... well, don't do that at all (except, of course, for |
| 3360 | the <code>#define</code> guards to prevent double |
| 3361 | inclusion of header files). It makes testing much more |
| 3362 | difficult.</p> |
| 3363 | |
| 3364 | <p>Macros can do things these other techniques cannot, |
| 3365 | and you do see them in the codebase, especially in the |
| 3366 | lower-level libraries. And some of their special features |
| 3367 | (like stringifying, concatenation, and so forth) are not |
| 3368 | available through the language proper. But before using a |
| 3369 | macro, consider carefully whether there's a non-macro way |
| 3370 | to achieve the same result. If you need to use a macro to |
| 3371 | define an interface, contact |
| 3372 | your project leads to request |
| 3373 | a waiver of this rule.</p> |
| 3374 | |
| 3375 | <p>The following usage pattern will avoid many problems |
| 3376 | with macros; if you use macros, follow it whenever |
| 3377 | possible:</p> |
| 3378 | |
| 3379 | <ul> |
| 3380 | <li>Don't define macros in a <code>.h</code> file.</li> |
| 3381 | |
| 3382 | <li><code>#define</code> macros right before you use |
| 3383 | them, and <code>#undef</code> them right after.</li> |
| 3384 | |
| 3385 | <li>Do not just <code>#undef</code> an existing macro |
| 3386 | before replacing it with your own; instead, pick a name |
| 3387 | that's likely to be unique.</li> |
| 3388 | |
| 3389 | <li>Try not to use macros that expand to unbalanced C++ |
| 3390 | constructs, or at least document that behavior |
| 3391 | well.</li> |
| 3392 | |
| 3393 | <li>Prefer not using <code>##</code> to generate |
| 3394 | function/class/variable names.</li> |
| 3395 | </ul> |
| 3396 | |
| 3397 | <p>Exporting macros from headers (i.e. defining them in a header |
| 3398 | without <code>#undef</code>ing them before the end of the header) |
| 3399 | is extremely strongly discouraged. If you do export a macro from a |
| 3400 | header, it must have a globally unique name. To achieve this, it |
| 3401 | must be named with a prefix consisting of your project's namespace |
| 3402 | name (but upper case). </p> |
| 3403 | |
| 3404 | </div> |
| 3405 | |
| 3406 | <h3 id="0_and_nullptr/NULL">0 and nullptr/NULL</h3> |
| 3407 | |
| 3408 | <div class="summary"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3409 | <p>Use <code>0</code> for integers, <code>0.0</code> for reals, |
| 3410 | <code>nullptr</code> for pointers, and <code>'\0'</code> for chars.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3411 | </div> |
| 3412 | |
| 3413 | <div class="stylebody"> |
| 3414 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3415 | <p>Use <code>0</code> for integers and <code>0.0</code> for reals.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3416 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 3417 | <p>For pointers (address values), use <code>nullptr</code>, as this |
| 3418 | provides type-safety.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3419 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3420 | <p>For C++03 projects, prefer <code>NULL</code> to <code>0</code>. While the |
| 3421 | values are equivalent, <code>NULL</code> looks more like a pointer to the |
| 3422 | reader, and some C++ compilers provide special definitions of <code>NULL</code> |
| 3423 | which enable them to give useful warnings.</p> |
| 3424 | |
| 3425 | <p>Use <code>'\0'</code> for the null character. Using the correct type makes |
| 3426 | the code more readable.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3427 | |
| 3428 | </div> |
| 3429 | |
| 3430 | <h3 id="sizeof">sizeof</h3> |
| 3431 | |
| 3432 | <div class="summary"> |
| 3433 | <p>Prefer <code>sizeof(<var>varname</var>)</code> to |
| 3434 | <code>sizeof(<var>type</var>)</code>.</p> |
| 3435 | </div> |
| 3436 | |
| 3437 | <div class="stylebody"> |
| 3438 | |
| 3439 | <p>Use <code>sizeof(<var>varname</var>)</code> when you |
| 3440 | take the size of a particular variable. |
| 3441 | <code>sizeof(<var>varname</var>)</code> will update |
| 3442 | appropriately if someone changes the variable type either |
| 3443 | now or later. You may use |
| 3444 | <code>sizeof(<var>type</var>)</code> for code unrelated |
| 3445 | to any particular variable, such as code that manages an |
| 3446 | external or internal data format where a variable of an |
| 3447 | appropriate C++ type is not convenient.</p> |
| 3448 | |
| 3449 | <pre>Struct data; |
| 3450 | memset(&data, 0, sizeof(data)); |
| 3451 | </pre> |
| 3452 | |
| 3453 | <pre class="badcode">memset(&data, 0, sizeof(Struct)); |
| 3454 | </pre> |
| 3455 | |
| 3456 | <pre>if (raw_size < sizeof(int)) { |
| 3457 | LOG(ERROR) << "compressed record not big enough for count: " << raw_size; |
| 3458 | return false; |
| 3459 | } |
| 3460 | </pre> |
| 3461 | |
| 3462 | </div> |
| 3463 | |
| 3464 | <h3 id="auto">auto</h3> |
| 3465 | |
| 3466 | <div class="summary"> |
| 3467 | <p>Use <code>auto</code> to avoid type names that are noisy, obvious, |
| 3468 | or unimportant - cases where the type doesn't aid in clarity for the |
| 3469 | reader. Continue to use manifest type declarations when it helps |
| 3470 | readability.</p> |
| 3471 | </div> |
| 3472 | |
| 3473 | <div class="stylebody"> |
| 3474 | |
| 3475 | <div class="pros"> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3476 | |
| 3477 | <ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3478 | <li>C++ type names can be long and cumbersome, especially when they |
| 3479 | involve templates or namespaces.</li> |
| 3480 | <li>When a C++ type name is repeated within a single declaration or a |
| 3481 | small code region, the repetition may not be aiding readability.</li> |
| 3482 | <li>It is sometimes safer to let the type be specified by the type of |
| 3483 | the initialization expression, since that avoids the possibility of |
| 3484 | unintended copies or type conversions.</li> |
| 3485 | </ul> |
| 3486 | </div> |
| 3487 | <div class="cons"> |
| 3488 | |
| 3489 | <p>Sometimes code is clearer when types are manifest, |
| 3490 | especially when a variable's initialization depends on |
| 3491 | things that were declared far away. In expressions |
| 3492 | like:</p> |
| 3493 | |
| 3494 | <pre class="badcode">auto foo = x.add_foo(); |
| 3495 | auto i = y.Find(key); |
| 3496 | </pre> |
| 3497 | |
| 3498 | <p>it may not be obvious what the resulting types are if the type |
| 3499 | of <code>y</code> isn't very well known, or if <code>y</code> was |
| 3500 | declared many lines earlier.</p> |
| 3501 | |
| 3502 | <p>Programmers have to understand the difference between |
| 3503 | <code>auto</code> and <code>const auto&</code> or |
| 3504 | they'll get copies when they didn't mean to.</p> |
| 3505 | |
| 3506 | <p>If an <code>auto</code> variable is used as part of an |
| 3507 | interface, e.g. as a constant in a header, then a |
| 3508 | programmer might change its type while only intending to |
| 3509 | change its value, leading to a more radical API change |
| 3510 | than intended.</p> |
| 3511 | </div> |
| 3512 | |
| 3513 | <div class="decision"> |
| 3514 | |
| 3515 | <p><code>auto</code> is permitted when it increases readability, |
| 3516 | particularly as described below. Never initialize an <code>auto</code>-typed |
| 3517 | variable with a braced initializer list.</p> |
| 3518 | |
| 3519 | <p>Specific cases where <code>auto</code> is allowed or encouraged: |
| 3520 | </p><ul> |
| 3521 | <li>(Encouraged) For iterators and other long/cluttery type names, particularly |
| 3522 | when the type is clear from context (calls |
| 3523 | to <code>find</code>, <code>begin</code>, or <code>end</code> for |
| 3524 | instance).</li> |
| 3525 | <li>(Allowed) When the type is clear from local context (in the same expression |
| 3526 | or within a few lines). Initialization of a pointer or smart pointer |
| 3527 | with calls |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 3528 | to <code>new</code> and |
| 3529 | <code>std::make_unique</code> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3530 | commonly falls into this category, as does use of <code>auto</code> in |
| 3531 | a range-based loop over a container whose type is spelled out |
| 3532 | nearby.</li> |
| 3533 | <li>(Allowed) When the type doesn't matter because it isn't being used for |
| 3534 | anything other than equality comparison.</li> |
| 3535 | <li>(Encouraged) When iterating over a map with a range-based loop |
| 3536 | (because it is often assumed that the correct type |
| 3537 | is <code>std::pair<KeyType, ValueType></code> whereas it is actually |
| 3538 | <code>std::pair<const KeyType, ValueType></code>). This is |
| 3539 | particularly well paired with local <code>key</code> |
| 3540 | and <code>value</code> aliases for <code>.first</code> |
| 3541 | and <code>.second</code> (often const-ref). |
| 3542 | <pre class="code">for (const auto& item : some_map) { |
| 3543 | const KeyType& key = item.first; |
| 3544 | const ValType& value = item.second; |
| 3545 | // The rest of the loop can now just refer to key and value, |
| 3546 | // a reader can see the types in question, and we've avoided |
| 3547 | // the too-common case of extra copies in this iteration. |
| 3548 | } |
| 3549 | </pre> |
| 3550 | </li> |
| 3551 | </ul> |
| 3552 | |
| 3553 | </div> |
| 3554 | |
| 3555 | </div> |
| 3556 | |
| 3557 | <h3 id="Braced_Initializer_List">Braced Initializer List</h3> |
| 3558 | |
| 3559 | <div class="summary"> |
| 3560 | <p>You may use braced initializer lists.</p> |
| 3561 | </div> |
| 3562 | |
| 3563 | <div class="stylebody"> |
| 3564 | |
| 3565 | <p>In C++03, aggregate types (arrays and structs with no |
| 3566 | constructor) could be initialized with braced initializer lists.</p> |
| 3567 | |
| 3568 | <pre>struct Point { int x; int y; }; |
| 3569 | Point p = {1, 2}; |
| 3570 | </pre> |
| 3571 | |
| 3572 | <p>In C++11, this syntax was generalized, and any object type can now |
| 3573 | be created with a braced initializer list, known as a |
| 3574 | <i>braced-init-list</i> in the C++ grammar. Here are a few examples |
| 3575 | of its use.</p> |
| 3576 | |
| 3577 | <pre>// Vector takes a braced-init-list of elements. |
| 3578 | std::vector<string> v{"foo", "bar"}; |
| 3579 | |
| 3580 | // Basically the same, ignoring some small technicalities. |
| 3581 | // You may choose to use either form. |
| 3582 | std::vector<string> v = {"foo", "bar"}; |
| 3583 | |
| 3584 | // Usable with 'new' expressions. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3585 | auto p = new std::vector<string>{"foo", "bar"}; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3586 | |
| 3587 | // A map can take a list of pairs. Nested braced-init-lists work. |
| 3588 | std::map<int, string> m = {{1, "one"}, {2, "2"}}; |
| 3589 | |
| 3590 | // A braced-init-list can be implicitly converted to a return type. |
| 3591 | std::vector<int> test_function() { return {1, 2, 3}; } |
| 3592 | |
| 3593 | // Iterate over a braced-init-list. |
| 3594 | for (int i : {-1, -2, -3}) {} |
| 3595 | |
| 3596 | // Call a function using a braced-init-list. |
| 3597 | void TestFunction2(std::vector<int> v) {} |
| 3598 | TestFunction2({1, 2, 3}); |
| 3599 | </pre> |
| 3600 | |
| 3601 | <p>A user-defined type can also define a constructor and/or assignment operator |
| 3602 | that take <code>std::initializer_list<T></code>, which is automatically |
| 3603 | created from <i>braced-init-list</i>:</p> |
| 3604 | |
| 3605 | <pre>class MyType { |
| 3606 | public: |
| 3607 | // std::initializer_list references the underlying init list. |
| 3608 | // It should be passed by value. |
| 3609 | MyType(std::initializer_list<int> init_list) { |
| 3610 | for (int i : init_list) append(i); |
| 3611 | } |
| 3612 | MyType& operator=(std::initializer_list<int> init_list) { |
| 3613 | clear(); |
| 3614 | for (int i : init_list) append(i); |
| 3615 | } |
| 3616 | }; |
| 3617 | MyType m{2, 3, 5, 7}; |
| 3618 | </pre> |
| 3619 | |
| 3620 | <p>Finally, brace initialization can also call ordinary |
| 3621 | constructors of data types, even if they do not have |
| 3622 | <code>std::initializer_list<T></code> constructors.</p> |
| 3623 | |
| 3624 | <pre>double d{1.23}; |
| 3625 | // Calls ordinary constructor as long as MyOtherType has no |
| 3626 | // std::initializer_list constructor. |
| 3627 | class MyOtherType { |
| 3628 | public: |
| 3629 | explicit MyOtherType(string); |
| 3630 | MyOtherType(int, string); |
| 3631 | }; |
| 3632 | MyOtherType m = {1, "b"}; |
| 3633 | // If the constructor is explicit, you can't use the "= {}" form. |
| 3634 | MyOtherType m{"b"}; |
| 3635 | </pre> |
| 3636 | |
| 3637 | <p>Never assign a <i>braced-init-list</i> to an auto |
| 3638 | local variable. In the single element case, what this |
| 3639 | means can be confusing.</p> |
| 3640 | |
| 3641 | <pre class="badcode">auto d = {1.23}; // d is a std::initializer_list<double> |
| 3642 | </pre> |
| 3643 | |
| 3644 | <pre>auto d = double{1.23}; // Good -- d is a double, not a std::initializer_list. |
| 3645 | </pre> |
| 3646 | |
| 3647 | <p>See <a href="#Braced_Initializer_List_Format">Braced_Initializer_List_Format</a> for formatting.</p> |
| 3648 | |
| 3649 | </div> |
| 3650 | |
| 3651 | <h3 id="Lambda_expressions">Lambda expressions</h3> |
| 3652 | |
| 3653 | <div class="summary"> |
| 3654 | <p>Use lambda expressions where appropriate. Prefer explicit captures |
| 3655 | when the lambda will escape the current scope.</p> |
| 3656 | </div> |
| 3657 | |
| 3658 | <div class="stylebody"> |
| 3659 | |
| 3660 | <div class="definition"> |
| 3661 | |
| 3662 | <p> Lambda expressions are a concise way of creating anonymous |
| 3663 | function objects. They're often useful when passing |
| 3664 | functions as arguments. For example:</p> |
| 3665 | |
| 3666 | <pre>std::sort(v.begin(), v.end(), [](int x, int y) { |
| 3667 | return Weight(x) < Weight(y); |
| 3668 | }); |
| 3669 | </pre> |
| 3670 | |
| 3671 | <p> They further allow capturing variables from the enclosing scope either |
| 3672 | explicitly by name, or implicitly using a default capture. Explicit captures |
| 3673 | require each variable to be listed, as |
| 3674 | either a value or reference capture:</p> |
| 3675 | |
| 3676 | <pre>int weight = 3; |
| 3677 | int sum = 0; |
| 3678 | // Captures `weight` by value and `sum` by reference. |
| 3679 | std::for_each(v.begin(), v.end(), [weight, &sum](int x) { |
| 3680 | sum += weight * x; |
| 3681 | }); |
| 3682 | </pre> |
| 3683 | |
| 3684 | |
| 3685 | Default captures implicitly capture any variable referenced in the |
| 3686 | lambda body, including <code>this</code> if any members are used: |
| 3687 | |
| 3688 | <pre>const std::vector<int> lookup_table = ...; |
| 3689 | std::vector<int> indices = ...; |
| 3690 | // Captures `lookup_table` by reference, sorts `indices` by the value |
| 3691 | // of the associated element in `lookup_table`. |
| 3692 | std::sort(indices.begin(), indices.end(), [&](int a, int b) { |
| 3693 | return lookup_table[a] < lookup_table[b]; |
| 3694 | }); |
| 3695 | </pre> |
| 3696 | |
| 3697 | <p>Lambdas were introduced in C++11 along with a set of utilities |
| 3698 | for working with function objects, such as the polymorphic |
| 3699 | wrapper <code>std::function</code>. |
| 3700 | </p> |
| 3701 | </div> |
| 3702 | |
| 3703 | <div class="pros"> |
| 3704 | <ul> |
| 3705 | <li>Lambdas are much more concise than other ways of |
| 3706 | defining function objects to be passed to STL |
| 3707 | algorithms, which can be a readability |
| 3708 | improvement.</li> |
| 3709 | |
| 3710 | <li>Appropriate use of default captures can remove |
| 3711 | redundancy and highlight important exceptions from |
| 3712 | the default.</li> |
| 3713 | |
| 3714 | <li>Lambdas, <code>std::function</code>, and |
| 3715 | <code>std::bind</code> can be used in combination as a |
| 3716 | general purpose callback mechanism; they make it easy |
| 3717 | to write functions that take bound functions as |
| 3718 | arguments.</li> |
| 3719 | </ul> |
| 3720 | </div> |
| 3721 | |
| 3722 | <div class="cons"> |
| 3723 | <ul> |
| 3724 | <li>Variable capture in lambdas can be a source of dangling-pointer |
| 3725 | bugs, particularly if a lambda escapes the current scope.</li> |
| 3726 | |
| 3727 | <li>Default captures by value can be misleading because they do not prevent |
| 3728 | dangling-pointer bugs. Capturing a pointer by value doesn't cause a deep |
| 3729 | copy, so it often has the same lifetime issues as capture by reference. |
| 3730 | This is especially confusing when capturing 'this' by value, since the use |
| 3731 | of 'this' is often implicit.</li> |
| 3732 | |
| 3733 | <li>It's possible for use of lambdas to get out of |
| 3734 | hand; very long nested anonymous functions can make |
| 3735 | code harder to understand.</li> |
| 3736 | |
| 3737 | </ul> |
| 3738 | </div> |
| 3739 | |
| 3740 | <div class="decision"> |
| 3741 | <ul> |
| 3742 | <li>Use lambda expressions where appropriate, with formatting as |
| 3743 | described <a href="#Formatting_Lambda_Expressions">below</a>.</li> |
| 3744 | <li>Prefer explicit captures if the lambda may escape the current scope. |
| 3745 | For example, instead of: |
| 3746 | <pre class="badcode">{ |
| 3747 | Foo foo; |
| 3748 | ... |
| 3749 | executor->Schedule([&] { Frobnicate(foo); }) |
| 3750 | ... |
| 3751 | } |
| 3752 | // BAD! The fact that the lambda makes use of a reference to `foo` and |
| 3753 | // possibly `this` (if `Frobnicate` is a member function) may not be |
| 3754 | // apparent on a cursory inspection. If the lambda is invoked after |
| 3755 | // the function returns, that would be bad, because both `foo` |
| 3756 | // and the enclosing object could have been destroyed. |
| 3757 | </pre> |
| 3758 | prefer to write: |
| 3759 | <pre>{ |
| 3760 | Foo foo; |
| 3761 | ... |
| 3762 | executor->Schedule([&foo] { Frobnicate(foo); }) |
| 3763 | ... |
| 3764 | } |
| 3765 | // BETTER - The compile will fail if `Frobnicate` is a member |
| 3766 | // function, and it's clearer that `foo` is dangerously captured by |
| 3767 | // reference. |
| 3768 | </pre> |
| 3769 | </li> |
| 3770 | <li>Use default capture by reference ([&]) only when the |
| 3771 | lifetime of the lambda is obviously shorter than any potential |
| 3772 | captures. |
| 3773 | </li> |
| 3774 | <li>Use default capture by value ([=]) only as a means of binding a |
| 3775 | few variables for a short lambda, where the set of captured |
| 3776 | variables is obvious at a glance. Prefer not to write long or |
| 3777 | complex lambdas with default capture by value. |
| 3778 | </li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3779 | <li>Specify the return type of the lambda explicitly if that will |
| 3780 | make it more obvious to readers, as with |
| 3781 | <a href="#auto"><code>auto</code></a>.</li> |
| 3782 | |
| 3783 | </ul> |
| 3784 | </div> |
| 3785 | |
| 3786 | </div> |
| 3787 | |
| 3788 | <h3 id="Template_metaprogramming">Template metaprogramming</h3> |
| 3789 | <div class="summary"> |
| 3790 | <p>Avoid complicated template programming.</p> |
| 3791 | </div> |
| 3792 | |
| 3793 | <div class="stylebody"> |
| 3794 | |
| 3795 | <div class="definition"> |
| 3796 | <p>Template metaprogramming refers to a family of techniques that |
| 3797 | exploit the fact that the C++ template instantiation mechanism is |
| 3798 | Turing complete and can be used to perform arbitrary compile-time |
| 3799 | computation in the type domain.</p> |
| 3800 | </div> |
| 3801 | |
| 3802 | <div class="pros"> |
| 3803 | <p>Template metaprogramming allows extremely flexible interfaces that |
| 3804 | are type safe and high performance. Facilities like |
| 3805 | |
| 3806 | <a href="https://code.google.com/p/googletest/">Google Test</a>, |
| 3807 | <code>std::tuple</code>, <code>std::function</code>, and |
| 3808 | Boost.Spirit would be impossible without it.</p> |
| 3809 | </div> |
| 3810 | |
| 3811 | <div class="cons"> |
| 3812 | <p>The techniques used in template metaprogramming are often obscure |
| 3813 | to anyone but language experts. Code that uses templates in |
| 3814 | complicated ways is often unreadable, and is hard to debug or |
| 3815 | maintain.</p> |
| 3816 | |
| 3817 | <p>Template metaprogramming often leads to extremely poor compiler |
| 3818 | time error messages: even if an interface is simple, the complicated |
| 3819 | implementation details become visible when the user does something |
| 3820 | wrong.</p> |
| 3821 | |
| 3822 | <p>Template metaprogramming interferes with large scale refactoring by |
| 3823 | making the job of refactoring tools harder. First, the template code |
| 3824 | is expanded in multiple contexts, and it's hard to verify that the |
| 3825 | transformation makes sense in all of them. Second, some refactoring |
| 3826 | tools work with an AST that only represents the structure of the code |
| 3827 | after template expansion. It can be difficult to automatically work |
| 3828 | back to the original source construct that needs to be |
| 3829 | rewritten.</p> |
| 3830 | </div> |
| 3831 | |
| 3832 | <div class="decision"> |
| 3833 | <p>Template metaprogramming sometimes allows cleaner and easier-to-use |
| 3834 | interfaces than would be possible without it, but it's also often a |
| 3835 | temptation to be overly clever. It's best used in a small number of |
| 3836 | low level components where the extra maintenance burden is spread out |
| 3837 | over a large number of uses.</p> |
| 3838 | |
| 3839 | <p>Think twice before using template metaprogramming or other |
| 3840 | complicated template techniques; think about whether the average |
| 3841 | member of your team will be able to understand your code well enough |
| 3842 | to maintain it after you switch to another project, or whether a |
| 3843 | non-C++ programmer or someone casually browsing the code base will be |
| 3844 | able to understand the error messages or trace the flow of a function |
| 3845 | they want to call. If you're using recursive template instantiations |
| 3846 | or type lists or metafunctions or expression templates, or relying on |
| 3847 | SFINAE or on the <code>sizeof</code> trick for detecting function |
| 3848 | overload resolution, then there's a good chance you've gone too |
| 3849 | far.</p> |
| 3850 | |
| 3851 | <p>If you use template metaprogramming, you should expect to put |
| 3852 | considerable effort into minimizing and isolating the complexity. You |
| 3853 | should hide metaprogramming as an implementation detail whenever |
| 3854 | possible, so that user-facing headers are readable, and you should |
| 3855 | make sure that tricky code is especially well commented. You should |
| 3856 | carefully document how the code is used, and you should say something |
| 3857 | about what the "generated" code looks like. Pay extra attention to the |
| 3858 | error messages that the compiler emits when users make mistakes. The |
| 3859 | error messages are part of your user interface, and your code should |
| 3860 | be tweaked as necessary so that the error messages are understandable |
| 3861 | and actionable from a user point of view.</p> |
| 3862 | |
| 3863 | </div> |
| 3864 | </div> |
| 3865 | |
| 3866 | |
| 3867 | <h3 id="Boost">Boost</h3> |
| 3868 | |
| 3869 | <div class="summary"> |
| 3870 | <p>Use only approved libraries from the Boost library |
| 3871 | collection.</p> |
| 3872 | </div> |
| 3873 | |
| 3874 | <div class="stylebody"> |
| 3875 | |
| 3876 | <div class="definition"> |
| 3877 | <p> The |
| 3878 | <a href="https://www.boost.org/"> |
| 3879 | Boost library collection</a> is a popular collection of |
| 3880 | peer-reviewed, free, open-source C++ libraries.</p> |
| 3881 | </div> |
| 3882 | |
| 3883 | <div class="pros"> |
| 3884 | <p>Boost code is generally very high-quality, is widely |
| 3885 | portable, and fills many important gaps in the C++ |
| 3886 | standard library, such as type traits and better binders.</p> |
| 3887 | </div> |
| 3888 | |
| 3889 | <div class="cons"> |
| 3890 | <p>Some Boost libraries encourage coding practices which can |
| 3891 | hamper readability, such as metaprogramming and other |
| 3892 | advanced template techniques, and an excessively |
| 3893 | "functional" style of programming. </p> |
| 3894 | </div> |
| 3895 | |
| 3896 | <div class="decision"> |
| 3897 | |
| 3898 | |
| 3899 | |
| 3900 | <div> |
| 3901 | <p>In order to maintain a high level of readability for |
| 3902 | all contributors who might read and maintain code, we |
| 3903 | only allow an approved subset of Boost features. |
| 3904 | Currently, the following libraries are permitted:</p> |
| 3905 | |
| 3906 | <ul> |
| 3907 | <li> |
| 3908 | <a href="https://www.boost.org/libs/utility/call_traits.htm"> |
| 3909 | Call Traits</a> from <code>boost/call_traits.hpp</code></li> |
| 3910 | |
| 3911 | <li><a href="https://www.boost.org/libs/utility/compressed_pair.htm"> |
| 3912 | Compressed Pair</a> from <code>boost/compressed_pair.hpp</code></li> |
| 3913 | |
| 3914 | <li><a href="https://www.boost.org/libs/graph/"> |
| 3915 | The Boost Graph Library (BGL)</a> from <code>boost/graph</code>, |
| 3916 | except serialization (<code>adj_list_serialize.hpp</code>) and |
| 3917 | parallel/distributed algorithms and data structures |
| 3918 | (<code>boost/graph/parallel/*</code> and |
| 3919 | <code>boost/graph/distributed/*</code>).</li> |
| 3920 | |
| 3921 | <li><a href="https://www.boost.org/libs/property_map/"> |
| 3922 | Property Map</a> from <code>boost/property_map</code>, except |
| 3923 | parallel/distributed property maps (<code>boost/property_map/parallel/*</code>).</li> |
| 3924 | |
| 3925 | <li><a href="https://www.boost.org/libs/iterator/"> |
| 3926 | Iterator</a> from <code>boost/iterator</code></li> |
| 3927 | |
| 3928 | <li>The part of <a href="https://www.boost.org/libs/polygon/"> |
| 3929 | Polygon</a> that deals with Voronoi diagram |
| 3930 | construction and doesn't depend on the rest of |
| 3931 | Polygon: |
| 3932 | <code>boost/polygon/voronoi_builder.hpp</code>, |
| 3933 | <code>boost/polygon/voronoi_diagram.hpp</code>, and |
| 3934 | <code>boost/polygon/voronoi_geometry_type.hpp</code></li> |
| 3935 | |
| 3936 | <li><a href="https://www.boost.org/libs/bimap/"> |
| 3937 | Bimap</a> from <code>boost/bimap</code></li> |
| 3938 | |
| 3939 | <li><a href="https://www.boost.org/libs/math/doc/html/dist.html"> |
| 3940 | Statistical Distributions and Functions</a> from |
| 3941 | <code>boost/math/distributions</code></li> |
| 3942 | |
| 3943 | <li><a href="https://www.boost.org/libs/math/doc/html/special.html"> |
| 3944 | Special Functions</a> from <code>boost/math/special_functions</code></li> |
| 3945 | |
| 3946 | <li><a href="https://www.boost.org/libs/multi_index/"> |
| 3947 | Multi-index</a> from <code>boost/multi_index</code></li> |
| 3948 | |
| 3949 | <li><a href="https://www.boost.org/libs/heap/"> |
| 3950 | Heap</a> from <code>boost/heap</code></li> |
| 3951 | |
| 3952 | <li>The flat containers from |
| 3953 | <a href="https://www.boost.org/libs/container/">Container</a>: |
| 3954 | <code>boost/container/flat_map</code>, and |
| 3955 | <code>boost/container/flat_set</code></li> |
| 3956 | |
| 3957 | <li><a href="https://www.boost.org/libs/intrusive/">Intrusive</a> |
| 3958 | from <code>boost/intrusive</code>.</li> |
| 3959 | |
| 3960 | <li><a href="https://www.boost.org/libs/sort/">The |
| 3961 | <code>boost/sort</code> library</a>.</li> |
| 3962 | |
| 3963 | <li><a href="https://www.boost.org/libs/preprocessor/">Preprocessor</a> |
| 3964 | from <code>boost/preprocessor</code>.</li> |
| 3965 | </ul> |
| 3966 | |
| 3967 | <p>We are actively considering adding other Boost |
| 3968 | features to the list, so this list may be expanded in |
| 3969 | the future.</p> |
| 3970 | </div> |
| 3971 | |
| 3972 | <p>The following libraries are permitted, but their use |
| 3973 | is discouraged because they've been superseded by |
| 3974 | standard libraries in C++11:</p> |
| 3975 | |
| 3976 | <ul> |
| 3977 | <li><a href="https://www.boost.org/libs/array/"> |
| 3978 | Array</a> from <code>boost/array.hpp</code>: use |
| 3979 | <a href="http://en.cppreference.com/w/cpp/container/array"> |
| 3980 | <code>std::array</code></a> instead.</li> |
| 3981 | |
| 3982 | <li><a href="https://www.boost.org/libs/ptr_container/"> |
| 3983 | Pointer Container</a> from <code>boost/ptr_container</code>: use containers of |
| 3984 | <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr"> |
| 3985 | <code>std::unique_ptr</code></a> instead.</li> |
| 3986 | </ul> |
| 3987 | </div> |
| 3988 | |
| 3989 | </div> |
| 3990 | |
| 3991 | |
| 3992 | |
| 3993 | <h3 id="std_hash">std::hash</h3> |
| 3994 | |
| 3995 | <div class="summary"> |
| 3996 | <p>Do not define specializations of <code>std::hash</code>.</p> |
| 3997 | </div> |
| 3998 | |
| 3999 | <div class="stylebody"> |
| 4000 | |
| 4001 | <div class="definition"> |
| 4002 | <p><code>std::hash<T></code> is the function object that the |
| 4003 | C++11 hash containers use to hash keys of type <code>T</code>, |
| 4004 | unless the user explicitly specifies a different hash function. For |
| 4005 | example, <code>std::unordered_map<int, string></code> is a hash |
| 4006 | map that uses <code>std::hash<int></code> to hash its keys, |
| 4007 | whereas <code>std::unordered_map<int, string, MyIntHash></code> |
| 4008 | uses <code>MyIntHash</code>.</p> |
| 4009 | |
| 4010 | <p><code>std::hash</code> is defined for all integral, floating-point, |
| 4011 | pointer, and <code>enum</code> types, as well as some standard library |
| 4012 | types such as <code>string</code> and <code>unique_ptr</code>. Users |
| 4013 | can enable it to work for their own types by defining specializations |
| 4014 | of it for those types.</p> |
| 4015 | </div> |
| 4016 | |
| 4017 | <div class="pros"> |
| 4018 | <p><code>std::hash</code> is easy to use, and simplifies the code |
| 4019 | since you don't have to name it explicitly. Specializing |
| 4020 | <code>std::hash</code> is the standard way of specifying how to |
| 4021 | hash a type, so it's what outside resources will teach, and what |
| 4022 | new engineers will expect.</p> |
| 4023 | </div> |
| 4024 | |
| 4025 | <div class="cons"> |
| 4026 | <p><code>std::hash</code> is hard to specialize. It requires a lot |
| 4027 | of boilerplate code, and more importantly, it combines responsibility |
| 4028 | for identifying the hash inputs with responsibility for executing the |
| 4029 | hashing algorithm itself. The type author has to be responsible for |
| 4030 | the former, but the latter requires expertise that a type author |
| 4031 | usually doesn't have, and shouldn't need. The stakes here are high |
| 4032 | because low-quality hash functions can be security vulnerabilities, |
| 4033 | due to the emergence of |
| 4034 | <a href="https://emboss.github.io/blog/2012/12/14/breaking-murmur-hash-flooding-dos-reloaded/"> |
| 4035 | hash flooding attacks</a>.</p> |
| 4036 | |
| 4037 | <p>Even for experts, <code>std::hash</code> specializations are |
| 4038 | inordinately difficult to implement correctly for compound types, |
| 4039 | because the implementation cannot recursively call <code>std::hash</code> |
| 4040 | on data members. High-quality hash algorithms maintain large |
| 4041 | amounts of internal state, and reducing that state to the |
| 4042 | <code>size_t</code> bytes that <code>std::hash</code> |
| 4043 | returns is usually the slowest part of the computation, so it |
| 4044 | should not be done more than once.</p> |
| 4045 | |
| 4046 | <p>Due to exactly that issue, <code>std::hash</code> does not work |
| 4047 | with <code>std::pair</code> or <code>std::tuple</code>, and the |
| 4048 | language does not allow us to extend it to support them.</p> |
| 4049 | </div> |
| 4050 | |
| 4051 | <div class="decision"> |
| 4052 | <p>You can use <code>std::hash</code> with the types that it supports |
| 4053 | "out of the box", but do not specialize it to support additional types. |
| 4054 | If you need a hash table with a key type that <code>std::hash</code> |
| 4055 | does not support, consider using legacy hash containers (e.g. |
| 4056 | <code>hash_map</code>) for now; they use a different default hasher, |
| 4057 | which is unaffected by this prohibition.</p> |
| 4058 | |
| 4059 | <p>If you want to use the standard hash containers anyway, you will |
| 4060 | need to specify a custom hasher for the key type, e.g.</p> |
| 4061 | <pre>std::unordered_map<MyKeyType, Value, MyKeyTypeHasher> my_map; |
| 4062 | </pre><p> |
| 4063 | Consult with the type's owners to see if there is an existing hasher |
| 4064 | that you can use; otherwise work with them to provide one, |
| 4065 | or roll your own.</p> |
| 4066 | |
| 4067 | <p>We are planning to provide a hash function that can work with any type, |
| 4068 | using a new customization mechanism that doesn't have the drawbacks of |
| 4069 | <code>std::hash</code>.</p> |
| 4070 | </div> |
| 4071 | |
| 4072 | </div> |
| 4073 | |
| 4074 | <h3 id="C++11">C++11</h3> |
| 4075 | |
| 4076 | <div class="summary"> |
| 4077 | <p>Use libraries and language extensions from C++11 when appropriate. |
| 4078 | Consider portability to other environments |
| 4079 | before using C++11 features in your |
| 4080 | project. </p> |
| 4081 | |
| 4082 | </div> |
| 4083 | |
| 4084 | <div class="stylebody"> |
| 4085 | |
| 4086 | <div class="definition"> |
| 4087 | <p> C++11 contains <a href="https://en.wikipedia.org/wiki/C%2B%2B11"> |
| 4088 | significant changes</a> both to the language and |
| 4089 | libraries. </p> |
| 4090 | </div> |
| 4091 | |
| 4092 | <div class="pros"> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4093 | <p>C++11 was the official standard until 2014, and |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4094 | is supported by most C++ compilers. It standardizes |
| 4095 | some common C++ extensions that we use already, allows |
| 4096 | shorthands for some operations, and has some performance |
| 4097 | and safety improvements.</p> |
| 4098 | </div> |
| 4099 | |
| 4100 | <div class="cons"> |
| 4101 | <p>The C++11 standard is substantially more complex than |
| 4102 | its predecessor (1,300 pages versus 800 pages), and is |
| 4103 | unfamiliar to many developers. The long-term effects of |
| 4104 | some features on code readability and maintenance are |
| 4105 | unknown. We cannot predict when its various features will |
| 4106 | be implemented uniformly by tools that may be of |
| 4107 | interest, particularly in the case of projects that are |
| 4108 | forced to use older versions of tools.</p> |
| 4109 | |
| 4110 | <p>As with <a href="#Boost">Boost</a>, some C++11 |
| 4111 | extensions encourage coding practices that hamper |
| 4112 | readability—for example by removing |
| 4113 | checked redundancy (such as type names) that may be |
| 4114 | helpful to readers, or by encouraging template |
| 4115 | metaprogramming. Other extensions duplicate functionality |
| 4116 | available through existing mechanisms, which may lead to confusion |
| 4117 | and conversion costs.</p> |
| 4118 | |
| 4119 | |
| 4120 | </div> |
| 4121 | |
| 4122 | <div class="decision"> |
| 4123 | |
| 4124 | <p>C++11 features may be used unless specified otherwise. |
| 4125 | In addition to what's described in the rest of the style |
| 4126 | guide, the following C++11 features may not be used:</p> |
| 4127 | |
| 4128 | <ul> |
| 4129 | |
| 4130 | |
| 4131 | |
| 4132 | |
| 4133 | |
| 4134 | |
| 4135 | |
| 4136 | |
| 4137 | <li>Compile-time rational numbers |
| 4138 | (<code><ratio></code>), because of concerns that |
| 4139 | it's tied to a more template-heavy interface |
| 4140 | style.</li> |
| 4141 | |
| 4142 | <li>The <code><cfenv></code> and |
| 4143 | <code><fenv.h></code> headers, because many |
| 4144 | compilers do not support those features reliably.</li> |
| 4145 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4146 | |
| 4147 | |
| 4148 | |
| 4149 | </ul> |
| 4150 | </div> |
| 4151 | |
| 4152 | </div> |
| 4153 | |
| 4154 | <h3 id="Nonstandard_Extensions">Nonstandard Extensions</h3> |
| 4155 | |
| 4156 | <div class="summary"> |
| 4157 | <p>Nonstandard extensions to C++ may not be used unless otherwise specified.</p> |
| 4158 | </div> |
| 4159 | <div class="stylebody"> |
| 4160 | <div class="definition"> |
| 4161 | <p>Compilers support various extensions that are not part of standard C++. Such |
| 4162 | extensions include GCC's <code>__attribute__</code>, intrinsic functions such |
| 4163 | as <code>__builtin_prefetch</code>, designated initializers (e.g. |
| 4164 | <code>Foo f = {.field = 3}</code>), inline assembly, <code>__COUNTER__</code>, |
| 4165 | <code>__PRETTY_FUNCTION__</code>, compound statement expressions (e.g. |
| 4166 | <code>foo = ({ int x; Bar(&x); x })</code>, variable-length arrays and |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4167 | <code>alloca()</code>, and the "<a href="https://en.wikipedia.org/wiki/Elvis_operator">Elvis Operator</a>" |
| 4168 | <code>a?:b</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4169 | </div> |
| 4170 | |
| 4171 | <div class="pros"> |
| 4172 | <ul> |
| 4173 | <li>Nonstandard extensions may provide useful features that do not exist |
| 4174 | in standard C++. For example, some people think that designated |
| 4175 | initializers are more readable than standard C++ features like |
| 4176 | constructors.</li> |
| 4177 | <li>Important performance guidance to the compiler can only be specified |
| 4178 | using extensions.</li> |
| 4179 | </ul> |
| 4180 | </div> |
| 4181 | |
| 4182 | <div class="cons"> |
| 4183 | <ul> |
| 4184 | <li>Nonstandard extensions do not work in all compilers. Use of nonstandard |
| 4185 | extensions reduces portability of code.</li> |
| 4186 | <li>Even if they are supported in all targeted compilers, the extensions |
| 4187 | are often not well-specified, and there may be subtle behavior differences |
| 4188 | between compilers.</li> |
| 4189 | <li>Nonstandard extensions add to the language features that a reader must |
| 4190 | know to understand the code.</li> |
| 4191 | </ul> |
| 4192 | </div> |
| 4193 | |
| 4194 | <div class="decision"> |
| 4195 | <p>Do not use nonstandard extensions. You may use portability wrappers that |
| 4196 | are implemented using nonstandard extensions, so long as those wrappers |
| 4197 | |
| 4198 | are provided by a designated project-wide |
| 4199 | portability header.</p> |
| 4200 | </div> |
| 4201 | </div> |
| 4202 | |
| 4203 | <h3 id="Aliases">Aliases</h3> |
| 4204 | |
| 4205 | <div class="summary"> |
| 4206 | <p>Public aliases are for the benefit of an API's user, and should be clearly documented.</p> |
| 4207 | </div> |
| 4208 | <div class="stylebody"> |
| 4209 | <div class="definition"> |
| 4210 | <p>There are several ways to create names that are aliases of other entities:</p> |
| 4211 | <pre>typedef Foo Bar; |
| 4212 | using Bar = Foo; |
| 4213 | using other_namespace::Foo; |
| 4214 | </pre> |
| 4215 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4216 | <p>In new code, <code>using</code> is preferable to <code>typedef</code>, |
| 4217 | because it provides a more consistent syntax with the rest of C++ and works |
| 4218 | with templates.</p> |
| 4219 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4220 | <p>Like other declarations, aliases declared in a header file are part of that |
| 4221 | header's public API unless they're in a function definition, in the private portion of a class, |
| 4222 | or in an explicitly-marked internal namespace. Aliases in such areas or in .cc files are |
| 4223 | implementation details (because client code can't refer to them), and are not restricted by this |
| 4224 | rule.</p> |
| 4225 | </div> |
| 4226 | |
| 4227 | <div class="pros"> |
| 4228 | <ul> |
| 4229 | <li>Aliases can improve readability by simplifying a long or complicated name.</li> |
| 4230 | <li>Aliases can reduce duplication by naming in one place a type used repeatedly in an API, |
| 4231 | which <em>might</em> make it easier to change the type later. |
| 4232 | </li> |
| 4233 | </ul> |
| 4234 | </div> |
| 4235 | |
| 4236 | <div class="cons"> |
| 4237 | <ul> |
| 4238 | <li>When placed in a header where client code can refer to them, aliases increase the |
| 4239 | number of entities in that header's API, increasing its complexity.</li> |
| 4240 | <li>Clients can easily rely on unintended details of public aliases, making |
| 4241 | changes difficult.</li> |
| 4242 | <li>It can be tempting to create a public alias that is only intended for use |
| 4243 | in the implementation, without considering its impact on the API, or on maintainability.</li> |
| 4244 | <li>Aliases can create risk of name collisions</li> |
| 4245 | <li>Aliases can reduce readability by giving a familiar construct an unfamiliar name</li> |
| 4246 | <li>Type aliases can create an unclear API contract: |
| 4247 | it is unclear whether the alias is guaranteed to be identical to the type it aliases, |
| 4248 | to have the same API, or only to be usable in specified narrow ways</li> |
| 4249 | </ul> |
| 4250 | </div> |
| 4251 | |
| 4252 | <div class="decision"> |
| 4253 | <p>Don't put an alias in your public API just to save typing in the implementation; |
| 4254 | do so only if you intend it to be used by your clients.</p> |
| 4255 | <p>When defining a public alias, document the intent of |
| 4256 | the new name, including whether it is guaranteed to always be the same as the type |
| 4257 | it's currently aliased to, or whether a more limited compatibility is |
| 4258 | intended. This lets the user know whether they can treat the types as |
| 4259 | substitutable or whether more specific rules must be followed, and can help the |
| 4260 | implementation retain some degree of freedom to change the alias.</p> |
| 4261 | <p>Don't put namespace aliases in your public API. (See also <a href="#Namespaces">Namespaces</a>). |
| 4262 | </p> |
| 4263 | |
| 4264 | <p>For example, these aliases document how they are intended to be used in client code:</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4265 | <pre>namespace mynamespace { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4266 | // Used to store field measurements. DataPoint may change from Bar* to some internal type. |
| 4267 | // Client code should treat it as an opaque pointer. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4268 | using DataPoint = foo::Bar*; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4269 | |
| 4270 | // A set of measurements. Just an alias for user convenience. |
| 4271 | using TimeSeries = std::unordered_set<DataPoint, std::hash<DataPoint>, DataPointComparator>; |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4272 | } // namespace mynamespace |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4273 | </pre> |
| 4274 | |
| 4275 | <p>These aliases don't document intended use, and half of them aren't meant for client use:</p> |
| 4276 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4277 | <pre class="badcode">namespace mynamespace { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4278 | // Bad: none of these say how they should be used. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4279 | using DataPoint = foo::Bar*; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4280 | using std::unordered_set; // Bad: just for local convenience |
| 4281 | using std::hash; // Bad: just for local convenience |
| 4282 | typedef unordered_set<DataPoint, hash<DataPoint>, DataPointComparator> TimeSeries; |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4283 | } // namespace mynamespace |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4284 | </pre> |
| 4285 | |
| 4286 | <p>However, local convenience aliases are fine in function definitions, private sections of |
| 4287 | classes, explicitly marked internal namespaces, and in .cc files:</p> |
| 4288 | |
| 4289 | <pre>// In a .cc file |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4290 | using foo::Bar; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4291 | </pre> |
| 4292 | |
| 4293 | </div> |
| 4294 | </div> |
| 4295 | |
| 4296 | <h2 id="Naming">Naming</h2> |
| 4297 | |
| 4298 | <p>The most important consistency rules are those that govern |
| 4299 | naming. The style of a name immediately informs us what sort of |
| 4300 | thing the named entity is: a type, a variable, a function, a |
| 4301 | constant, a macro, etc., without requiring us to search for the |
| 4302 | declaration of that entity. The pattern-matching engine in our |
| 4303 | brains relies a great deal on these naming rules. |
| 4304 | </p> |
| 4305 | |
| 4306 | <p>Naming rules are pretty arbitrary, but |
| 4307 | we feel that |
| 4308 | consistency is more important than individual preferences in this |
| 4309 | area, so regardless of whether you find them sensible or not, |
| 4310 | the rules are the rules.</p> |
| 4311 | |
| 4312 | <h3 id="General_Naming_Rules">General Naming Rules</h3> |
| 4313 | |
| 4314 | <div class="summary"> |
| 4315 | <p>Names should be descriptive; avoid abbreviation.</p> |
| 4316 | </div> |
| 4317 | |
| 4318 | <div class="stylebody"> |
| 4319 | <p>Give as descriptive a name as possible, within reason. |
| 4320 | Do not worry about saving horizontal space as it is far |
| 4321 | more important to make your code immediately |
| 4322 | understandable by a new reader. Do not use abbreviations |
| 4323 | that are ambiguous or unfamiliar to readers outside your |
| 4324 | project, and do not abbreviate by deleting letters within |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4325 | a word. Abbreviations that would be familiar to someone |
| 4326 | outside your project with relevant domain knowledge are OK. |
| 4327 | As a rule of thumb, an abbreviation is probably OK if it's listed |
| 4328 | in |
| 4329 | |
| 4330 | Wikipedia.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4331 | |
| 4332 | <pre>int price_count_reader; // No abbreviation. |
| 4333 | int num_errors; // "num" is a widespread convention. |
| 4334 | int num_dns_connections; // Most people know what "DNS" stands for. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4335 | int lstm_size; // "LSTM" is a common machine learning abbreviation. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4336 | </pre> |
| 4337 | |
| 4338 | <pre class="badcode">int n; // Meaningless. |
| 4339 | int nerr; // Ambiguous abbreviation. |
| 4340 | int n_comp_conns; // Ambiguous abbreviation. |
| 4341 | int wgc_connections; // Only your group knows what this stands for. |
| 4342 | int pc_reader; // Lots of things can be abbreviated "pc". |
| 4343 | int cstmr_id; // Deletes internal letters. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4344 | FooBarRequestInfo fbri; // Not even a word. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4345 | </pre> |
| 4346 | |
| 4347 | <p>Note that certain universally-known abbreviations are OK, such as |
| 4348 | <code>i</code> for an iteration variable and <code>T</code> for a |
| 4349 | template parameter.</p> |
| 4350 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4351 | <p>For some symbols, this style guide recommends names to start with a capital |
| 4352 | letter and to have a capital letter for each new word (a.k.a. |
| 4353 | "<a href="https://en.wikipedia.org/wiki/Camel_case">Camel Case</a>" |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4354 | or "Pascal case"). When abbreviations or acronyms appear in such |
| 4355 | names, prefer to capitalize the abbreviations or acronyms as single words (i.e |
| 4356 | <code>StartRpc()</code>, not <code>StartRPC()</code>).</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4357 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4358 | <p>Template parameters should follow the naming style for their |
| 4359 | category: type template parameters should follow the rules for |
| 4360 | <a href="#Type_Names">type names</a>, and non-type template |
| 4361 | parameters should follow the rules for <a href="#Variable_Names"> |
| 4362 | variable names</a>. |
| 4363 | |
| 4364 | </p></div> |
| 4365 | |
| 4366 | <h3 id="File_Names">File Names</h3> |
| 4367 | |
| 4368 | <div class="summary"> |
| 4369 | <p>Filenames should be all lowercase and can include |
| 4370 | underscores (<code>_</code>) or dashes (<code>-</code>). |
| 4371 | Follow the convention that your |
| 4372 | |
| 4373 | project uses. If there is no consistent |
| 4374 | local pattern to follow, prefer "_".</p> |
| 4375 | </div> |
| 4376 | |
| 4377 | <div class="stylebody"> |
| 4378 | |
| 4379 | <p>Examples of acceptable file names:</p> |
| 4380 | |
| 4381 | <ul> |
| 4382 | <li><code>my_useful_class.cc</code></li> |
| 4383 | <li><code>my-useful-class.cc</code></li> |
| 4384 | <li><code>myusefulclass.cc</code></li> |
| 4385 | <li><code>myusefulclass_test.cc // _unittest and _regtest are deprecated.</code></li> |
| 4386 | </ul> |
| 4387 | |
| 4388 | <p>C++ files should end in <code>.cc</code> and header files should end in |
| 4389 | <code>.h</code>. Files that rely on being textually included at specific points |
| 4390 | should end in <code>.inc</code> (see also the section on |
| 4391 | <a href="#Self_contained_Headers">self-contained headers</a>).</p> |
| 4392 | |
| 4393 | <p>Do not use filenames that already exist in |
| 4394 | <code>/usr/include</code>, such as <code>db.h</code>.</p> |
| 4395 | |
| 4396 | <p>In general, make your filenames very specific. For |
| 4397 | example, use <code>http_server_logs.h</code> rather than |
| 4398 | <code>logs.h</code>. A very common case is to have a pair |
| 4399 | of files called, e.g., <code>foo_bar.h</code> and |
| 4400 | <code>foo_bar.cc</code>, defining a class called |
| 4401 | <code>FooBar</code>.</p> |
| 4402 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4403 | </div> |
| 4404 | |
| 4405 | <h3 id="Type_Names">Type Names</h3> |
| 4406 | |
| 4407 | <div class="summary"> |
| 4408 | <p>Type names start with a capital letter and have a capital |
| 4409 | letter for each new word, with no underscores: |
| 4410 | <code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.</p> |
| 4411 | </div> |
| 4412 | |
| 4413 | <div class="stylebody"> |
| 4414 | |
| 4415 | <p>The names of all types — classes, structs, type aliases, |
| 4416 | enums, and type template parameters — have the same naming convention. |
| 4417 | Type names should start with a capital letter and have a capital letter |
| 4418 | for each new word. No underscores. For example:</p> |
| 4419 | |
| 4420 | <pre>// classes and structs |
| 4421 | class UrlTable { ... |
| 4422 | class UrlTableTester { ... |
| 4423 | struct UrlTableProperties { ... |
| 4424 | |
| 4425 | // typedefs |
| 4426 | typedef hash_map<UrlTableProperties *, string> PropertiesMap; |
| 4427 | |
| 4428 | // using aliases |
| 4429 | using PropertiesMap = hash_map<UrlTableProperties *, string>; |
| 4430 | |
| 4431 | // enums |
| 4432 | enum UrlTableErrors { ... |
| 4433 | </pre> |
| 4434 | |
| 4435 | </div> |
| 4436 | |
| 4437 | <h3 id="Variable_Names">Variable Names</h3> |
| 4438 | |
| 4439 | <div class="summary"> |
| 4440 | <p>The names of variables (including function parameters) and data members are |
| 4441 | all lowercase, with underscores between words. Data members of classes (but not |
| 4442 | structs) additionally have trailing underscores. For instance: |
| 4443 | <code>a_local_variable</code>, <code>a_struct_data_member</code>, |
| 4444 | <code>a_class_data_member_</code>.</p> |
| 4445 | </div> |
| 4446 | |
| 4447 | <div class="stylebody"> |
| 4448 | |
| 4449 | <h4 class="stylepoint_subsection">Common Variable names</h4> |
| 4450 | |
| 4451 | <p>For example:</p> |
| 4452 | |
| 4453 | <pre>string table_name; // OK - uses underscore. |
| 4454 | string tablename; // OK - all lowercase. |
| 4455 | </pre> |
| 4456 | |
| 4457 | <pre class="badcode">string tableName; // Bad - mixed case. |
| 4458 | </pre> |
| 4459 | |
| 4460 | <h4 class="stylepoint_subsection">Class Data Members</h4> |
| 4461 | |
| 4462 | <p>Data members of classes, both static and non-static, are |
| 4463 | named like ordinary nonmember variables, but with a |
| 4464 | trailing underscore.</p> |
| 4465 | |
| 4466 | <pre>class TableInfo { |
| 4467 | ... |
| 4468 | private: |
| 4469 | string table_name_; // OK - underscore at end. |
| 4470 | string tablename_; // OK. |
| 4471 | static Pool<TableInfo>* pool_; // OK. |
| 4472 | }; |
| 4473 | </pre> |
| 4474 | |
| 4475 | <h4 class="stylepoint_subsection">Struct Data Members</h4> |
| 4476 | |
| 4477 | <p>Data members of structs, both static and non-static, |
| 4478 | are named like ordinary nonmember variables. They do not have |
| 4479 | the trailing underscores that data members in classes have.</p> |
| 4480 | |
| 4481 | <pre>struct UrlTableProperties { |
| 4482 | string name; |
| 4483 | int num_entries; |
| 4484 | static Pool<UrlTableProperties>* pool; |
| 4485 | }; |
| 4486 | </pre> |
| 4487 | |
| 4488 | |
| 4489 | <p>See <a href="#Structs_vs._Classes">Structs vs. |
| 4490 | Classes</a> for a discussion of when to use a struct |
| 4491 | versus a class.</p> |
| 4492 | |
| 4493 | </div> |
| 4494 | |
| 4495 | <h3 id="Constant_Names">Constant Names</h3> |
| 4496 | |
| 4497 | <div class="summary"> |
| 4498 | <p>Variables declared constexpr or const, and whose value is fixed for |
| 4499 | the duration of the program, are named with a leading "k" followed |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4500 | by mixed case. Underscores can be used as separators in the rare cases |
| 4501 | where capitalization cannot be used for separation. For example:</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4502 | </div> |
| 4503 | |
| 4504 | <pre>const int kDaysInAWeek = 7; |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4505 | const int kAndroid8_0_0 = 24; // Android 8.0.0 |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4506 | </pre> |
| 4507 | |
| 4508 | <div class="stylebody"> |
| 4509 | |
| 4510 | <p>All such variables with static storage duration (i.e. statics and globals, |
| 4511 | see <a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration"> |
| 4512 | Storage Duration</a> for details) should be named this way. This |
| 4513 | convention is optional for variables of other storage classes, e.g. automatic |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4514 | variables, otherwise the usual variable naming rules apply.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4515 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4516 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4517 | |
| 4518 | <h3 id="Function_Names">Function Names</h3> |
| 4519 | |
| 4520 | <div class="summary"> |
| 4521 | <p>Regular functions have mixed case; accessors and mutators may be named |
| 4522 | like variables.</p> |
| 4523 | </div> |
| 4524 | |
| 4525 | <div class="stylebody"> |
| 4526 | |
| 4527 | <p>Ordinarily, functions should start with a capital letter and have a |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4528 | capital letter for each new word.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4529 | |
| 4530 | <pre>AddTableEntry() |
| 4531 | DeleteUrl() |
| 4532 | OpenFileOrDie() |
| 4533 | </pre> |
| 4534 | |
| 4535 | <p>(The same naming rule applies to class- and namespace-scope |
| 4536 | constants that are exposed as part of an API and that are intended to look |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4537 | like functions, because the fact that they're objects rather than functions |
| 4538 | is an unimportant implementation detail.)</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4539 | |
| 4540 | <p>Accessors and mutators (get and set functions) may be named like |
| 4541 | variables. These often correspond to actual member variables, but this is |
| 4542 | not required. For example, <code>int count()</code> and <code>void |
| 4543 | set_count(int count)</code>.</p> |
| 4544 | |
| 4545 | </div> |
| 4546 | |
| 4547 | <h3 id="Namespace_Names">Namespace Names</h3> |
| 4548 | |
| 4549 | <div class="summary"> |
| 4550 | Namespace names are all lower-case. Top-level namespace names are |
| 4551 | based on the project name |
| 4552 | . Avoid collisions |
| 4553 | between nested namespaces and well-known top-level namespaces. |
| 4554 | </div> |
| 4555 | |
| 4556 | <div class="stylebody"> |
| 4557 | <p>The name of a top-level namespace should usually be the |
| 4558 | name of the project or team whose code is contained in that |
| 4559 | namespace. The code in that namespace should usually be in |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4560 | a directory whose basename matches the namespace name (or in |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4561 | subdirectories thereof).</p> |
| 4562 | |
| 4563 | |
| 4564 | |
| 4565 | |
| 4566 | |
| 4567 | <p>Keep in mind that the <a href="#General_Naming_Rules">rule |
| 4568 | against abbreviated names</a> applies to namespaces just as much |
| 4569 | as variable names. Code inside the namespace seldom needs to |
| 4570 | mention the namespace name, so there's usually no particular need |
| 4571 | for abbreviation anyway.</p> |
| 4572 | |
| 4573 | <p>Avoid nested namespaces that match well-known top-level |
| 4574 | namespaces. Collisions between namespace names can lead to surprising |
| 4575 | build breaks because of name lookup rules. In particular, do not |
| 4576 | create any nested <code>std</code> namespaces. Prefer unique project |
| 4577 | identifiers |
| 4578 | (<code>websearch::index</code>, <code>websearch::index_util</code>) |
| 4579 | over collision-prone names like <code>websearch::util</code>.</p> |
| 4580 | |
| 4581 | <p>For <code>internal</code> namespaces, be wary of other code being |
| 4582 | added to the same <code>internal</code> namespace causing a collision |
| 4583 | (internal helpers within a team tend to be related and may lead to |
| 4584 | collisions). In such a situation, using the filename to make a unique |
| 4585 | internal name is helpful |
| 4586 | (<code>websearch::index::frobber_internal</code> for use |
| 4587 | in <code>frobber.h</code>)</p> |
| 4588 | |
| 4589 | </div> |
| 4590 | |
| 4591 | <h3 id="Enumerator_Names">Enumerator Names</h3> |
| 4592 | |
| 4593 | <div class="summary"> |
| 4594 | <p>Enumerators (for both scoped and unscoped enums) should be named <i>either</i> like |
| 4595 | <a href="#Constant_Names">constants</a> or like |
| 4596 | <a href="#Macro_Names">macros</a>: either <code>kEnumName</code> or |
| 4597 | <code>ENUM_NAME</code>.</p> |
| 4598 | </div> |
| 4599 | |
| 4600 | <div class="stylebody"> |
| 4601 | |
| 4602 | <p>Preferably, the individual enumerators should be named |
| 4603 | like <a href="#Constant_Names">constants</a>. However, it |
| 4604 | is also acceptable to name them like |
| 4605 | <a href="#Macro_Names">macros</a>. The enumeration name, |
| 4606 | <code>UrlTableErrors</code> (and |
| 4607 | <code>AlternateUrlTableErrors</code>), is a type, and |
| 4608 | therefore mixed case.</p> |
| 4609 | |
| 4610 | <pre>enum UrlTableErrors { |
| 4611 | kOK = 0, |
| 4612 | kErrorOutOfMemory, |
| 4613 | kErrorMalformedInput, |
| 4614 | }; |
| 4615 | enum AlternateUrlTableErrors { |
| 4616 | OK = 0, |
| 4617 | OUT_OF_MEMORY = 1, |
| 4618 | MALFORMED_INPUT = 2, |
| 4619 | }; |
| 4620 | </pre> |
| 4621 | |
| 4622 | <p>Until January 2009, the style was to name enum values |
| 4623 | like <a href="#Macro_Names">macros</a>. This caused |
| 4624 | problems with name collisions between enum values and |
| 4625 | macros. Hence, the change to prefer constant-style naming |
| 4626 | was put in place. New code should prefer constant-style |
| 4627 | naming if possible. However, there is no reason to change |
| 4628 | old code to use constant-style names, unless the old |
| 4629 | names are actually causing a compile-time problem.</p> |
| 4630 | |
| 4631 | |
| 4632 | |
| 4633 | </div> |
| 4634 | |
| 4635 | <h3 id="Macro_Names">Macro Names</h3> |
| 4636 | |
| 4637 | <div class="summary"> |
| 4638 | <p>You're not really going to <a href="#Preprocessor_Macros"> |
| 4639 | define a macro</a>, are you? If you do, they're like this: |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4640 | <code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN_AND_ADULTS_ALIKE</code>. |
| 4641 | </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4642 | </div> |
| 4643 | |
| 4644 | <div class="stylebody"> |
| 4645 | |
| 4646 | <p>Please see the <a href="#Preprocessor_Macros">description |
| 4647 | of macros</a>; in general macros should <em>not</em> be used. |
| 4648 | However, if they are absolutely needed, then they should be |
| 4649 | named with all capitals and underscores.</p> |
| 4650 | |
| 4651 | <pre>#define ROUND(x) ... |
| 4652 | #define PI_ROUNDED 3.0 |
| 4653 | </pre> |
| 4654 | |
| 4655 | </div> |
| 4656 | |
| 4657 | <h3 id="Exceptions_to_Naming_Rules">Exceptions to Naming Rules</h3> |
| 4658 | |
| 4659 | <div class="summary"> |
| 4660 | <p>If you are naming something that is analogous to an |
| 4661 | existing C or C++ entity then you can follow the existing |
| 4662 | naming convention scheme.</p> |
| 4663 | </div> |
| 4664 | |
| 4665 | <div class="stylebody"> |
| 4666 | |
| 4667 | <dl> |
| 4668 | <dt><code>bigopen()</code></dt> |
| 4669 | <dd>function name, follows form of <code>open()</code></dd> |
| 4670 | |
| 4671 | <dt><code>uint</code></dt> |
| 4672 | <dd><code>typedef</code></dd> |
| 4673 | |
| 4674 | <dt><code>bigpos</code></dt> |
| 4675 | <dd><code>struct</code> or <code>class</code>, follows |
| 4676 | form of <code>pos</code></dd> |
| 4677 | |
| 4678 | <dt><code>sparse_hash_map</code></dt> |
| 4679 | <dd>STL-like entity; follows STL naming conventions</dd> |
| 4680 | |
| 4681 | <dt><code>LONGLONG_MAX</code></dt> |
| 4682 | <dd>a constant, as in <code>INT_MAX</code></dd> |
| 4683 | </dl> |
| 4684 | |
| 4685 | </div> |
| 4686 | |
| 4687 | <h2 id="Comments">Comments</h2> |
| 4688 | |
| 4689 | <p>Though a pain to write, comments are absolutely vital to |
| 4690 | keeping our code readable. The following rules describe what |
| 4691 | you should comment and where. But remember: while comments are |
| 4692 | very important, the best code is self-documenting. Giving |
| 4693 | sensible names to types and variables is much better than using |
| 4694 | obscure names that you must then explain through comments.</p> |
| 4695 | |
| 4696 | <p>When writing your comments, write for your audience: the |
| 4697 | next |
| 4698 | contributor who will need to |
| 4699 | understand your code. Be generous — the next |
| 4700 | one may be you!</p> |
| 4701 | |
| 4702 | <h3 id="Comment_Style">Comment Style</h3> |
| 4703 | |
| 4704 | <div class="summary"> |
| 4705 | <p>Use either the <code>//</code> or <code>/* */</code> |
| 4706 | syntax, as long as you are consistent.</p> |
| 4707 | </div> |
| 4708 | |
| 4709 | <div class="stylebody"> |
| 4710 | |
| 4711 | <p>You can use either the <code>//</code> or the <code>/* |
| 4712 | */</code> syntax; however, <code>//</code> is |
| 4713 | <em>much</em> more common. Be consistent with how you |
| 4714 | comment and what style you use where.</p> |
| 4715 | |
| 4716 | </div> |
| 4717 | |
| 4718 | <h3 id="File_Comments">File Comments</h3> |
| 4719 | |
| 4720 | <div class="summary"> |
| 4721 | <p>Start each file with license boilerplate.</p> |
| 4722 | |
| 4723 | <p>File comments describe the contents of a file. If a file declares, |
| 4724 | implements, or tests exactly one abstraction that is documented by a comment |
| 4725 | at the point of declaration, file comments are not required. All other files |
| 4726 | must have file comments.</p> |
| 4727 | |
| 4728 | </div> |
| 4729 | |
| 4730 | <div class="stylebody"> |
| 4731 | |
| 4732 | <h4 class="stylepoint_subsection">Legal Notice and Author |
| 4733 | Line</h4> |
| 4734 | |
| 4735 | |
| 4736 | |
| 4737 | <p>Every file should contain license |
| 4738 | boilerplate. Choose the appropriate boilerplate for the |
| 4739 | license used by the project (for example, Apache 2.0, |
| 4740 | BSD, LGPL, GPL).</p> |
| 4741 | |
| 4742 | <p>If you make significant changes to a file with an |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4743 | author line, consider deleting the author line. |
| 4744 | New files should usually not contain copyright notice or |
| 4745 | author line.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4746 | |
| 4747 | <h4 class="stylepoint_subsection">File Contents</h4> |
| 4748 | |
| 4749 | <p>If a <code>.h</code> declares multiple abstractions, the file-level comment |
| 4750 | should broadly describe the contents of the file, and how the abstractions are |
| 4751 | related. A 1 or 2 sentence file-level comment may be sufficient. The detailed |
| 4752 | documentation about individual abstractions belongs with those abstractions, |
| 4753 | not at the file level.</p> |
| 4754 | |
| 4755 | <p>Do not duplicate comments in both the <code>.h</code> and the |
| 4756 | <code>.cc</code>. Duplicated comments diverge.</p> |
| 4757 | |
| 4758 | </div> |
| 4759 | |
| 4760 | <h3 id="Class_Comments">Class Comments</h3> |
| 4761 | |
| 4762 | <div class="summary"> |
| 4763 | <p>Every non-obvious class declaration should have an accompanying |
| 4764 | comment that describes what it is for and how it should be used.</p> |
| 4765 | </div> |
| 4766 | |
| 4767 | <div class="stylebody"> |
| 4768 | |
| 4769 | <pre>// Iterates over the contents of a GargantuanTable. |
| 4770 | // Example: |
| 4771 | // GargantuanTableIterator* iter = table->NewIterator(); |
| 4772 | // for (iter->Seek("foo"); !iter->done(); iter->Next()) { |
| 4773 | // process(iter->key(), iter->value()); |
| 4774 | // } |
| 4775 | // delete iter; |
| 4776 | class GargantuanTableIterator { |
| 4777 | ... |
| 4778 | }; |
| 4779 | </pre> |
| 4780 | |
| 4781 | <p>The class comment should provide the reader with enough information to know |
| 4782 | how and when to use the class, as well as any additional considerations |
| 4783 | necessary to correctly use the class. Document the synchronization assumptions |
| 4784 | the class makes, if any. If an instance of the class can be accessed by |
| 4785 | multiple threads, take extra care to document the rules and invariants |
| 4786 | surrounding multithreaded use.</p> |
| 4787 | |
| 4788 | <p>The class comment is often a good place for a small example code snippet |
| 4789 | demonstrating a simple and focused usage of the class.</p> |
| 4790 | |
| 4791 | <p>When sufficiently separated (e.g. <code>.h</code> and <code>.cc</code> |
| 4792 | files), comments describing the use of the class should go together with its |
| 4793 | interface definition; comments about the class operation and implementation |
| 4794 | should accompany the implementation of the class's methods.</p> |
| 4795 | |
| 4796 | </div> |
| 4797 | |
| 4798 | <h3 id="Function_Comments">Function Comments</h3> |
| 4799 | |
| 4800 | <div class="summary"> |
| 4801 | <p>Declaration comments describe use of the function (when it is |
| 4802 | non-obvious); comments at the definition of a function describe |
| 4803 | operation.</p> |
| 4804 | </div> |
| 4805 | |
| 4806 | <div class="stylebody"> |
| 4807 | |
| 4808 | <h4 class="stylepoint_subsection">Function Declarations</h4> |
| 4809 | |
| 4810 | <p>Almost every function declaration should have comments immediately |
| 4811 | preceding it that describe what the function does and how to use |
| 4812 | it. These comments may be omitted only if the function is simple and |
| 4813 | obvious (e.g. simple accessors for obvious properties of the |
| 4814 | class). These comments should be descriptive ("Opens the file") |
| 4815 | rather than imperative ("Open the file"); the comment describes the |
| 4816 | function, it does not tell the function what to do. In general, these |
| 4817 | comments do not describe how the function performs its task. Instead, |
| 4818 | that should be left to comments in the function definition.</p> |
| 4819 | |
| 4820 | <p>Types of things to mention in comments at the function |
| 4821 | declaration:</p> |
| 4822 | |
| 4823 | <ul> |
| 4824 | <li>What the inputs and outputs are.</li> |
| 4825 | |
| 4826 | <li>For class member functions: whether the object |
| 4827 | remembers reference arguments beyond the duration of |
| 4828 | the method call, and whether it will free them or |
| 4829 | not.</li> |
| 4830 | |
| 4831 | <li>If the function allocates memory that the caller |
| 4832 | must free.</li> |
| 4833 | |
| 4834 | <li>Whether any of the arguments can be a null |
| 4835 | pointer.</li> |
| 4836 | |
| 4837 | <li>If there are any performance implications of how a |
| 4838 | function is used.</li> |
| 4839 | |
| 4840 | <li>If the function is re-entrant. What are its |
| 4841 | synchronization assumptions?</li> |
| 4842 | </ul> |
| 4843 | |
| 4844 | <p>Here is an example:</p> |
| 4845 | |
| 4846 | <pre>// Returns an iterator for this table. It is the client's |
| 4847 | // responsibility to delete the iterator when it is done with it, |
| 4848 | // and it must not use the iterator once the GargantuanTable object |
| 4849 | // on which the iterator was created has been deleted. |
| 4850 | // |
| 4851 | // The iterator is initially positioned at the beginning of the table. |
| 4852 | // |
| 4853 | // This method is equivalent to: |
| 4854 | // Iterator* iter = table->NewIterator(); |
| 4855 | // iter->Seek(""); |
| 4856 | // return iter; |
| 4857 | // If you are going to immediately seek to another place in the |
| 4858 | // returned iterator, it will be faster to use NewIterator() |
| 4859 | // and avoid the extra seek. |
| 4860 | Iterator* GetIterator() const; |
| 4861 | </pre> |
| 4862 | |
| 4863 | <p>However, do not be unnecessarily verbose or state the |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4864 | completely obvious.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4865 | |
| 4866 | <p>When documenting function overrides, focus on the |
| 4867 | specifics of the override itself, rather than repeating |
| 4868 | the comment from the overridden function. In many of these |
| 4869 | cases, the override needs no additional documentation and |
| 4870 | thus no comment is required.</p> |
| 4871 | |
| 4872 | <p>When commenting constructors and destructors, remember |
| 4873 | that the person reading your code knows what constructors |
| 4874 | and destructors are for, so comments that just say |
| 4875 | something like "destroys this object" are not useful. |
| 4876 | Document what constructors do with their arguments (for |
| 4877 | example, if they take ownership of pointers), and what |
| 4878 | cleanup the destructor does. If this is trivial, just |
| 4879 | skip the comment. It is quite common for destructors not |
| 4880 | to have a header comment.</p> |
| 4881 | |
| 4882 | <h4 class="stylepoint_subsection">Function Definitions</h4> |
| 4883 | |
| 4884 | <p>If there is anything tricky about how a function does |
| 4885 | its job, the function definition should have an |
| 4886 | explanatory comment. For example, in the definition |
| 4887 | comment you might describe any coding tricks you use, |
| 4888 | give an overview of the steps you go through, or explain |
| 4889 | why you chose to implement the function in the way you |
| 4890 | did rather than using a viable alternative. For instance, |
| 4891 | you might mention why it must acquire a lock for the |
| 4892 | first half of the function but why it is not needed for |
| 4893 | the second half.</p> |
| 4894 | |
| 4895 | <p>Note you should <em>not</em> just repeat the comments |
| 4896 | given with the function declaration, in the |
| 4897 | <code>.h</code> file or wherever. It's okay to |
| 4898 | recapitulate briefly what the function does, but the |
| 4899 | focus of the comments should be on how it does it.</p> |
| 4900 | |
| 4901 | </div> |
| 4902 | |
| 4903 | <h3 id="Variable_Comments">Variable Comments</h3> |
| 4904 | |
| 4905 | <div class="summary"> |
| 4906 | <p>In general the actual name of the variable should be |
| 4907 | descriptive enough to give a good idea of what the variable |
| 4908 | is used for. In certain cases, more comments are required.</p> |
| 4909 | </div> |
| 4910 | |
| 4911 | <div class="stylebody"> |
| 4912 | |
| 4913 | <h4 class="stylepoint_subsection">Class Data Members</h4> |
| 4914 | |
| 4915 | <p>The purpose of each class data member (also called an instance |
| 4916 | variable or member variable) must be clear. If there are any |
| 4917 | invariants (special values, relationships between members, lifetime |
| 4918 | requirements) not clearly expressed by the type and name, they must be |
| 4919 | commented. However, if the type and name suffice (<code>int |
| 4920 | num_events_;</code>), no comment is needed.</p> |
| 4921 | |
| 4922 | <p>In particular, add comments to describe the existence and meaning |
| 4923 | of sentinel values, such as nullptr or -1, when they are not |
| 4924 | obvious. For example:</p> |
| 4925 | |
| 4926 | <pre>private: |
| 4927 | // Used to bounds-check table accesses. -1 means |
| 4928 | // that we don't yet know how many entries the table has. |
| 4929 | int num_total_entries_; |
| 4930 | </pre> |
| 4931 | |
| 4932 | <h4 class="stylepoint_subsection">Global Variables</h4> |
| 4933 | |
| 4934 | <p>All global variables should have a comment describing what they |
| 4935 | are, what they are used for, and (if unclear) why it needs to be |
| 4936 | global. For example:</p> |
| 4937 | |
| 4938 | <pre>// The total number of tests cases that we run through in this regression test. |
| 4939 | const int kNumTestCases = 6; |
| 4940 | </pre> |
| 4941 | |
| 4942 | </div> |
| 4943 | |
| 4944 | <h3 id="Implementation_Comments">Implementation Comments</h3> |
| 4945 | |
| 4946 | <div class="summary"> |
| 4947 | <p>In your implementation you should have comments in tricky, |
| 4948 | non-obvious, interesting, or important parts of your code.</p> |
| 4949 | </div> |
| 4950 | |
| 4951 | <div class="stylebody"> |
| 4952 | |
| 4953 | <h4 class="stylepoint_subsection">Explanatory Comments</h4> |
| 4954 | |
| 4955 | <p>Tricky or complicated code blocks should have comments |
| 4956 | before them. Example:</p> |
| 4957 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4958 | <pre>// Divides result by two, taking into account that x |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4959 | // contains the carry from the add. |
| 4960 | for (int i = 0; i < result->size(); i++) { |
| 4961 | x = (x << 8) + (*result)[i]; |
| 4962 | (*result)[i] = x >> 1; |
| 4963 | x &= 1; |
| 4964 | } |
| 4965 | </pre> |
| 4966 | |
| 4967 | <h4 class="stylepoint_subsection">Line Comments</h4> |
| 4968 | |
| 4969 | <p>Also, lines that are non-obvious should get a comment |
| 4970 | at the end of the line. These end-of-line comments should |
| 4971 | be separated from the code by 2 spaces. Example:</p> |
| 4972 | |
| 4973 | <pre>// If we have enough memory, mmap the data portion too. |
| 4974 | mmap_budget = max<int64>(0, mmap_budget - index_->length()); |
| 4975 | if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock)) |
| 4976 | return; // Error already logged. |
| 4977 | </pre> |
| 4978 | |
| 4979 | <p>Note that there are both comments that describe what |
| 4980 | the code is doing, and comments that mention that an |
| 4981 | error has already been logged when the function |
| 4982 | returns.</p> |
| 4983 | |
| 4984 | <p>If you have several comments on subsequent lines, it |
| 4985 | can often be more readable to line them up:</p> |
| 4986 | |
| 4987 | <pre>DoSomething(); // Comment here so the comments line up. |
| 4988 | DoSomethingElseThatIsLonger(); // Two spaces between the code and the comment. |
| 4989 | { // One space before comment when opening a new scope is allowed, |
| 4990 | // thus the comment lines up with the following comments and code. |
| 4991 | DoSomethingElse(); // Two spaces before line comments normally. |
| 4992 | } |
| 4993 | std::vector<string> list{ |
| 4994 | // Comments in braced lists describe the next element... |
| 4995 | "First item", |
| 4996 | // .. and should be aligned appropriately. |
| 4997 | "Second item"}; |
| 4998 | DoSomething(); /* For trailing block comments, one space is fine. */ |
| 4999 | </pre> |
| 5000 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5001 | <h4 class="stylepoint_subsection" id="Function_Argument_Comments">Function Argument Comments</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5002 | |
| 5003 | <p>When the meaning of a function argument is nonobvious, consider |
| 5004 | one of the following remedies:</p> |
| 5005 | |
| 5006 | <ul> |
| 5007 | <li>If the argument is a literal constant, and the same constant is |
| 5008 | used in multiple function calls in a way that tacitly assumes they're |
| 5009 | the same, you should use a named constant to make that constraint |
| 5010 | explicit, and to guarantee that it holds.</li> |
| 5011 | |
| 5012 | <li>Consider changing the function signature to replace a <code>bool</code> |
| 5013 | argument with an <code>enum</code> argument. This will make the argument |
| 5014 | values self-describing.</li> |
| 5015 | |
| 5016 | <li>For functions that have several configuration options, consider |
| 5017 | defining a single class or struct to hold all the options |
| 5018 | , |
| 5019 | and pass an instance of that. |
| 5020 | This approach has several advantages. Options are referenced by name |
| 5021 | at the call site, which clarifies their meaning. It also reduces |
| 5022 | function argument count, which makes function calls easier to read and |
| 5023 | write. As an added benefit, you don't have to change call sites when |
| 5024 | you add another option. |
| 5025 | </li> |
| 5026 | |
| 5027 | <li>Replace large or complex nested expressions with named variables.</li> |
| 5028 | |
| 5029 | <li>As a last resort, use comments to clarify argument meanings at the |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5030 | call site. </li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5031 | </ul> |
| 5032 | |
| 5033 | Consider the following example: |
| 5034 | |
| 5035 | <pre class="badcode">// What are these arguments? |
| 5036 | const DecimalNumber product = CalculateProduct(values, 7, false, nullptr); |
| 5037 | </pre> |
| 5038 | |
| 5039 | <p>versus:</p> |
| 5040 | |
| 5041 | <pre>ProductOptions options; |
| 5042 | options.set_precision_decimals(7); |
| 5043 | options.set_use_cache(ProductOptions::kDontUseCache); |
| 5044 | const DecimalNumber product = |
| 5045 | CalculateProduct(values, options, /*completion_callback=*/nullptr); |
| 5046 | </pre> |
| 5047 | |
| 5048 | <h4 class="stylepoint_subsection">Don'ts</h4> |
| 5049 | |
| 5050 | <p>Do not state the obvious. In particular, don't literally describe what |
| 5051 | code does, unless the behavior is nonobvious to a reader who understands |
| 5052 | C++ well. Instead, provide higher level comments that describe <i>why</i> |
| 5053 | the code does what it does, or make the code self describing.</p> |
| 5054 | |
| 5055 | Compare this: |
| 5056 | |
| 5057 | <pre class="badcode">// Find the element in the vector. <-- Bad: obvious! |
| 5058 | auto iter = std::find(v.begin(), v.end(), element); |
| 5059 | if (iter != v.end()) { |
| 5060 | Process(element); |
| 5061 | } |
| 5062 | </pre> |
| 5063 | |
| 5064 | To this: |
| 5065 | |
| 5066 | <pre>// Process "element" unless it was already processed. |
| 5067 | auto iter = std::find(v.begin(), v.end(), element); |
| 5068 | if (iter != v.end()) { |
| 5069 | Process(element); |
| 5070 | } |
| 5071 | </pre> |
| 5072 | |
| 5073 | Self-describing code doesn't need a comment. The comment from |
| 5074 | the example above would be obvious: |
| 5075 | |
| 5076 | <pre>if (!IsAlreadyProcessed(element)) { |
| 5077 | Process(element); |
| 5078 | } |
| 5079 | </pre> |
| 5080 | |
| 5081 | </div> |
| 5082 | |
| 5083 | <h3 id="Punctuation,_Spelling_and_Grammar">Punctuation, Spelling and Grammar</h3> |
| 5084 | |
| 5085 | <div class="summary"> |
| 5086 | <p>Pay attention to punctuation, spelling, and grammar; it is |
| 5087 | easier to read well-written comments than badly written |
| 5088 | ones.</p> |
| 5089 | </div> |
| 5090 | |
| 5091 | <div class="stylebody"> |
| 5092 | |
| 5093 | <p>Comments should be as readable as narrative text, with |
| 5094 | proper capitalization and punctuation. In many cases, |
| 5095 | complete sentences are more readable than sentence |
| 5096 | fragments. Shorter comments, such as comments at the end |
| 5097 | of a line of code, can sometimes be less formal, but you |
| 5098 | should be consistent with your style.</p> |
| 5099 | |
| 5100 | <p>Although it can be frustrating to have a code reviewer |
| 5101 | point out that you are using a comma when you should be |
| 5102 | using a semicolon, it is very important that source code |
| 5103 | maintain a high level of clarity and readability. Proper |
| 5104 | punctuation, spelling, and grammar help with that |
| 5105 | goal.</p> |
| 5106 | |
| 5107 | </div> |
| 5108 | |
| 5109 | <h3 id="TODO_Comments">TODO Comments</h3> |
| 5110 | |
| 5111 | <div class="summary"> |
| 5112 | <p>Use <code>TODO</code> comments for code that is temporary, |
| 5113 | a short-term solution, or good-enough but not perfect.</p> |
| 5114 | </div> |
| 5115 | |
| 5116 | <div class="stylebody"> |
| 5117 | |
| 5118 | <p><code>TODO</code>s should include the string |
| 5119 | <code>TODO</code> in all caps, followed by the |
| 5120 | |
| 5121 | name, e-mail address, bug ID, or other |
| 5122 | identifier |
| 5123 | of the person or issue with the best context |
| 5124 | about the problem referenced by the <code>TODO</code>. The |
| 5125 | main purpose is to have a consistent <code>TODO</code> that |
| 5126 | can be searched to find out how to get more details upon |
| 5127 | request. A <code>TODO</code> is not a commitment that the |
| 5128 | person referenced will fix the problem. Thus when you create |
| 5129 | a <code>TODO</code> with a name, it is almost always your |
| 5130 | name that is given.</p> |
| 5131 | |
| 5132 | |
| 5133 | |
| 5134 | <div> |
| 5135 | <pre>// TODO(kl@gmail.com): Use a "*" here for concatenation operator. |
| 5136 | // TODO(Zeke) change this to use relations. |
| 5137 | // TODO(bug 12345): remove the "Last visitors" feature |
| 5138 | </pre> |
| 5139 | </div> |
| 5140 | |
| 5141 | <p>If your <code>TODO</code> is of the form "At a future |
| 5142 | date do something" make sure that you either include a |
| 5143 | very specific date ("Fix by November 2005") or a very |
| 5144 | specific event ("Remove this code when all clients can |
| 5145 | handle XML responses.").</p> |
| 5146 | |
| 5147 | </div> |
| 5148 | |
| 5149 | <h3 id="Deprecation_Comments">Deprecation Comments</h3> |
| 5150 | |
| 5151 | <div class="summary"> |
| 5152 | <p>Mark deprecated interface points with <code>DEPRECATED</code> |
| 5153 | comments.</p> |
| 5154 | </div> |
| 5155 | |
| 5156 | <div class="stylebody"> |
| 5157 | |
| 5158 | <p>You can mark an interface as deprecated by writing a |
| 5159 | comment containing the word <code>DEPRECATED</code> in |
| 5160 | all caps. The comment goes either before the declaration |
| 5161 | of the interface or on the same line as the |
| 5162 | declaration.</p> |
| 5163 | |
| 5164 | |
| 5165 | |
| 5166 | <p>After the word |
| 5167 | <code>DEPRECATED</code>, write your name, e-mail address, |
| 5168 | or other identifier in parentheses.</p> |
| 5169 | |
| 5170 | <p>A deprecation comment must include simple, clear |
| 5171 | directions for people to fix their callsites. In C++, you |
| 5172 | can implement a deprecated function as an inline function |
| 5173 | that calls the new interface point.</p> |
| 5174 | |
| 5175 | <p>Marking an interface point <code>DEPRECATED</code> |
| 5176 | will not magically cause any callsites to change. If you |
| 5177 | want people to actually stop using the deprecated |
| 5178 | facility, you will have to fix the callsites yourself or |
| 5179 | recruit a crew to help you.</p> |
| 5180 | |
| 5181 | <p>New code should not contain calls to deprecated |
| 5182 | interface points. Use the new interface point instead. If |
| 5183 | you cannot understand the directions, find the person who |
| 5184 | created the deprecation and ask them for help using the |
| 5185 | new interface point.</p> |
| 5186 | |
| 5187 | |
| 5188 | |
| 5189 | </div> |
| 5190 | |
| 5191 | <h2 id="Formatting">Formatting</h2> |
| 5192 | |
| 5193 | <p>Coding style and formatting are pretty arbitrary, but a |
| 5194 | |
| 5195 | project is much easier to follow |
| 5196 | if everyone uses the same style. Individuals may not agree with every |
| 5197 | aspect of the formatting rules, and some of the rules may take |
| 5198 | some getting used to, but it is important that all |
| 5199 | |
| 5200 | project contributors follow the |
| 5201 | style rules so that |
| 5202 | they can all read and understand |
| 5203 | everyone's code easily.</p> |
| 5204 | |
| 5205 | |
| 5206 | |
| 5207 | <p>To help you format code correctly, we've |
| 5208 | created a |
| 5209 | <a href="https://raw.githubusercontent.com/google/styleguide/gh-pages/google-c-style.el"> |
| 5210 | settings file for emacs</a>.</p> |
| 5211 | |
| 5212 | <h3 id="Line_Length">Line Length</h3> |
| 5213 | |
| 5214 | <div class="summary"> |
| 5215 | <p>Each line of text in your code should be at most 80 |
| 5216 | characters long.</p> |
| 5217 | </div> |
| 5218 | |
| 5219 | <div class="stylebody"> |
| 5220 | |
| 5221 | |
| 5222 | |
| 5223 | <p>We recognize that this rule is |
| 5224 | controversial, but so much existing code already adheres |
| 5225 | to it, and we feel that consistency is important.</p> |
| 5226 | |
| 5227 | <div class="pros"> |
| 5228 | <p>Those who favor this rule |
| 5229 | argue that it is rude to force them to resize |
| 5230 | their windows and there is no need for anything longer. |
| 5231 | Some folks are used to having several code windows |
| 5232 | side-by-side, and thus don't have room to widen their |
| 5233 | windows in any case. People set up their work environment |
| 5234 | assuming a particular maximum window width, and 80 |
| 5235 | columns has been the traditional standard. Why change |
| 5236 | it?</p> |
| 5237 | </div> |
| 5238 | |
| 5239 | <div class="cons"> |
| 5240 | <p>Proponents of change argue that a wider line can make |
| 5241 | code more readable. The 80-column limit is an hidebound |
| 5242 | throwback to 1960s mainframes; modern equipment has wide screens that |
| 5243 | can easily show longer lines.</p> |
| 5244 | </div> |
| 5245 | |
| 5246 | <div class="decision"> |
| 5247 | <p> 80 characters is the maximum.</p> |
| 5248 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5249 | <p>A line may exceed 80 characters if it is</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5250 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5251 | <ul> |
| 5252 | <li>a comment line which is not feasible to split without harming |
| 5253 | readability, ease of cut and paste or auto-linking -- e.g. if a line |
| 5254 | contains an example command or a literal URL longer than 80 characters.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5255 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5256 | <li>a raw-string literal with content that exceeds 80 characters. Except for |
| 5257 | test code, such literals should appear near the top of a file.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5258 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5259 | <li>an include statement.</li> |
| 5260 | |
| 5261 | <li>a <a href="#The__define_Guard">header guard</a></li> |
| 5262 | |
| 5263 | <li>a using-declaration</li> |
| 5264 | </ul> |
| 5265 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5266 | </div> |
| 5267 | |
| 5268 | </div> |
| 5269 | |
| 5270 | <h3 id="Non-ASCII_Characters">Non-ASCII Characters</h3> |
| 5271 | |
| 5272 | <div class="summary"> |
| 5273 | <p>Non-ASCII characters should be rare, and must use UTF-8 |
| 5274 | formatting.</p> |
| 5275 | </div> |
| 5276 | |
| 5277 | <div class="stylebody"> |
| 5278 | |
| 5279 | <p>You shouldn't hard-code user-facing text in source, |
| 5280 | even English, so use of non-ASCII characters should be |
| 5281 | rare. However, in certain cases it is appropriate to |
| 5282 | include such words in your code. For example, if your |
| 5283 | code parses data files from foreign sources, it may be |
| 5284 | appropriate to hard-code the non-ASCII string(s) used in |
| 5285 | those data files as delimiters. More commonly, unittest |
| 5286 | code (which does not need to be localized) might |
| 5287 | contain non-ASCII strings. In such cases, you should use |
| 5288 | UTF-8, since that is an encoding |
| 5289 | understood by most tools able to handle more than just |
| 5290 | ASCII.</p> |
| 5291 | |
| 5292 | <p>Hex encoding is also OK, and encouraged where it |
| 5293 | enhances readability — for example, |
| 5294 | <code>"\xEF\xBB\xBF"</code>, or, even more simply, |
| 5295 | <code>u8"\uFEFF"</code>, is the Unicode zero-width |
| 5296 | no-break space character, which would be invisible if |
| 5297 | included in the source as straight UTF-8.</p> |
| 5298 | |
| 5299 | <p>Use the <code>u8</code> prefix |
| 5300 | to guarantee that a string literal containing |
| 5301 | <code>\uXXXX</code> escape sequences is encoded as UTF-8. |
| 5302 | Do not use it for strings containing non-ASCII characters |
| 5303 | encoded as UTF-8, because that will produce incorrect |
| 5304 | output if the compiler does not interpret the source file |
| 5305 | as UTF-8. </p> |
| 5306 | |
| 5307 | <p>You shouldn't use the C++11 <code>char16_t</code> and |
| 5308 | <code>char32_t</code> character types, since they're for |
| 5309 | non-UTF-8 text. For similar reasons you also shouldn't |
| 5310 | use <code>wchar_t</code> (unless you're writing code that |
| 5311 | interacts with the Windows API, which uses |
| 5312 | <code>wchar_t</code> extensively).</p> |
| 5313 | |
| 5314 | </div> |
| 5315 | |
| 5316 | <h3 id="Spaces_vs._Tabs">Spaces vs. Tabs</h3> |
| 5317 | |
| 5318 | <div class="summary"> |
| 5319 | <p>Use only spaces, and indent 2 spaces at a time.</p> |
| 5320 | </div> |
| 5321 | |
| 5322 | <div class="stylebody"> |
| 5323 | |
| 5324 | <p>We use spaces for indentation. Do not use tabs in your |
| 5325 | code. You should set your editor to emit spaces when you |
| 5326 | hit the tab key.</p> |
| 5327 | |
| 5328 | </div> |
| 5329 | |
| 5330 | <h3 id="Function_Declarations_and_Definitions">Function Declarations and Definitions</h3> |
| 5331 | |
| 5332 | <div class="summary"> |
| 5333 | <p>Return type on the same line as function name, parameters |
| 5334 | on the same line if they fit. Wrap parameter lists which do |
| 5335 | not fit on a single line as you would wrap arguments in a |
| 5336 | <a href="#Function_Calls">function call</a>.</p> |
| 5337 | </div> |
| 5338 | |
| 5339 | <div class="stylebody"> |
| 5340 | |
| 5341 | <p>Functions look like this:</p> |
| 5342 | |
| 5343 | |
| 5344 | <pre>ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) { |
| 5345 | DoSomething(); |
| 5346 | ... |
| 5347 | } |
| 5348 | </pre> |
| 5349 | |
| 5350 | <p>If you have too much text to fit on one line:</p> |
| 5351 | |
| 5352 | <pre>ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2, |
| 5353 | Type par_name3) { |
| 5354 | DoSomething(); |
| 5355 | ... |
| 5356 | } |
| 5357 | </pre> |
| 5358 | |
| 5359 | <p>or if you cannot fit even the first parameter:</p> |
| 5360 | |
| 5361 | <pre>ReturnType LongClassName::ReallyReallyReallyLongFunctionName( |
| 5362 | Type par_name1, // 4 space indent |
| 5363 | Type par_name2, |
| 5364 | Type par_name3) { |
| 5365 | DoSomething(); // 2 space indent |
| 5366 | ... |
| 5367 | } |
| 5368 | </pre> |
| 5369 | |
| 5370 | <p>Some points to note:</p> |
| 5371 | |
| 5372 | <ul> |
| 5373 | <li>Choose good parameter names.</li> |
| 5374 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5375 | <li>A parameter name may be omitted only if the parameter is not used in the |
| 5376 | function's definition.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5377 | |
| 5378 | <li>If you cannot fit the return type and the function |
| 5379 | name on a single line, break between them.</li> |
| 5380 | |
| 5381 | <li>If you break after the return type of a function |
| 5382 | declaration or definition, do not indent.</li> |
| 5383 | |
| 5384 | <li>The open parenthesis is always on the same line as |
| 5385 | the function name.</li> |
| 5386 | |
| 5387 | <li>There is never a space between the function name |
| 5388 | and the open parenthesis.</li> |
| 5389 | |
| 5390 | <li>There is never a space between the parentheses and |
| 5391 | the parameters.</li> |
| 5392 | |
| 5393 | <li>The open curly brace is always on the end of the last line of the function |
| 5394 | declaration, not the start of the next line.</li> |
| 5395 | |
| 5396 | <li>The close curly brace is either on the last line by |
| 5397 | itself or on the same line as the open curly brace.</li> |
| 5398 | |
| 5399 | <li>There should be a space between the close |
| 5400 | parenthesis and the open curly brace.</li> |
| 5401 | |
| 5402 | <li>All parameters should be aligned if possible.</li> |
| 5403 | |
| 5404 | <li>Default indentation is 2 spaces.</li> |
| 5405 | |
| 5406 | <li>Wrapped parameters have a 4 space indent.</li> |
| 5407 | </ul> |
| 5408 | |
| 5409 | <p>Unused parameters that are obvious from context may be omitted:</p> |
| 5410 | |
| 5411 | <pre>class Foo { |
| 5412 | public: |
| 5413 | Foo(Foo&&); |
| 5414 | Foo(const Foo&); |
| 5415 | Foo& operator=(Foo&&); |
| 5416 | Foo& operator=(const Foo&); |
| 5417 | }; |
| 5418 | </pre> |
| 5419 | |
| 5420 | <p>Unused parameters that might not be obvious should comment out the variable |
| 5421 | name in the function definition:</p> |
| 5422 | |
| 5423 | <pre>class Shape { |
| 5424 | public: |
| 5425 | virtual void Rotate(double radians) = 0; |
| 5426 | }; |
| 5427 | |
| 5428 | class Circle : public Shape { |
| 5429 | public: |
| 5430 | void Rotate(double radians) override; |
| 5431 | }; |
| 5432 | |
| 5433 | void Circle::Rotate(double /*radians*/) {} |
| 5434 | </pre> |
| 5435 | |
| 5436 | <pre class="badcode">// Bad - if someone wants to implement later, it's not clear what the |
| 5437 | // variable means. |
| 5438 | void Circle::Rotate(double) {} |
| 5439 | </pre> |
| 5440 | |
| 5441 | <p>Attributes, and macros that expand to attributes, appear at the very |
| 5442 | beginning of the function declaration or definition, before the |
| 5443 | return type:</p> |
| 5444 | <pre>MUST_USE_RESULT bool IsOK(); |
| 5445 | </pre> |
| 5446 | |
| 5447 | </div> |
| 5448 | |
| 5449 | <h3 id="Formatting_Lambda_Expressions">Lambda Expressions</h3> |
| 5450 | |
| 5451 | <div class="summary"> |
| 5452 | <p>Format parameters and bodies as for any other function, and capture |
| 5453 | lists like other comma-separated lists.</p> |
| 5454 | </div> |
| 5455 | |
| 5456 | <div class="stylebody"> |
| 5457 | <p>For by-reference captures, do not leave a space between the |
| 5458 | ampersand (&) and the variable name.</p> |
| 5459 | <pre>int x = 0; |
| 5460 | auto x_plus_n = [&x](int n) -> int { return x + n; } |
| 5461 | </pre> |
| 5462 | <p>Short lambdas may be written inline as function arguments.</p> |
| 5463 | <pre>std::set<int> blacklist = {7, 8, 9}; |
| 5464 | std::vector<int> digits = {3, 9, 1, 8, 4, 7, 1}; |
| 5465 | digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) { |
| 5466 | return blacklist.find(i) != blacklist.end(); |
| 5467 | }), |
| 5468 | digits.end()); |
| 5469 | </pre> |
| 5470 | |
| 5471 | </div> |
| 5472 | |
| 5473 | <h3 id="Function_Calls">Function Calls</h3> |
| 5474 | |
| 5475 | <div class="summary"> |
| 5476 | <p>Either write the call all on a single line, wrap the |
| 5477 | arguments at the parenthesis, or start the arguments on a new |
| 5478 | line indented by four spaces and continue at that 4 space |
| 5479 | indent. In the absence of other considerations, use the |
| 5480 | minimum number of lines, including placing multiple arguments |
| 5481 | on each line where appropriate.</p> |
| 5482 | </div> |
| 5483 | |
| 5484 | <div class="stylebody"> |
| 5485 | |
| 5486 | <p>Function calls have the following format:</p> |
| 5487 | <pre>bool result = DoSomething(argument1, argument2, argument3); |
| 5488 | </pre> |
| 5489 | |
| 5490 | <p>If the arguments do not all fit on one line, they |
| 5491 | should be broken up onto multiple lines, with each |
| 5492 | subsequent line aligned with the first argument. Do not |
| 5493 | add spaces after the open paren or before the close |
| 5494 | paren:</p> |
| 5495 | <pre>bool result = DoSomething(averyveryveryverylongargument1, |
| 5496 | argument2, argument3); |
| 5497 | </pre> |
| 5498 | |
| 5499 | <p>Arguments may optionally all be placed on subsequent |
| 5500 | lines with a four space indent:</p> |
| 5501 | <pre>if (...) { |
| 5502 | ... |
| 5503 | ... |
| 5504 | if (...) { |
| 5505 | bool result = DoSomething( |
| 5506 | argument1, argument2, // 4 space indent |
| 5507 | argument3, argument4); |
| 5508 | ... |
| 5509 | } |
| 5510 | </pre> |
| 5511 | |
| 5512 | <p>Put multiple arguments on a single line to reduce the |
| 5513 | number of lines necessary for calling a function unless |
| 5514 | there is a specific readability problem. Some find that |
| 5515 | formatting with strictly one argument on each line is |
| 5516 | more readable and simplifies editing of the arguments. |
| 5517 | However, we prioritize for the reader over the ease of |
| 5518 | editing arguments, and most readability problems are |
| 5519 | better addressed with the following techniques.</p> |
| 5520 | |
| 5521 | <p>If having multiple arguments in a single line decreases |
| 5522 | readability due to the complexity or confusing nature of the |
| 5523 | expressions that make up some arguments, try creating |
| 5524 | variables that capture those arguments in a descriptive name:</p> |
| 5525 | <pre>int my_heuristic = scores[x] * y + bases[x]; |
| 5526 | bool result = DoSomething(my_heuristic, x, y, z); |
| 5527 | </pre> |
| 5528 | |
| 5529 | <p>Or put the confusing argument on its own line with |
| 5530 | an explanatory comment:</p> |
| 5531 | <pre>bool result = DoSomething(scores[x] * y + bases[x], // Score heuristic. |
| 5532 | x, y, z); |
| 5533 | </pre> |
| 5534 | |
| 5535 | <p>If there is still a case where one argument is |
| 5536 | significantly more readable on its own line, then put it on |
| 5537 | its own line. The decision should be specific to the argument |
| 5538 | which is made more readable rather than a general policy.</p> |
| 5539 | |
| 5540 | <p>Sometimes arguments form a structure that is important |
| 5541 | for readability. In those cases, feel free to format the |
| 5542 | arguments according to that structure:</p> |
| 5543 | <pre>// Transform the widget by a 3x3 matrix. |
| 5544 | my_widget.Transform(x1, x2, x3, |
| 5545 | y1, y2, y3, |
| 5546 | z1, z2, z3); |
| 5547 | </pre> |
| 5548 | |
| 5549 | </div> |
| 5550 | |
| 5551 | <h3 id="Braced_Initializer_List_Format">Braced Initializer List Format</h3> |
| 5552 | |
| 5553 | <div class="summary"> |
| 5554 | <p>Format a <a href="#Braced_Initializer_List">braced initializer list</a> |
| 5555 | exactly like you would format a function call in its place.</p> |
| 5556 | </div> |
| 5557 | |
| 5558 | <div class="stylebody"> |
| 5559 | |
| 5560 | <p>If the braced list follows a name (e.g. a type or |
| 5561 | variable name), format as if the <code>{}</code> were the |
| 5562 | parentheses of a function call with that name. If there |
| 5563 | is no name, assume a zero-length name.</p> |
| 5564 | |
| 5565 | <pre>// Examples of braced init list on a single line. |
| 5566 | return {foo, bar}; |
| 5567 | functioncall({foo, bar}); |
| 5568 | std::pair<int, int> p{foo, bar}; |
| 5569 | |
| 5570 | // When you have to wrap. |
| 5571 | SomeFunction( |
| 5572 | {"assume a zero-length name before {"}, |
| 5573 | some_other_function_parameter); |
| 5574 | SomeType variable{ |
| 5575 | some, other, values, |
| 5576 | {"assume a zero-length name before {"}, |
| 5577 | SomeOtherType{ |
| 5578 | "Very long string requiring the surrounding breaks.", |
| 5579 | some, other values}, |
| 5580 | SomeOtherType{"Slightly shorter string", |
| 5581 | some, other, values}}; |
| 5582 | SomeType variable{ |
| 5583 | "This is too long to fit all in one line"}; |
| 5584 | MyType m = { // Here, you could also break before {. |
| 5585 | superlongvariablename1, |
| 5586 | superlongvariablename2, |
| 5587 | {short, interior, list}, |
| 5588 | {interiorwrappinglist, |
| 5589 | interiorwrappinglist2}}; |
| 5590 | </pre> |
| 5591 | |
| 5592 | </div> |
| 5593 | |
| 5594 | <h3 id="Conditionals">Conditionals</h3> |
| 5595 | |
| 5596 | <div class="summary"> |
| 5597 | <p>Prefer no spaces inside parentheses. The <code>if</code> |
| 5598 | and <code>else</code> keywords belong on separate lines.</p> |
| 5599 | </div> |
| 5600 | |
| 5601 | <div class="stylebody"> |
| 5602 | |
| 5603 | <p>There are two acceptable formats for a basic |
| 5604 | conditional statement. One includes spaces between the |
| 5605 | parentheses and the condition, and one does not.</p> |
| 5606 | |
| 5607 | <p>The most common form is without spaces. Either is |
| 5608 | fine, but <em>be consistent</em>. If you are modifying a |
| 5609 | file, use the format that is already present. If you are |
| 5610 | writing new code, use the format that the other files in |
| 5611 | that directory or project use. If in doubt and you have |
| 5612 | no personal preference, do not add the spaces.</p> |
| 5613 | |
| 5614 | <pre>if (condition) { // no spaces inside parentheses |
| 5615 | ... // 2 space indent. |
| 5616 | } else if (...) { // The else goes on the same line as the closing brace. |
| 5617 | ... |
| 5618 | } else { |
| 5619 | ... |
| 5620 | } |
| 5621 | </pre> |
| 5622 | |
| 5623 | <p>If you prefer you may add spaces inside the |
| 5624 | parentheses:</p> |
| 5625 | |
| 5626 | <pre>if ( condition ) { // spaces inside parentheses - rare |
| 5627 | ... // 2 space indent. |
| 5628 | } else { // The else goes on the same line as the closing brace. |
| 5629 | ... |
| 5630 | } |
| 5631 | </pre> |
| 5632 | |
| 5633 | <p>Note that in all cases you must have a space between |
| 5634 | the <code>if</code> and the open parenthesis. You must |
| 5635 | also have a space between the close parenthesis and the |
| 5636 | curly brace, if you're using one.</p> |
| 5637 | |
| 5638 | <pre class="badcode">if(condition) { // Bad - space missing after IF. |
| 5639 | if (condition){ // Bad - space missing before {. |
| 5640 | if(condition){ // Doubly bad. |
| 5641 | </pre> |
| 5642 | |
| 5643 | <pre>if (condition) { // Good - proper space after IF and before {. |
| 5644 | </pre> |
| 5645 | |
| 5646 | <p>Short conditional statements may be written on one |
| 5647 | line if this enhances readability. You may use this only |
| 5648 | when the line is brief and the statement does not use the |
| 5649 | <code>else</code> clause.</p> |
| 5650 | |
| 5651 | <pre>if (x == kFoo) return new Foo(); |
| 5652 | if (x == kBar) return new Bar(); |
| 5653 | </pre> |
| 5654 | |
| 5655 | <p>This is not allowed when the if statement has an |
| 5656 | <code>else</code>:</p> |
| 5657 | |
| 5658 | <pre class="badcode">// Not allowed - IF statement on one line when there is an ELSE clause |
| 5659 | if (x) DoThis(); |
| 5660 | else DoThat(); |
| 5661 | </pre> |
| 5662 | |
| 5663 | <p>In general, curly braces are not required for |
| 5664 | single-line statements, but they are allowed if you like |
| 5665 | them; conditional or loop statements with complex |
| 5666 | conditions or statements may be more readable with curly |
| 5667 | braces. Some |
| 5668 | projects require that an |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5669 | <code>if</code> must always have an accompanying |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5670 | brace.</p> |
| 5671 | |
| 5672 | <pre>if (condition) |
| 5673 | DoSomething(); // 2 space indent. |
| 5674 | |
| 5675 | if (condition) { |
| 5676 | DoSomething(); // 2 space indent. |
| 5677 | } |
| 5678 | </pre> |
| 5679 | |
| 5680 | <p>However, if one part of an |
| 5681 | <code>if</code>-<code>else</code> statement uses curly |
| 5682 | braces, the other part must too:</p> |
| 5683 | |
| 5684 | <pre class="badcode">// Not allowed - curly on IF but not ELSE |
| 5685 | if (condition) { |
| 5686 | foo; |
| 5687 | } else |
| 5688 | bar; |
| 5689 | |
| 5690 | // Not allowed - curly on ELSE but not IF |
| 5691 | if (condition) |
| 5692 | foo; |
| 5693 | else { |
| 5694 | bar; |
| 5695 | } |
| 5696 | </pre> |
| 5697 | |
| 5698 | <pre>// Curly braces around both IF and ELSE required because |
| 5699 | // one of the clauses used braces. |
| 5700 | if (condition) { |
| 5701 | foo; |
| 5702 | } else { |
| 5703 | bar; |
| 5704 | } |
| 5705 | </pre> |
| 5706 | |
| 5707 | </div> |
| 5708 | |
| 5709 | <h3 id="Loops_and_Switch_Statements">Loops and Switch Statements</h3> |
| 5710 | |
| 5711 | <div class="summary"> |
| 5712 | <p>Switch statements may use braces for blocks. Annotate |
| 5713 | non-trivial fall-through between cases. |
| 5714 | Braces are optional for single-statement loops. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5715 | Empty loop bodies should use either empty braces or <code>continue</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5716 | </div> |
| 5717 | |
| 5718 | <div class="stylebody"> |
| 5719 | |
| 5720 | <p><code>case</code> blocks in <code>switch</code> |
| 5721 | statements can have curly braces or not, depending on |
| 5722 | your preference. If you do include curly braces they |
| 5723 | should be placed as shown below.</p> |
| 5724 | |
| 5725 | <p>If not conditional on an enumerated value, switch |
| 5726 | statements should always have a <code>default</code> case |
| 5727 | (in the case of an enumerated value, the compiler will |
| 5728 | warn you if any values are not handled). If the default |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5729 | case should never execute, treat this as an error. For example: |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5730 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5731 | </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5732 | |
| 5733 | <div> |
| 5734 | <pre>switch (var) { |
| 5735 | case 0: { // 2 space indent |
| 5736 | ... // 4 space indent |
| 5737 | break; |
| 5738 | } |
| 5739 | case 1: { |
| 5740 | ... |
| 5741 | break; |
| 5742 | } |
| 5743 | default: { |
| 5744 | assert(false); |
| 5745 | } |
| 5746 | } |
| 5747 | </pre> |
| 5748 | </div> |
| 5749 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 5750 | <p>Fall-through from one case label to |
| 5751 | another must be annotated using the |
| 5752 | <code>ABSL_FALLTHROUGH_INTENDED;</code> macro (defined in |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5753 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 5754 | <code>absl/base/macros.h</code>). |
| 5755 | <code>ABSL_FALLTHROUGH_INTENDED;</code> should be placed at a |
| 5756 | point of execution where a fall-through to the next case |
| 5757 | label occurs. A common exception is consecutive case |
| 5758 | labels without intervening code, in which case no |
| 5759 | annotation is needed.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5760 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 5761 | <div> |
| 5762 | <pre>switch (x) { |
| 5763 | case 41: // No annotation needed here. |
| 5764 | case 43: |
| 5765 | if (dont_be_picky) { |
| 5766 | // Use this instead of or along with annotations in comments. |
| 5767 | ABSL_FALLTHROUGH_INTENDED; |
| 5768 | } else { |
| 5769 | CloseButNoCigar(); |
| 5770 | break; |
| 5771 | } |
| 5772 | case 42: |
| 5773 | DoSomethingSpecial(); |
| 5774 | ABSL_FALLTHROUGH_INTENDED; |
| 5775 | default: |
| 5776 | DoSomethingGeneric(); |
| 5777 | break; |
| 5778 | } |
| 5779 | </pre> |
| 5780 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5781 | |
| 5782 | <p> Braces are optional for single-statement loops.</p> |
| 5783 | |
| 5784 | <pre>for (int i = 0; i < kSomeNumber; ++i) |
| 5785 | printf("I love you\n"); |
| 5786 | |
| 5787 | for (int i = 0; i < kSomeNumber; ++i) { |
| 5788 | printf("I take it back\n"); |
| 5789 | } |
| 5790 | </pre> |
| 5791 | |
| 5792 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5793 | <p>Empty loop bodies should use either an empty pair of braces or |
| 5794 | <code>continue</code> with no braces, rather than a single semicolon.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5795 | |
| 5796 | <pre>while (condition) { |
| 5797 | // Repeat test until it returns false. |
| 5798 | } |
| 5799 | for (int i = 0; i < kSomeNumber; ++i) {} // Good - one newline is also OK. |
| 5800 | while (condition) continue; // Good - continue indicates no logic. |
| 5801 | </pre> |
| 5802 | |
| 5803 | <pre class="badcode">while (condition); // Bad - looks like part of do/while loop. |
| 5804 | </pre> |
| 5805 | |
| 5806 | </div> |
| 5807 | |
| 5808 | <h3 id="Pointer_and_Reference_Expressions">Pointer and Reference Expressions</h3> |
| 5809 | |
| 5810 | <div class="summary"> |
| 5811 | <p>No spaces around period or arrow. Pointer operators do not |
| 5812 | have trailing spaces.</p> |
| 5813 | </div> |
| 5814 | |
| 5815 | <div class="stylebody"> |
| 5816 | |
| 5817 | <p>The following are examples of correctly-formatted |
| 5818 | pointer and reference expressions:</p> |
| 5819 | |
| 5820 | <pre>x = *p; |
| 5821 | p = &x; |
| 5822 | x = r.y; |
| 5823 | x = r->y; |
| 5824 | </pre> |
| 5825 | |
| 5826 | <p>Note that:</p> |
| 5827 | |
| 5828 | <ul> |
| 5829 | <li>There are no spaces around the period or arrow when |
| 5830 | accessing a member.</li> |
| 5831 | |
| 5832 | <li>Pointer operators have no space after the |
| 5833 | <code>*</code> or <code>&</code>.</li> |
| 5834 | </ul> |
| 5835 | |
| 5836 | <p>When declaring a pointer variable or argument, you may |
| 5837 | place the asterisk adjacent to either the type or to the |
| 5838 | variable name:</p> |
| 5839 | |
| 5840 | <pre>// These are fine, space preceding. |
| 5841 | char *c; |
| 5842 | const string &str; |
| 5843 | |
| 5844 | // These are fine, space following. |
| 5845 | char* c; |
| 5846 | const string& str; |
| 5847 | </pre> |
| 5848 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5849 | <p>You should do this consistently within a single |
| 5850 | file, |
| 5851 | so, when modifying an existing file, use the style in |
| 5852 | that file.</p> |
| 5853 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5854 | It is allowed (if unusual) to declare multiple variables in the same |
| 5855 | declaration, but it is disallowed if any of those have pointer or |
| 5856 | reference decorations. Such declarations are easily misread. |
| 5857 | <pre>// Fine if helpful for readability. |
| 5858 | int x, y; |
| 5859 | </pre> |
| 5860 | <pre class="badcode">int x, *y; // Disallowed - no & or * in multiple declaration |
| 5861 | char * c; // Bad - spaces on both sides of * |
| 5862 | const string & str; // Bad - spaces on both sides of & |
| 5863 | </pre> |
| 5864 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5865 | </div> |
| 5866 | |
| 5867 | <h3 id="Boolean_Expressions">Boolean Expressions</h3> |
| 5868 | |
| 5869 | <div class="summary"> |
| 5870 | <p>When you have a boolean expression that is longer than the |
| 5871 | <a href="#Line_Length">standard line length</a>, be |
| 5872 | consistent in how you break up the lines.</p> |
| 5873 | </div> |
| 5874 | |
| 5875 | <div class="stylebody"> |
| 5876 | |
| 5877 | <p>In this example, the logical AND operator is always at |
| 5878 | the end of the lines:</p> |
| 5879 | |
| 5880 | <pre>if (this_one_thing > this_other_thing && |
| 5881 | a_third_thing == a_fourth_thing && |
| 5882 | yet_another && last_one) { |
| 5883 | ... |
| 5884 | } |
| 5885 | </pre> |
| 5886 | |
| 5887 | <p>Note that when the code wraps in this example, both of |
| 5888 | the <code>&&</code> logical AND operators are at |
| 5889 | the end of the line. This is more common in Google code, |
| 5890 | though wrapping all operators at the beginning of the |
| 5891 | line is also allowed. Feel free to insert extra |
| 5892 | parentheses judiciously because they can be very helpful |
| 5893 | in increasing readability when used |
| 5894 | appropriately. Also note that you should always use |
| 5895 | the punctuation operators, such as |
| 5896 | <code>&&</code> and <code>~</code>, rather than |
| 5897 | the word operators, such as <code>and</code> and |
| 5898 | <code>compl</code>.</p> |
| 5899 | |
| 5900 | </div> |
| 5901 | |
| 5902 | <h3 id="Return_Values">Return Values</h3> |
| 5903 | |
| 5904 | <div class="summary"> |
| 5905 | <p>Do not needlessly surround the <code>return</code> |
| 5906 | expression with parentheses.</p> |
| 5907 | </div> |
| 5908 | |
| 5909 | <div class="stylebody"> |
| 5910 | |
| 5911 | <p>Use parentheses in <code>return expr;</code> only |
| 5912 | where you would use them in <code>x = expr;</code>.</p> |
| 5913 | |
| 5914 | <pre>return result; // No parentheses in the simple case. |
| 5915 | // Parentheses OK to make a complex expression more readable. |
| 5916 | return (some_long_condition && |
| 5917 | another_condition); |
| 5918 | </pre> |
| 5919 | |
| 5920 | <pre class="badcode">return (value); // You wouldn't write var = (value); |
| 5921 | return(result); // return is not a function! |
| 5922 | </pre> |
| 5923 | |
| 5924 | </div> |
| 5925 | |
| 5926 | |
| 5927 | |
| 5928 | <h3 id="Variable_and_Array_Initialization">Variable and Array Initialization</h3> |
| 5929 | |
| 5930 | <div class="summary"> |
| 5931 | <p>Your choice of <code>=</code>, <code>()</code>, or |
| 5932 | <code>{}</code>.</p> |
| 5933 | </div> |
| 5934 | |
| 5935 | <div class="stylebody"> |
| 5936 | |
| 5937 | <p>You may choose between <code>=</code>, |
| 5938 | <code>()</code>, and <code>{}</code>; the following are |
| 5939 | all correct:</p> |
| 5940 | |
| 5941 | <pre>int x = 3; |
| 5942 | int x(3); |
| 5943 | int x{3}; |
| 5944 | string name = "Some Name"; |
| 5945 | string name("Some Name"); |
| 5946 | string name{"Some Name"}; |
| 5947 | </pre> |
| 5948 | |
| 5949 | <p>Be careful when using a braced initialization list <code>{...}</code> |
| 5950 | on a type with an <code>std::initializer_list</code> constructor. |
| 5951 | A nonempty <i>braced-init-list</i> prefers the |
| 5952 | <code>std::initializer_list</code> constructor whenever |
| 5953 | possible. Note that empty braces <code>{}</code> are special, and |
| 5954 | will call a default constructor if available. To force the |
| 5955 | non-<code>std::initializer_list</code> constructor, use parentheses |
| 5956 | instead of braces.</p> |
| 5957 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5958 | <pre>std::vector<int> v(100, 1); // A vector containing 100 items: All 1s. |
| 5959 | std::vector<int> v{100, 1}; // A vector containing 2 items: 100 and 1. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5960 | </pre> |
| 5961 | |
| 5962 | <p>Also, the brace form prevents narrowing of integral |
| 5963 | types. This can prevent some types of programming |
| 5964 | errors.</p> |
| 5965 | |
| 5966 | <pre>int pi(3.14); // OK -- pi == 3. |
| 5967 | int pi{3.14}; // Compile error: narrowing conversion. |
| 5968 | </pre> |
| 5969 | |
| 5970 | </div> |
| 5971 | |
| 5972 | <h3 id="Preprocessor_Directives">Preprocessor Directives</h3> |
| 5973 | |
| 5974 | <div class="summary"> |
| 5975 | <p>The hash mark that starts a preprocessor directive should |
| 5976 | always be at the beginning of the line.</p> |
| 5977 | </div> |
| 5978 | |
| 5979 | <div class="stylebody"> |
| 5980 | |
| 5981 | <p>Even when preprocessor directives are within the body |
| 5982 | of indented code, the directives should start at the |
| 5983 | beginning of the line.</p> |
| 5984 | |
| 5985 | <pre>// Good - directives at beginning of line |
| 5986 | if (lopsided_score) { |
| 5987 | #if DISASTER_PENDING // Correct -- Starts at beginning of line |
| 5988 | DropEverything(); |
| 5989 | # if NOTIFY // OK but not required -- Spaces after # |
| 5990 | NotifyClient(); |
| 5991 | # endif |
| 5992 | #endif |
| 5993 | BackToNormal(); |
| 5994 | } |
| 5995 | </pre> |
| 5996 | |
| 5997 | <pre class="badcode">// Bad - indented directives |
| 5998 | if (lopsided_score) { |
| 5999 | #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line |
| 6000 | DropEverything(); |
| 6001 | #endif // Wrong! Do not indent "#endif" |
| 6002 | BackToNormal(); |
| 6003 | } |
| 6004 | </pre> |
| 6005 | |
| 6006 | </div> |
| 6007 | |
| 6008 | <h3 id="Class_Format">Class Format</h3> |
| 6009 | |
| 6010 | <div class="summary"> |
| 6011 | <p>Sections in <code>public</code>, <code>protected</code> and |
| 6012 | <code>private</code> order, each indented one space.</p> |
| 6013 | </div> |
| 6014 | |
| 6015 | <div class="stylebody"> |
| 6016 | |
| 6017 | <p>The basic format for a class definition (lacking the |
| 6018 | comments, see <a href="#Class_Comments">Class |
| 6019 | Comments</a> for a discussion of what comments are |
| 6020 | needed) is:</p> |
| 6021 | |
| 6022 | <pre>class MyClass : public OtherClass { |
| 6023 | public: // Note the 1 space indent! |
| 6024 | MyClass(); // Regular 2 space indent. |
| 6025 | explicit MyClass(int var); |
| 6026 | ~MyClass() {} |
| 6027 | |
| 6028 | void SomeFunction(); |
| 6029 | void SomeFunctionThatDoesNothing() { |
| 6030 | } |
| 6031 | |
| 6032 | void set_some_var(int var) { some_var_ = var; } |
| 6033 | int some_var() const { return some_var_; } |
| 6034 | |
| 6035 | private: |
| 6036 | bool SomeInternalFunction(); |
| 6037 | |
| 6038 | int some_var_; |
| 6039 | int some_other_var_; |
| 6040 | }; |
| 6041 | </pre> |
| 6042 | |
| 6043 | <p>Things to note:</p> |
| 6044 | |
| 6045 | <ul> |
| 6046 | <li>Any base class name should be on the same line as |
| 6047 | the subclass name, subject to the 80-column limit.</li> |
| 6048 | |
| 6049 | <li>The <code>public:</code>, <code>protected:</code>, |
| 6050 | and <code>private:</code> keywords should be indented |
| 6051 | one space.</li> |
| 6052 | |
| 6053 | <li>Except for the first instance, these keywords |
| 6054 | should be preceded by a blank line. This rule is |
| 6055 | optional in small classes.</li> |
| 6056 | |
| 6057 | <li>Do not leave a blank line after these |
| 6058 | keywords.</li> |
| 6059 | |
| 6060 | <li>The <code>public</code> section should be first, |
| 6061 | followed by the <code>protected</code> and finally the |
| 6062 | <code>private</code> section.</li> |
| 6063 | |
| 6064 | <li>See <a href="#Declaration_Order">Declaration |
| 6065 | Order</a> for rules on ordering declarations within |
| 6066 | each of these sections.</li> |
| 6067 | </ul> |
| 6068 | |
| 6069 | </div> |
| 6070 | |
| 6071 | <h3 id="Constructor_Initializer_Lists">Constructor Initializer Lists</h3> |
| 6072 | |
| 6073 | <div class="summary"> |
| 6074 | <p>Constructor initializer lists can be all on one line or |
| 6075 | with subsequent lines indented four spaces.</p> |
| 6076 | </div> |
| 6077 | |
| 6078 | <div class="stylebody"> |
| 6079 | |
| 6080 | <p>The acceptable formats for initializer lists are:</p> |
| 6081 | |
| 6082 | <pre>// When everything fits on one line: |
| 6083 | MyClass::MyClass(int var) : some_var_(var) { |
| 6084 | DoSomething(); |
| 6085 | } |
| 6086 | |
| 6087 | // If the signature and initializer list are not all on one line, |
| 6088 | // you must wrap before the colon and indent 4 spaces: |
| 6089 | MyClass::MyClass(int var) |
| 6090 | : some_var_(var), some_other_var_(var + 1) { |
| 6091 | DoSomething(); |
| 6092 | } |
| 6093 | |
| 6094 | // When the list spans multiple lines, put each member on its own line |
| 6095 | // and align them: |
| 6096 | MyClass::MyClass(int var) |
| 6097 | : some_var_(var), // 4 space indent |
| 6098 | some_other_var_(var + 1) { // lined up |
| 6099 | DoSomething(); |
| 6100 | } |
| 6101 | |
| 6102 | // As with any other code block, the close curly can be on the same |
| 6103 | // line as the open curly, if it fits. |
| 6104 | MyClass::MyClass(int var) |
| 6105 | : some_var_(var) {} |
| 6106 | </pre> |
| 6107 | |
| 6108 | </div> |
| 6109 | |
| 6110 | <h3 id="Namespace_Formatting">Namespace Formatting</h3> |
| 6111 | |
| 6112 | <div class="summary"> |
| 6113 | <p>The contents of namespaces are not indented.</p> |
| 6114 | </div> |
| 6115 | |
| 6116 | <div class="stylebody"> |
| 6117 | |
| 6118 | <p><a href="#Namespaces">Namespaces</a> do not add an |
| 6119 | extra level of indentation. For example, use:</p> |
| 6120 | |
| 6121 | <pre>namespace { |
| 6122 | |
| 6123 | void foo() { // Correct. No extra indentation within namespace. |
| 6124 | ... |
| 6125 | } |
| 6126 | |
| 6127 | } // namespace |
| 6128 | </pre> |
| 6129 | |
| 6130 | <p>Do not indent within a namespace:</p> |
| 6131 | |
| 6132 | <pre class="badcode">namespace { |
| 6133 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 6134 | // Wrong! Indented when it should not be. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 6135 | void foo() { |
| 6136 | ... |
| 6137 | } |
| 6138 | |
| 6139 | } // namespace |
| 6140 | </pre> |
| 6141 | |
| 6142 | <p>When declaring nested namespaces, put each namespace |
| 6143 | on its own line.</p> |
| 6144 | |
| 6145 | <pre>namespace foo { |
| 6146 | namespace bar { |
| 6147 | </pre> |
| 6148 | |
| 6149 | </div> |
| 6150 | |
| 6151 | <h3 id="Horizontal_Whitespace">Horizontal Whitespace</h3> |
| 6152 | |
| 6153 | <div class="summary"> |
| 6154 | <p>Use of horizontal whitespace depends on location. Never put |
| 6155 | trailing whitespace at the end of a line.</p> |
| 6156 | </div> |
| 6157 | |
| 6158 | <div class="stylebody"> |
| 6159 | |
| 6160 | <h4 class="stylepoint_subsection">General</h4> |
| 6161 | |
| 6162 | <pre>void f(bool b) { // Open braces should always have a space before them. |
| 6163 | ... |
| 6164 | int i = 0; // Semicolons usually have no space before them. |
| 6165 | // Spaces inside braces for braced-init-list are optional. If you use them, |
| 6166 | // put them on both sides! |
| 6167 | int x[] = { 0 }; |
| 6168 | int x[] = {0}; |
| 6169 | |
| 6170 | // Spaces around the colon in inheritance and initializer lists. |
| 6171 | class Foo : public Bar { |
| 6172 | public: |
| 6173 | // For inline function implementations, put spaces between the braces |
| 6174 | // and the implementation itself. |
| 6175 | Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces. |
| 6176 | void Reset() { baz_ = 0; } // Spaces separating braces from implementation. |
| 6177 | ... |
| 6178 | </pre> |
| 6179 | |
| 6180 | <p>Adding trailing whitespace can cause extra work for |
| 6181 | others editing the same file, when they merge, as can |
| 6182 | removing existing trailing whitespace. So: Don't |
| 6183 | introduce trailing whitespace. Remove it if you're |
| 6184 | already changing that line, or do it in a separate |
| 6185 | clean-up |
| 6186 | operation (preferably when no-one |
| 6187 | else is working on the file).</p> |
| 6188 | |
| 6189 | <h4 class="stylepoint_subsection">Loops and Conditionals</h4> |
| 6190 | |
| 6191 | <pre>if (b) { // Space after the keyword in conditions and loops. |
| 6192 | } else { // Spaces around else. |
| 6193 | } |
| 6194 | while (test) {} // There is usually no space inside parentheses. |
| 6195 | switch (i) { |
| 6196 | for (int i = 0; i < 5; ++i) { |
| 6197 | // Loops and conditions may have spaces inside parentheses, but this |
| 6198 | // is rare. Be consistent. |
| 6199 | switch ( i ) { |
| 6200 | if ( test ) { |
| 6201 | for ( int i = 0; i < 5; ++i ) { |
| 6202 | // For loops always have a space after the semicolon. They may have a space |
| 6203 | // before the semicolon, but this is rare. |
| 6204 | for ( ; i < 5 ; ++i) { |
| 6205 | ... |
| 6206 | |
| 6207 | // Range-based for loops always have a space before and after the colon. |
| 6208 | for (auto x : counts) { |
| 6209 | ... |
| 6210 | } |
| 6211 | switch (i) { |
| 6212 | case 1: // No space before colon in a switch case. |
| 6213 | ... |
| 6214 | case 2: break; // Use a space after a colon if there's code after it. |
| 6215 | </pre> |
| 6216 | |
| 6217 | <h4 class="stylepoint_subsection">Operators</h4> |
| 6218 | |
| 6219 | <pre>// Assignment operators always have spaces around them. |
| 6220 | x = 0; |
| 6221 | |
| 6222 | // Other binary operators usually have spaces around them, but it's |
| 6223 | // OK to remove spaces around factors. Parentheses should have no |
| 6224 | // internal padding. |
| 6225 | v = w * x + y / z; |
| 6226 | v = w*x + y/z; |
| 6227 | v = w * (x + z); |
| 6228 | |
| 6229 | // No spaces separating unary operators and their arguments. |
| 6230 | x = -5; |
| 6231 | ++x; |
| 6232 | if (x && !y) |
| 6233 | ... |
| 6234 | </pre> |
| 6235 | |
| 6236 | <h4 class="stylepoint_subsection">Templates and Casts</h4> |
| 6237 | |
| 6238 | <pre>// No spaces inside the angle brackets (< and >), before |
| 6239 | // <, or between >( in a cast |
| 6240 | std::vector<string> x; |
| 6241 | y = static_cast<char*>(x); |
| 6242 | |
| 6243 | // Spaces between type and pointer are OK, but be consistent. |
| 6244 | std::vector<char *> x; |
| 6245 | </pre> |
| 6246 | |
| 6247 | </div> |
| 6248 | |
| 6249 | <h3 id="Vertical_Whitespace">Vertical Whitespace</h3> |
| 6250 | |
| 6251 | <div class="summary"> |
| 6252 | <p>Minimize use of vertical whitespace.</p> |
| 6253 | </div> |
| 6254 | |
| 6255 | <div class="stylebody"> |
| 6256 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 6257 | <p>This is more a principle than a rule: don't use blank lines when |
| 6258 | you don't have to. In particular, don't put more than one or two blank |
| 6259 | lines between functions, resist starting functions with a blank line, |
| 6260 | don't end functions with a blank line, and be sparing with your use of |
| 6261 | blank lines. A blank line within a block of code serves like a |
| 6262 | paragraph break in prose: visually separating two thoughts.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 6263 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 6264 | <p>The basic principle is: The more code that fits on one screen, the |
| 6265 | easier it is to follow and understand the control flow of the |
| 6266 | program. Use whitespace purposefully to provide separation in that |
| 6267 | flow.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 6268 | |
| 6269 | <p>Some rules of thumb to help when blank lines may be |
| 6270 | useful:</p> |
| 6271 | |
| 6272 | <ul> |
| 6273 | <li>Blank lines at the beginning or end of a function |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 6274 | do not help readability.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 6275 | |
| 6276 | <li>Blank lines inside a chain of if-else blocks may |
| 6277 | well help readability.</li> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 6278 | |
| 6279 | <li>A blank line before a comment line usually helps |
| 6280 | readability — the introduction of a new comment suggests |
| 6281 | the start of a new thought, and the blank line makes it clear |
| 6282 | that the comment goes with the following thing instead of the |
| 6283 | preceding.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 6284 | </ul> |
| 6285 | |
| 6286 | </div> |
| 6287 | |
| 6288 | <h2 id="Exceptions_to_the_Rules">Exceptions to the Rules</h2> |
| 6289 | |
| 6290 | <p>The coding conventions described above are mandatory. |
| 6291 | However, like all good rules, these sometimes have exceptions, |
| 6292 | which we discuss here.</p> |
| 6293 | |
| 6294 | |
| 6295 | |
| 6296 | <div> |
| 6297 | <h3 id="Existing_Non-conformant_Code">Existing Non-conformant Code</h3> |
| 6298 | |
| 6299 | <div class="summary"> |
| 6300 | <p>You may diverge from the rules when dealing with code that |
| 6301 | does not conform to this style guide.</p> |
| 6302 | </div> |
| 6303 | |
| 6304 | <div class="stylebody"> |
| 6305 | |
| 6306 | <p>If you find yourself modifying code that was written |
| 6307 | to specifications other than those presented by this |
| 6308 | guide, you may have to diverge from these rules in order |
| 6309 | to stay consistent with the local conventions in that |
| 6310 | code. If you are in doubt about how to do this, ask the |
| 6311 | original author or the person currently responsible for |
| 6312 | the code. Remember that <em>consistency</em> includes |
| 6313 | local consistency, too.</p> |
| 6314 | |
| 6315 | </div> |
| 6316 | </div> |
| 6317 | |
| 6318 | |
| 6319 | |
| 6320 | <h3 id="Windows_Code">Windows Code</h3> |
| 6321 | |
| 6322 | <div class="summary"> |
| 6323 | <p> Windows |
| 6324 | programmers have developed their own set of coding |
| 6325 | conventions, mainly derived from the conventions in Windows |
| 6326 | headers and other Microsoft code. We want to make it easy |
| 6327 | for anyone to understand your code, so we have a single set |
| 6328 | of guidelines for everyone writing C++ on any platform.</p> |
| 6329 | </div> |
| 6330 | |
| 6331 | <div class="stylebody"> |
| 6332 | <p>It is worth reiterating a few of the guidelines that |
| 6333 | you might forget if you are used to the prevalent Windows |
| 6334 | style:</p> |
| 6335 | |
| 6336 | <ul> |
| 6337 | <li>Do not use Hungarian notation (for example, naming |
| 6338 | an integer <code>iNum</code>). Use the Google naming |
| 6339 | conventions, including the <code>.cc</code> extension |
| 6340 | for source files.</li> |
| 6341 | |
| 6342 | <li>Windows defines many of its own synonyms for |
| 6343 | primitive types, such as <code>DWORD</code>, |
| 6344 | <code>HANDLE</code>, etc. It is perfectly acceptable, |
| 6345 | and encouraged, that you use these types when calling |
| 6346 | Windows API functions. Even so, keep as close as you |
| 6347 | can to the underlying C++ types. For example, use |
| 6348 | <code>const TCHAR *</code> instead of |
| 6349 | <code>LPCTSTR</code>.</li> |
| 6350 | |
| 6351 | <li>When compiling with Microsoft Visual C++, set the |
| 6352 | compiler to warning level 3 or higher, and treat all |
| 6353 | warnings as errors.</li> |
| 6354 | |
| 6355 | <li>Do not use <code>#pragma once</code>; instead use |
| 6356 | the standard Google include guards. The path in the |
| 6357 | include guards should be relative to the top of your |
| 6358 | project tree.</li> |
| 6359 | |
| 6360 | <li>In fact, do not use any nonstandard extensions, |
| 6361 | like <code>#pragma</code> and <code>__declspec</code>, |
| 6362 | unless you absolutely must. Using |
| 6363 | <code>__declspec(dllimport)</code> and |
| 6364 | <code>__declspec(dllexport)</code> is allowed; however, |
| 6365 | you must use them through macros such as |
| 6366 | <code>DLLIMPORT</code> and <code>DLLEXPORT</code>, so |
| 6367 | that someone can easily disable the extensions if they |
| 6368 | share the code.</li> |
| 6369 | </ul> |
| 6370 | |
| 6371 | <p>However, there are just a few rules that we |
| 6372 | occasionally need to break on Windows:</p> |
| 6373 | |
| 6374 | <ul> |
| 6375 | <li>Normally we <a href="#Multiple_Inheritance">forbid |
| 6376 | the use of multiple implementation inheritance</a>; |
| 6377 | however, it is required when using COM and some ATL/WTL |
| 6378 | classes. You may use multiple implementation |
| 6379 | inheritance to implement COM or ATL/WTL classes and |
| 6380 | interfaces.</li> |
| 6381 | |
| 6382 | <li>Although you should not use exceptions in your own |
| 6383 | code, they are used extensively in the ATL and some |
| 6384 | STLs, including the one that comes with Visual C++. |
| 6385 | When using the ATL, you should define |
| 6386 | <code>_ATL_NO_EXCEPTIONS</code> to disable exceptions. |
| 6387 | You should investigate whether you can also disable |
| 6388 | exceptions in your STL, but if not, it is OK to turn on |
| 6389 | exceptions in the compiler. (Note that this is only to |
| 6390 | get the STL to compile. You should still not write |
| 6391 | exception handling code yourself.)</li> |
| 6392 | |
| 6393 | <li>The usual way of working with precompiled headers |
| 6394 | is to include a header file at the top of each source |
| 6395 | file, typically with a name like <code>StdAfx.h</code> |
| 6396 | or <code>precompile.h</code>. To make your code easier |
| 6397 | to share with other projects, avoid including this file |
| 6398 | explicitly (except in <code>precompile.cc</code>), and |
| 6399 | use the <code>/FI</code> compiler option to include the |
| 6400 | file automatically.</li> |
| 6401 | |
| 6402 | <li>Resource headers, which are usually named |
| 6403 | <code>resource.h</code> and contain only macros, do not |
| 6404 | need to conform to these style guidelines.</li> |
| 6405 | </ul> |
| 6406 | |
| 6407 | </div> |
| 6408 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 6409 | <h2 id="Parting_Words">Parting Words</h2> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 6410 | |
| 6411 | <p>Use common sense and <em>BE CONSISTENT</em>.</p> |
| 6412 | |
| 6413 | <p>If you are editing code, take a few minutes to look at the |
| 6414 | code around you and determine its style. If they use spaces |
| 6415 | around their <code>if</code> clauses, you should, too. If their |
| 6416 | comments have little boxes of stars around them, make your |
| 6417 | comments have little boxes of stars around them too.</p> |
| 6418 | |
| 6419 | <p>The point of having style guidelines is to have a common |
| 6420 | vocabulary of coding so people can concentrate on what you are |
| 6421 | saying, rather than on how you are saying it. We present global |
| 6422 | style rules here so people know the vocabulary. But local style |
| 6423 | is also important. If code you add to a file looks drastically |
| 6424 | different from the existing code around it, the discontinuity |
| 6425 | throws readers out of their rhythm when they go to read it. Try |
| 6426 | to avoid this.</p> |
| 6427 | |
| 6428 | |
| 6429 | |
| 6430 | <p>OK, enough writing about writing code; the code itself is much |
| 6431 | more interesting. Have fun!</p> |
| 6432 | |
| 6433 | <hr> |
| 6434 | |
| 6435 | </div> |
| 6436 | </div> |
| 6437 | </body> |
| 6438 | </html> |