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 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 16 | <h2 id="Background" class="ignoreLink">Background</h2> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 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 |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 25 | describing in detail the dos and don'ts of writing C++ code |
| 26 | . These rules exist to |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 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 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 42 | <p>Note that this guide is not a C++ tutorial: we assume that |
| 43 | the reader is familiar with the language. </p> |
| 44 | |
| 45 | <h3 id="Goals">Goals of the Style Guide</h3> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 46 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 47 | <p>Why do we have this document?</p> |
| 48 | |
| 49 | <p>There are a few core goals that we believe this guide should |
| 50 | serve. These are the fundamental <b>why</b>s that |
| 51 | underlie all of the individual rules. By bringing these ideas to |
| 52 | the fore, we hope to ground discussions and make it clearer to our |
| 53 | broader community why the rules are in place and why particular |
| 54 | decisions have been made. If you understand what goals each rule is |
| 55 | serving, it should be clearer to everyone when a rule may be waived |
| 56 | (some can be), and what sort of argument or alternative would be |
| 57 | necessary to change a rule in the guide.</p> |
| 58 | |
| 59 | <p>The goals of the style guide as we currently see them are as follows:</p> |
| 60 | <dl> |
| 61 | <dt>Style rules should pull their weight</dt> |
| 62 | <dd>The benefit of a style rule |
| 63 | must be large enough to justify asking all of our engineers to |
| 64 | remember it. The benefit is measured relative to the codebase we would |
| 65 | get without the rule, so a rule against a very harmful practice may |
| 66 | still have a small benefit if people are unlikely to do it |
| 67 | anyway. This principle mostly explains the rules we don’t have, rather |
| 68 | than the rules we do: for example, <code>goto</code> contravenes many |
| 69 | of the following principles, but is already vanishingly rare, so the Style |
| 70 | Guide doesn’t discuss it.</dd> |
| 71 | |
| 72 | <dt>Optimize for the reader, not the writer</dt> |
| 73 | <dd>Our codebase (and most individual components submitted to it) is |
| 74 | expected to continue for quite some time. As a result, more time will |
| 75 | be spent reading most of our code than writing it. We explicitly |
| 76 | choose to optimize for the experience of our average software engineer |
| 77 | reading, maintaining, and debugging code in our codebase rather than |
| 78 | ease when writing said code. "Leave a trace for the reader" is a |
| 79 | particularly common sub-point of this principle: When something |
| 80 | surprising or unusual is happening in a snippet of code (for example, |
| 81 | transfer of pointer ownership), leaving textual hints for the reader |
| 82 | at the point of use is valuable (<code>std::unique_ptr</code> |
| 83 | demonstrates the ownership transfer unambiguously at the call |
| 84 | site). </dd> |
| 85 | |
| 86 | <dt>Be consistent with existing code</dt> |
| 87 | <dd>Using one style consistently through our codebase lets us focus on |
| 88 | other (more important) issues. Consistency also allows for |
| 89 | automation: tools that format your code or adjust |
| 90 | your <code>#include</code>s only work properly when your code is |
| 91 | consistent with the expectations of the tooling. In many cases, rules |
| 92 | that are attributed to "Be Consistent" boil down to "Just pick one and |
| 93 | stop worrying about it"; the potential value of allowing flexibility |
| 94 | on these points is outweighed by the cost of having people argue over |
| 95 | them. </dd> |
| 96 | |
| 97 | <dt>Be consistent with the broader C++ community when appropriate</dt> |
| 98 | <dd>Consistency with the way other organizations use C++ has value for |
| 99 | the same reasons as consistency within our code base. If a feature in |
| 100 | the C++ standard solves a problem, or if some idiom is widely known |
| 101 | and accepted, that's an argument for using it. However, sometimes |
| 102 | standard features and idioms are flawed, or were just designed without |
| 103 | our codebase's needs in mind. In those cases (as described below) it's |
| 104 | appropriate to constrain or ban standard features. In some cases we |
| 105 | prefer a homegrown or third-party library over a library defined in |
| 106 | the C++ Standard, either out of perceived superiority or insufficient |
| 107 | value to transition the codebase to the standard interface.</dd> |
| 108 | |
| 109 | <dt>Avoid surprising or dangerous constructs</dt> |
| 110 | <dd>C++ has features that are more surprising or dangerous than one |
| 111 | might think at a glance. Some style guide restrictions are in place to |
| 112 | prevent falling into these pitfalls. There is a high bar for style |
| 113 | guide waivers on such restrictions, because waiving such rules often |
| 114 | directly risks compromising program correctness. |
| 115 | </dd> |
| 116 | |
| 117 | <dt>Avoid constructs that our average C++ programmer would find tricky |
| 118 | or hard to maintain</dt> |
| 119 | <dd>C++ has features that may not be generally appropriate because of |
| 120 | the complexity they introduce to the code. In widely used |
| 121 | code, it may be more acceptable to use |
| 122 | trickier language constructs, because any benefits of more complex |
| 123 | implementation are multiplied widely by usage, and the cost in understanding |
| 124 | the complexity does not need to be paid again when working with new |
| 125 | portions of the codebase. When in doubt, waivers to rules of this type |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 126 | can be sought by asking |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 127 | your project leads. This is specifically |
| 128 | important for our codebase because code ownership and team membership |
| 129 | changes over time: even if everyone that works with some piece of code |
| 130 | currently understands it, such understanding is not guaranteed to hold a |
| 131 | few years from now.</dd> |
| 132 | |
| 133 | <dt>Be mindful of our scale</dt> |
| 134 | <dd>With a codebase of 100+ million lines and thousands of engineers, |
| 135 | some mistakes and simplifications for one engineer can become costly |
| 136 | for many. For instance it's particularly important to |
| 137 | avoid polluting the global namespace: name collisions across a |
| 138 | codebase of hundreds of millions of lines are difficult to work with |
| 139 | and hard to avoid if everyone puts things into the global |
| 140 | namespace.</dd> |
| 141 | |
| 142 | <dt>Concede to optimization when necessary</dt> |
| 143 | <dd>Performance optimizations can sometimes be necessary and |
| 144 | appropriate, even when they conflict with the other principles of this |
| 145 | document.</dd> |
| 146 | </dl> |
| 147 | |
| 148 | <p>The intent of this document is to provide maximal guidance with |
| 149 | reasonable restriction. As always, common sense and good taste should |
| 150 | prevail. By this we specifically refer to the established conventions |
| 151 | of the entire Google C++ community, not just your personal preferences |
| 152 | or those of your team. Be skeptical about and reluctant to use |
| 153 | clever or unusual constructs: the absence of a prohibition is not the |
| 154 | same as a license to proceed. Use your judgment, and if you are |
| 155 | unsure, please don't hesitate to ask your project leads to get additional |
| 156 | input.</p> |
| 157 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 158 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 159 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 160 | <h2 id="C++_Version">C++ Version</h2> |
| 161 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 162 | <p>Currently, code should target C++17, i.e., should not use C++2x |
| 163 | features. The C++ version targeted by this guide will advance |
| 164 | (aggressively) over time.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 165 | |
| 166 | |
| 167 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 168 | <p>Do not use |
| 169 | <a href="#Nonstandard_Extensions">non-standard extensions</a>.</p> |
| 170 | |
| 171 | <div>Consider portability to other environments |
| 172 | before using features from C++14 and C++17 in your project. |
| 173 | </div> |
| 174 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 175 | <h2 id="Header_Files">Header Files</h2> |
| 176 | |
| 177 | <p>In general, every <code>.cc</code> file should have an |
| 178 | associated <code>.h</code> file. There are some common |
| 179 | exceptions, such as unittests and |
| 180 | small <code>.cc</code> files containing just a |
| 181 | <code>main()</code> function.</p> |
| 182 | |
| 183 | <p>Correct use of header files can make a huge difference to |
| 184 | the readability, size and performance of your code.</p> |
| 185 | |
| 186 | <p>The following rules will guide you through the various |
| 187 | pitfalls of using header files.</p> |
| 188 | |
| 189 | <a id="The_-inl.h_Files"></a> |
| 190 | <h3 id="Self_contained_Headers">Self-contained Headers</h3> |
| 191 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 192 | <p>Header files should be self-contained (compile on their own) and |
| 193 | end in <code>.h</code>. Non-header files that are meant for inclusion |
| 194 | should end in <code>.inc</code> and be used sparingly.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 195 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 196 | <p>All header files should be self-contained. Users and refactoring |
| 197 | tools should not have to adhere to special conditions to include the |
| 198 | header. Specifically, a header should |
| 199 | have <a href="#The__define_Guard">header guards</a> and include all |
| 200 | other headers it needs.</p> |
| 201 | |
| 202 | <p>Prefer placing the definitions for template and inline functions in |
| 203 | the same file as their declarations. The definitions of these |
| 204 | constructs must be included into every <code>.cc</code> file that uses |
| 205 | them, or the program may fail to link in some build configurations. If |
| 206 | declarations and definitions are in different files, including the |
| 207 | former should transitively include the latter. Do not move these |
| 208 | definitions to separately included header files (<code>-inl.h</code>); |
| 209 | this practice was common in the past, but is no longer allowed.</p> |
| 210 | |
| 211 | <p>As an exception, a template that is explicitly instantiated for |
| 212 | all relevant sets of template arguments, or that is a private |
| 213 | implementation detail of a class, is allowed to be defined in the one |
| 214 | and only <code>.cc</code> file that instantiates the template.</p> |
| 215 | |
| 216 | <p>There are rare cases where a file designed to be included is not |
| 217 | self-contained. These are typically intended to be included at unusual |
| 218 | locations, such as the middle of another file. They might not |
| 219 | use <a href="#The__define_Guard">header guards</a>, and might not include |
| 220 | their prerequisites. Name such files with the <code>.inc</code> |
| 221 | extension. Use sparingly, and prefer self-contained headers when |
| 222 | possible.</p> |
| 223 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 224 | <h3 id="The__define_Guard">The #define Guard</h3> |
| 225 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 226 | <p>All header files should have <code>#define</code> guards to |
| 227 | prevent multiple inclusion. The format of the symbol name |
| 228 | should be |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 229 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 230 | <code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 231 | |
| 232 | |
| 233 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 234 | <div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 235 | <p>To guarantee uniqueness, they should |
| 236 | be based on the full path in a project's source tree. For |
| 237 | example, the file <code>foo/src/bar/baz.h</code> in |
| 238 | project <code>foo</code> should have the following |
| 239 | guard:</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 240 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 241 | |
| 242 | <pre>#ifndef FOO_BAR_BAZ_H_ |
| 243 | #define FOO_BAR_BAZ_H_ |
| 244 | |
| 245 | ... |
| 246 | |
| 247 | #endif // FOO_BAR_BAZ_H_ |
| 248 | </pre> |
| 249 | |
| 250 | |
| 251 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 252 | <h3 id="Forward_Declarations">Forward Declarations</h3> |
| 253 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 254 | <p>Avoid using forward declarations where possible. |
| 255 | Instead, <code>#include</code> the headers you need.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 256 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 257 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 258 | <p>A "forward declaration" is a declaration of a class, |
| 259 | function, or template without an associated definition.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 260 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 261 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 262 | <ul> |
| 263 | <li>Forward declarations can save compile time, as |
| 264 | <code>#include</code>s force the compiler to open |
| 265 | more files and process more input.</li> |
| 266 | |
| 267 | <li>Forward declarations can save on unnecessary |
| 268 | recompilation. <code>#include</code>s can force |
| 269 | your code to be recompiled more often, due to unrelated |
| 270 | changes in the header.</li> |
| 271 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 272 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 273 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 274 | <ul> |
| 275 | <li>Forward declarations can hide a dependency, allowing |
| 276 | user code to skip necessary recompilation when headers |
| 277 | change.</li> |
| 278 | |
| 279 | <li>A forward declaration may be broken by subsequent |
| 280 | changes to the library. Forward declarations of functions |
| 281 | and templates can prevent the header owners from making |
| 282 | otherwise-compatible changes to their APIs, such as |
| 283 | widening a parameter type, adding a template parameter |
| 284 | with a default value, or migrating to a new namespace.</li> |
| 285 | |
| 286 | <li>Forward declaring symbols from namespace |
| 287 | <code>std::</code> yields undefined behavior.</li> |
| 288 | |
| 289 | <li>It can be difficult to determine whether a forward |
| 290 | declaration or a full <code>#include</code> is needed. |
| 291 | Replacing an <code>#include</code> with a forward |
| 292 | declaration can silently change the meaning of |
| 293 | code: |
| 294 | <pre> // b.h: |
| 295 | struct B {}; |
| 296 | struct D : B {}; |
| 297 | |
| 298 | // good_user.cc: |
| 299 | #include "b.h" |
| 300 | void f(B*); |
| 301 | void f(void*); |
| 302 | void test(D* x) { f(x); } // calls f(B*) |
| 303 | </pre> |
| 304 | If the <code>#include</code> was replaced with forward |
| 305 | decls for <code>B</code> and <code>D</code>, |
| 306 | <code>test()</code> would call <code>f(void*)</code>. |
| 307 | </li> |
| 308 | |
| 309 | <li>Forward declaring multiple symbols from a header |
| 310 | can be more verbose than simply |
| 311 | <code>#include</code>ing the header.</li> |
| 312 | |
| 313 | <li>Structuring code to enable forward declarations |
| 314 | (e.g. using pointer members instead of object members) |
| 315 | can make the code slower and more complex.</li> |
| 316 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 317 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 318 | </ul> |
| 319 | |
| 320 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 321 | <ul> |
| 322 | <li>Try to avoid forward declarations of entities |
| 323 | defined in another project.</li> |
| 324 | |
| 325 | <li>When using a function declared in a header file, |
| 326 | always <code>#include</code> that header.</li> |
| 327 | |
| 328 | <li>When using a class template, prefer to |
| 329 | <code>#include</code> its header file.</li> |
| 330 | </ul> |
| 331 | |
| 332 | <p>Please see <a href="#Names_and_Order_of_Includes">Names and Order |
| 333 | of Includes</a> for rules about when to #include a header.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 334 | |
| 335 | <h3 id="Inline_Functions">Inline Functions</h3> |
| 336 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 337 | <p>Define functions inline only when they are small, say, 10 |
| 338 | lines or fewer.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 339 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 340 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 341 | <p>You can declare functions in a way that allows the compiler to expand |
| 342 | them inline rather than calling them through the usual |
| 343 | function call mechanism.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 344 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 345 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 346 | <p>Inlining a function can generate more efficient object |
| 347 | code, as long as the inlined function is small. Feel free |
| 348 | to inline accessors and mutators, and other short, |
| 349 | performance-critical functions.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 350 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 351 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 352 | <p>Overuse of inlining can actually make programs slower. |
| 353 | Depending on a function's size, inlining it can cause the |
| 354 | code size to increase or decrease. Inlining a very small |
| 355 | accessor function will usually decrease code size while |
| 356 | inlining a very large function can dramatically increase |
| 357 | code size. On modern processors smaller code usually runs |
| 358 | faster due to better use of the instruction cache.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 359 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 360 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 361 | <p>A decent rule of thumb is to not inline a function if |
| 362 | it is more than 10 lines long. Beware of destructors, |
| 363 | which are often longer than they appear because of |
| 364 | implicit member- and base-destructor calls!</p> |
| 365 | |
| 366 | <p>Another useful rule of thumb: it's typically not cost |
| 367 | effective to inline functions with loops or switch |
| 368 | statements (unless, in the common case, the loop or |
| 369 | switch statement is never executed).</p> |
| 370 | |
| 371 | <p>It is important to know that functions are not always |
| 372 | inlined even if they are declared as such; for example, |
| 373 | virtual and recursive functions are not normally inlined. |
| 374 | Usually recursive functions should not be inline. The |
| 375 | main reason for making a virtual function inline is to |
| 376 | place its definition in the class, either for convenience |
| 377 | or to document its behavior, e.g., for accessors and |
| 378 | mutators.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 379 | |
| 380 | <h3 id="Names_and_Order_of_Includes">Names and Order of Includes</h3> |
| 381 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 382 | <p>Include headers in the following order: Related header, C system headers, |
| 383 | C++ standard library headers, |
| 384 | other libraries' headers, your project's |
| 385 | headers.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 386 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 387 | <p> |
| 388 | All of a project's header files should be |
| 389 | listed as descendants of the project's source |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 390 | directory without use of UNIX directory aliases |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 391 | <code>.</code> (the current directory) or <code>..</code> |
| 392 | (the parent directory). For example, |
| 393 | |
| 394 | <code>google-awesome-project/src/base/logging.h</code> |
| 395 | should be included as:</p> |
| 396 | |
| 397 | <pre>#include "base/logging.h" |
| 398 | </pre> |
| 399 | |
| 400 | <p>In <code><var>dir/foo</var>.cc</code> or |
| 401 | <code><var>dir/foo_test</var>.cc</code>, whose main |
| 402 | purpose is to implement or test the stuff in |
| 403 | <code><var>dir2/foo2</var>.h</code>, order your includes |
| 404 | as follows:</p> |
| 405 | |
| 406 | <ol> |
| 407 | <li><code><var>dir2/foo2</var>.h</code>.</li> |
| 408 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 409 | <li>A blank line</li> |
| 410 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 411 | <li>C system headers (more precisely: headers in angle brackets with the |
| 412 | <code>.h</code> extension), e.g. <code><unistd.h></code>, |
| 413 | <code><stdlib.h></code>.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 414 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 415 | <li>A blank line</li> |
| 416 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 417 | <li>C++ standard library headers (without file extension), e.g. |
| 418 | <code><algorithm></code>, <code><cstddef></code>.</li> |
| 419 | |
| 420 | <li>A blank line</li> |
| 421 | |
| 422 | <div> |
| 423 | <li>Other libraries' <code>.h</code> files.</li> |
| 424 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 425 | |
| 426 | <li> |
| 427 | Your project's <code>.h</code> |
| 428 | files.</li> |
| 429 | </ol> |
| 430 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 431 | <p>Separate each non-empty group with one blank line.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 432 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 433 | <p>With the preferred ordering, if the related header |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 434 | <code><var>dir2/foo2</var>.h</code> omits any necessary |
| 435 | includes, the build of <code><var>dir/foo</var>.cc</code> |
| 436 | or <code><var>dir/foo</var>_test.cc</code> will break. |
| 437 | Thus, this rule ensures that build breaks show up first |
| 438 | for the people working on these files, not for innocent |
| 439 | people in other packages.</p> |
| 440 | |
| 441 | <p><code><var>dir/foo</var>.cc</code> and |
| 442 | <code><var>dir2/foo2</var>.h</code> are usually in the same |
| 443 | directory (e.g. <code>base/basictypes_test.cc</code> and |
| 444 | <code>base/basictypes.h</code>), but may sometimes be in different |
| 445 | directories too.</p> |
| 446 | |
| 447 | |
| 448 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 449 | <p>Note that the C headers such as <code>stddef.h</code> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 450 | are essentially interchangeable with their C++ counterparts |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 451 | (<code>cstddef</code>). |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 452 | Either style is acceptable, but prefer consistency with existing code.</p> |
| 453 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 454 | <p>Within each section the includes should be ordered |
| 455 | alphabetically. Note that older code might not conform to |
| 456 | this rule and should be fixed when convenient.</p> |
| 457 | |
| 458 | <p>You should include all the headers that define the symbols you rely |
| 459 | upon, except in the unusual case of <a href="#Forward_Declarations">forward |
| 460 | declaration</a>. If you rely on symbols from <code>bar.h</code>, |
| 461 | don't count on the fact that you included <code>foo.h</code> which |
| 462 | (currently) includes <code>bar.h</code>: include <code>bar.h</code> |
| 463 | yourself, unless <code>foo.h</code> explicitly demonstrates its intent |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 464 | to provide you the symbols of <code>bar.h</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 465 | |
| 466 | <p>For example, the includes in |
| 467 | |
| 468 | <code>google-awesome-project/src/foo/internal/fooserver.cc</code> |
| 469 | might look like this:</p> |
| 470 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 471 | <pre>#include "foo/server/fooserver.h" |
| 472 | |
| 473 | #include <sys/types.h> |
| 474 | #include <unistd.h> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 475 | |
| 476 | #include <string> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 477 | #include <vector> |
| 478 | |
| 479 | #include "base/basictypes.h" |
| 480 | #include "base/commandlineflags.h" |
| 481 | #include "foo/server/bar.h" |
| 482 | </pre> |
| 483 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 484 | <p><b>Exception:</b></p> |
| 485 | |
| 486 | <p>Sometimes, system-specific code needs |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 487 | conditional includes. Such code can put conditional |
| 488 | includes after other includes. Of course, keep your |
| 489 | system-specific code small and localized. Example:</p> |
| 490 | |
| 491 | <pre>#include "foo/public/fooserver.h" |
| 492 | |
| 493 | #include "base/port.h" // For LANG_CXX11. |
| 494 | |
| 495 | #ifdef LANG_CXX11 |
| 496 | #include <initializer_list> |
| 497 | #endif // LANG_CXX11 |
| 498 | </pre> |
| 499 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 500 | <h2 id="Scoping">Scoping</h2> |
| 501 | |
| 502 | <h3 id="Namespaces">Namespaces</h3> |
| 503 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 504 | <p>With few exceptions, place code in a namespace. Namespaces |
| 505 | should have unique names based on the project name, and possibly |
| 506 | its path. Do not use <i>using-directives</i> (e.g. |
| 507 | <code>using namespace foo</code>). Do not use |
| 508 | inline namespaces. For unnamed namespaces, see |
| 509 | <a href="#Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and |
| 510 | Static Variables</a>. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 511 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 512 | </p><p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 513 | <p>Namespaces subdivide the global scope |
| 514 | into distinct, named scopes, and so are useful for preventing |
| 515 | name collisions in the global scope.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 516 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 517 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 518 | |
| 519 | <p>Namespaces provide a method for preventing name conflicts |
| 520 | in large programs while allowing most code to use reasonably |
| 521 | short names.</p> |
| 522 | |
| 523 | <p>For example, if two different projects have a class |
| 524 | <code>Foo</code> in the global scope, these symbols may |
| 525 | collide at compile time or at runtime. If each project |
| 526 | places their code in a namespace, <code>project1::Foo</code> |
| 527 | and <code>project2::Foo</code> are now distinct symbols that |
| 528 | do not collide, and code within each project's namespace |
| 529 | can continue to refer to <code>Foo</code> without the prefix.</p> |
| 530 | |
| 531 | <p>Inline namespaces automatically place their names in |
| 532 | the enclosing scope. Consider the following snippet, for |
| 533 | example:</p> |
| 534 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 535 | <pre class="neutralcode">namespace outer { |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 536 | inline namespace inner { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 537 | void foo(); |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 538 | } // namespace inner |
| 539 | } // namespace outer |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 540 | </pre> |
| 541 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 542 | <p>The expressions <code>outer::inner::foo()</code> and |
| 543 | <code>outer::foo()</code> are interchangeable. Inline |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 544 | namespaces are primarily intended for ABI compatibility |
| 545 | across versions.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 546 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 547 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 548 | |
| 549 | <p>Namespaces can be confusing, because they complicate |
| 550 | the mechanics of figuring out what definition a name refers |
| 551 | to.</p> |
| 552 | |
| 553 | <p>Inline namespaces, in particular, can be confusing |
| 554 | because names aren't actually restricted to the namespace |
| 555 | where they are declared. They are only useful as part of |
| 556 | some larger versioning policy.</p> |
| 557 | |
| 558 | <p>In some contexts, it's necessary to repeatedly refer to |
| 559 | symbols by their fully-qualified names. For deeply-nested |
| 560 | namespaces, this can add a lot of clutter.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 561 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 562 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 563 | |
| 564 | <p>Namespaces should be used as follows:</p> |
| 565 | |
| 566 | <ul> |
| 567 | <li>Follow the rules on <a href="#Namespace_Names">Namespace Names</a>. |
| 568 | </li><li>Terminate namespaces with comments as shown in the given examples. |
| 569 | </li><li> |
| 570 | |
| 571 | <p>Namespaces wrap the entire source file after |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 572 | includes, |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 573 | <a href="https://gflags.github.io/gflags/"> |
| 574 | gflags</a> definitions/declarations |
| 575 | and forward declarations of classes from other namespaces.</p> |
| 576 | |
| 577 | <pre>// In the .h file |
| 578 | namespace mynamespace { |
| 579 | |
| 580 | // All declarations are within the namespace scope. |
| 581 | // Notice the lack of indentation. |
| 582 | class MyClass { |
| 583 | public: |
| 584 | ... |
| 585 | void Foo(); |
| 586 | }; |
| 587 | |
| 588 | } // namespace mynamespace |
| 589 | </pre> |
| 590 | |
| 591 | <pre>// In the .cc file |
| 592 | namespace mynamespace { |
| 593 | |
| 594 | // Definition of functions is within scope of the namespace. |
| 595 | void MyClass::Foo() { |
| 596 | ... |
| 597 | } |
| 598 | |
| 599 | } // namespace mynamespace |
| 600 | </pre> |
| 601 | |
| 602 | <p>More complex <code>.cc</code> files might have additional details, |
| 603 | like flags or using-declarations.</p> |
| 604 | |
| 605 | <pre>#include "a.h" |
| 606 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 607 | ABSL_FLAG(bool, someflag, false, "dummy flag"); |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 608 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 609 | namespace mynamespace { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 610 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 611 | using ::foo::Bar; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 612 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 613 | ...code for mynamespace... // Code goes against the left margin. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 614 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 615 | } // namespace mynamespace |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 616 | </pre> |
| 617 | </li> |
| 618 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 619 | <li>To place generated protocol |
| 620 | message code in a namespace, use the |
| 621 | <code>package</code> specifier in the |
| 622 | <code>.proto</code> file. See |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 623 | |
| 624 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 625 | <a href="https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#package"> |
| 626 | Protocol Buffer Packages</a> |
| 627 | for details.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 628 | |
| 629 | <li>Do not declare anything in namespace |
| 630 | <code>std</code>, including forward declarations of |
| 631 | standard library classes. Declaring entities in |
| 632 | namespace <code>std</code> is undefined behavior, i.e., |
| 633 | not portable. To declare entities from the standard |
| 634 | library, include the appropriate header file.</li> |
| 635 | |
| 636 | <li><p>You may not use a <i>using-directive</i> |
| 637 | to make all names from a namespace available.</p> |
| 638 | |
| 639 | <pre class="badcode">// Forbidden -- This pollutes the namespace. |
| 640 | using namespace foo; |
| 641 | </pre> |
| 642 | </li> |
| 643 | |
| 644 | <li><p>Do not use <i>Namespace aliases</i> at namespace scope |
| 645 | in header files except in explicitly marked |
| 646 | internal-only namespaces, because anything imported into a namespace |
| 647 | in a header file becomes part of the public |
| 648 | API exported by that file.</p> |
| 649 | |
| 650 | <pre>// Shorten access to some commonly used names in .cc files. |
| 651 | namespace baz = ::foo::bar::baz; |
| 652 | </pre> |
| 653 | |
| 654 | <pre>// Shorten access to some commonly used names (in a .h file). |
| 655 | namespace librarian { |
| 656 | namespace impl { // Internal, not part of the API. |
| 657 | namespace sidetable = ::pipeline_diagnostics::sidetable; |
| 658 | } // namespace impl |
| 659 | |
| 660 | inline void my_inline_function() { |
| 661 | // namespace alias local to a function (or method). |
| 662 | namespace baz = ::foo::bar::baz; |
| 663 | ... |
| 664 | } |
| 665 | } // namespace librarian |
| 666 | </pre> |
| 667 | |
| 668 | </li><li>Do not use inline namespaces.</li> |
| 669 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 670 | |
| 671 | <h3 id="Unnamed_Namespaces_and_Static_Variables">Unnamed Namespaces and Static |
| 672 | Variables</h3> |
| 673 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 674 | <p>When definitions in a <code>.cc</code> file do not need to be |
| 675 | referenced outside that file, place them in an unnamed |
| 676 | namespace or declare them <code>static</code>. Do not use either |
| 677 | of these constructs in <code>.h</code> files. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 678 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 679 | </p><p class="definition"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 680 | <p>All declarations can be given internal linkage by placing them in unnamed |
| 681 | namespaces. Functions and variables can also be given internal linkage by |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 682 | declaring them <code>static</code>. This means that anything you're declaring |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 683 | can't be accessed from another file. If a different file declares something with |
| 684 | the same name, then the two entities are completely independent.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 685 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 686 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 687 | |
| 688 | <p>Use of internal linkage in <code>.cc</code> files is encouraged |
| 689 | for all code that does not need to be referenced elsewhere. |
| 690 | Do not use internal linkage in <code>.h</code> files.</p> |
| 691 | |
| 692 | <p>Format unnamed namespaces like named namespaces. In the |
| 693 | terminating comment, leave the namespace name empty:</p> |
| 694 | |
| 695 | <pre>namespace { |
| 696 | ... |
| 697 | } // namespace |
| 698 | </pre> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 699 | |
| 700 | <h3 id="Nonmember,_Static_Member,_and_Global_Functions">Nonmember, Static Member, and Global Functions</h3> |
| 701 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 702 | <p>Prefer placing nonmember functions in a namespace; use completely global |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 703 | functions rarely. Do not use a class simply to group static functions. Static |
| 704 | methods of a class should generally be closely related to instances of the |
| 705 | class or the class's static data.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 706 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 707 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 708 | <p class="pros"></p> |
| 709 | <p>Nonmember and static member functions can be useful in |
| 710 | some situations. Putting nonmember functions in a |
| 711 | namespace avoids polluting the global namespace.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 712 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 713 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 714 | <p>Nonmember and static member functions may make more sense |
| 715 | as members of a new class, especially if they access |
| 716 | external resources or have significant dependencies.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 717 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 718 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 719 | <p>Sometimes it is useful to define a |
| 720 | function not bound to a class instance. Such a function |
| 721 | can be either a static member or a nonmember function. |
| 722 | Nonmember functions should not depend on external |
| 723 | variables, and should nearly always exist in a namespace. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 724 | Do not create classes only to group static member functions; |
| 725 | this is no different than just giving the function names a |
| 726 | common prefix, and such grouping is usually unnecessary anyway.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 727 | |
| 728 | <p>If you define a nonmember function and it is only |
| 729 | needed in its <code>.cc</code> file, use |
| 730 | <a href="#Unnamed_Namespaces_and_Static_Variables">internal linkage</a> to limit |
| 731 | its scope.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 732 | |
| 733 | <h3 id="Local_Variables">Local Variables</h3> |
| 734 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 735 | <p>Place a function's variables in the narrowest scope |
| 736 | possible, and initialize variables in the declaration.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 737 | |
| 738 | <p>C++ allows you to declare variables anywhere in a |
| 739 | function. We encourage you to declare them in as local a |
| 740 | scope as possible, and as close to the first use as |
| 741 | possible. This makes it easier for the reader to find the |
| 742 | declaration and see what type the variable is and what it |
| 743 | was initialized to. In particular, initialization should |
| 744 | be used instead of declaration and assignment, e.g.:</p> |
| 745 | |
| 746 | <pre class="badcode">int i; |
| 747 | i = f(); // Bad -- initialization separate from declaration. |
| 748 | </pre> |
| 749 | |
| 750 | <pre>int j = g(); // Good -- declaration has initialization. |
| 751 | </pre> |
| 752 | |
| 753 | <pre class="badcode">std::vector<int> v; |
| 754 | v.push_back(1); // Prefer initializing using brace initialization. |
| 755 | v.push_back(2); |
| 756 | </pre> |
| 757 | |
| 758 | <pre>std::vector<int> v = {1, 2}; // Good -- v starts initialized. |
| 759 | </pre> |
| 760 | |
| 761 | <p>Variables needed for <code>if</code>, <code>while</code> |
| 762 | and <code>for</code> statements should normally be declared |
| 763 | within those statements, so that such variables are confined |
| 764 | to those scopes. E.g.:</p> |
| 765 | |
| 766 | <pre>while (const char* p = strchr(str, '/')) str = p + 1; |
| 767 | </pre> |
| 768 | |
| 769 | <p>There is one caveat: if the variable is an object, its |
| 770 | constructor is invoked every time it enters scope and is |
| 771 | created, and its destructor is invoked every time it goes |
| 772 | out of scope.</p> |
| 773 | |
| 774 | <pre class="badcode">// Inefficient implementation: |
| 775 | for (int i = 0; i < 1000000; ++i) { |
| 776 | Foo f; // My ctor and dtor get called 1000000 times each. |
| 777 | f.DoSomething(i); |
| 778 | } |
| 779 | </pre> |
| 780 | |
| 781 | <p>It may be more efficient to declare such a variable |
| 782 | used in a loop outside that loop:</p> |
| 783 | |
| 784 | <pre>Foo f; // My ctor and dtor get called once each. |
| 785 | for (int i = 0; i < 1000000; ++i) { |
| 786 | f.DoSomething(i); |
| 787 | } |
| 788 | </pre> |
| 789 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 790 | <h3 id="Static_and_Global_Variables">Static and Global Variables</h3> |
| 791 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 792 | <p>Objects with |
| 793 | <a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration"> |
| 794 | static storage duration</a> are forbidden unless they are |
| 795 | <a href="http://en.cppreference.com/w/cpp/types/is_destructible">trivially |
| 796 | destructible</a>. Informally this means that the destructor does not do |
| 797 | anything, even taking member and base destructors into account. More formally it |
| 798 | means that the type has no user-defined or virtual destructor and that all bases |
| 799 | and non-static members are trivially destructible. |
| 800 | Static function-local variables may use dynamic initialization. |
| 801 | Use of dynamic initialization for static class member variables or variables at |
| 802 | namespace scope is discouraged, but allowed in limited circumstances; see below |
| 803 | for details.</p> |
| 804 | |
| 805 | <p>As a rule of thumb: a global variable satisfies these requirements if its |
| 806 | declaration, considered in isolation, could be <code>constexpr</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 807 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 808 | <p class="definition"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 809 | <p>Every object has a <dfn>storage duration</dfn>, which correlates with its |
| 810 | lifetime. Objects with static storage duration live from the point of their |
| 811 | initialization until the end of the program. Such objects appear as variables at |
| 812 | namespace scope ("global variables"), as static data members of classes, or as |
| 813 | function-local variables that are declared with the <code>static</code> |
| 814 | specifier. Function-local static variables are initialized when control first |
| 815 | passes through their declaration; all other objects with static storage duration |
| 816 | are initialized as part of program start-up. All objects with static storage |
| 817 | duration are destroyed at program exit (which happens before unjoined threads |
| 818 | are terminated).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 819 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 820 | <p>Initialization may be <dfn>dynamic</dfn>, which means that something |
| 821 | non-trivial happens during initialization. (For example, consider a constructor |
| 822 | that allocates memory, or a variable that is initialized with the current |
| 823 | process ID.) The other kind of initialization is <dfn>static</dfn> |
| 824 | initialization. The two aren't quite opposites, though: static |
| 825 | initialization <em>always</em> happens to objects with static storage duration |
| 826 | (initializing the object either to a given constant or to a representation |
| 827 | consisting of all bytes set to zero), whereas dynamic initialization happens |
| 828 | after that, if required.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 829 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 830 | <p class="pros"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 831 | <p>Global and static variables are very useful for a large number of |
| 832 | applications: named constants, auxiliary data structures internal to some |
| 833 | translation unit, command-line flags, logging, registration mechanisms, |
| 834 | background infrastructure, etc.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 835 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 836 | <p class="cons"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 837 | <p>Global and static variables that use dynamic initialization or have |
| 838 | non-trivial destructors create complexity that can easily lead to hard-to-find |
| 839 | bugs. Dynamic initialization is not ordered across translation units, and |
| 840 | neither is destruction (except that destruction |
| 841 | happens in reverse order of initialization). When one initialization refers to |
| 842 | another variable with static storage duration, it is possible that this causes |
| 843 | an object to be accessed before its lifetime has begun (or after its lifetime |
| 844 | has ended). Moreover, when a program starts threads that are not joined at exit, |
| 845 | those threads may attempt to access objects after their lifetime has ended if |
| 846 | their destructor has already run.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 847 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 848 | <p class="decision"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 849 | <h4>Decision on destruction</h4> |
| 850 | |
| 851 | <p>When destructors are trivial, their execution is not subject to ordering at |
| 852 | all (they are effectively not "run"); otherwise we are exposed to the risk of |
| 853 | accessing objects after the end of their lifetime. Therefore, we only allow |
| 854 | objects with static storage duration if they are trivially destructible. |
| 855 | Fundamental types (like pointers and <code>int</code>) are trivially |
| 856 | destructible, as are arrays of trivially destructible types. Note that |
| 857 | variables marked with <code>constexpr</code> are trivially destructible.</p> |
| 858 | <pre>const int kNum = 10; // allowed |
| 859 | |
| 860 | struct X { int n; }; |
| 861 | const X kX[] = {{1}, {2}, {3}}; // allowed |
| 862 | |
| 863 | void foo() { |
| 864 | static const char* const kMessages[] = {"hello", "world"}; // allowed |
| 865 | } |
| 866 | |
| 867 | // allowed: constexpr guarantees trivial destructor |
| 868 | constexpr std::array<int, 3> kArray = {{1, 2, 3}};</pre> |
| 869 | <pre class="badcode">// bad: non-trivial destructor |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 870 | const std::string kFoo = "foo"; |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 871 | |
| 872 | // bad for the same reason, even though kBar is a reference (the |
| 873 | // rule also applies to lifetime-extended temporary objects) |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 874 | const std::string& kBar = StrCat("a", "b", "c"); |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 875 | |
| 876 | void bar() { |
| 877 | // bad: non-trivial destructor |
| 878 | static std::map<int, int> kData = {{1, 0}, {2, 0}, {3, 0}}; |
| 879 | }</pre> |
| 880 | |
| 881 | <p>Note that references are not objects, and thus they are not subject to the |
| 882 | constraints on destructibility. The constraint on dynamic initialization still |
| 883 | applies, though. In particular, a function-local static reference of the form |
| 884 | <code>static T& t = *new T;</code> is allowed.</p> |
| 885 | |
| 886 | <h4>Decision on initialization</h4> |
| 887 | |
| 888 | <p>Initialization is a more complex topic. This is because we must not only |
| 889 | consider whether class constructors execute, but we must also consider the |
| 890 | evaluation of the initializer:</p> |
| 891 | <pre class="neutralcode">int n = 5; // fine |
| 892 | int m = f(); // ? (depends on f) |
| 893 | Foo x; // ? (depends on Foo::Foo) |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 894 | Bar y = g(); // ? (depends on g and on Bar::Bar) |
| 895 | </pre> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 896 | |
| 897 | <p>All but the first statement expose us to indeterminate initialization |
| 898 | ordering.</p> |
| 899 | |
| 900 | <p>The concept we are looking for is called <em>constant initialization</em> in |
| 901 | the formal language of the C++ standard. It means that the initializing |
| 902 | expression is a constant expression, and if the object is initialized by a |
| 903 | constructor call, then the constructor must be specified as |
| 904 | <code>constexpr</code>, too:</p> |
| 905 | <pre>struct Foo { constexpr Foo(int) {} }; |
| 906 | |
| 907 | int n = 5; // fine, 5 is a constant expression |
| 908 | Foo x(2); // fine, 2 is a constant expression and the chosen constructor is constexpr |
| 909 | Foo a[] = { Foo(1), Foo(2), Foo(3) }; // fine</pre> |
| 910 | |
| 911 | <p>Constant initialization is always allowed. Constant initialization of |
| 912 | static storage duration variables should be marked with <code>constexpr</code> |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 913 | or where possible the |
| 914 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 915 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 916 | <a href="https://github.com/abseil/abseil-cpp/blob/03c1513538584f4a04d666be5eb469e3979febba/absl/base/attributes.h#L540"> |
| 917 | <code>ABSL_CONST_INIT</code></a> |
| 918 | attribute. Any non-local static storage |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 919 | duration variable that is not so marked should be presumed to have |
| 920 | dynamic initialization, and reviewed very carefully.</p> |
| 921 | |
| 922 | <p>By contrast, the following initializations are problematic:</p> |
| 923 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 924 | <pre class="badcode">// Some declarations used below. |
| 925 | time_t time(time_t*); // not constexpr! |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 926 | int f(); // not constexpr! |
| 927 | struct Bar { Bar() {} }; |
| 928 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 929 | // Problematic initializations. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 930 | time_t m = time(nullptr); // initializing expression not a constant expression |
| 931 | Foo y(f()); // ditto |
| 932 | Bar b; // chosen constructor Bar::Bar() not constexpr</pre> |
| 933 | |
| 934 | <p>Dynamic initialization of nonlocal variables is discouraged, and in general |
| 935 | it is forbidden. However, we do permit it if no aspect of the program depends |
| 936 | on the sequencing of this initialization with respect to all other |
| 937 | initializations. Under those restrictions, the ordering of the initialization |
| 938 | does not make an observable difference. For example:</p> |
| 939 | <pre>int p = getpid(); // allowed, as long as no other static variable |
| 940 | // uses p in its own initialization</pre> |
| 941 | |
| 942 | <p>Dynamic initialization of static local variables is allowed (and common).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 943 | |
| 944 | |
| 945 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 946 | <h4>Common patterns</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 947 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 948 | <ul> |
| 949 | <li>Global strings: if you require a global or static string constant, |
| 950 | consider using a simple character array, or a char pointer to the first |
| 951 | element of a string literal. String literals have static storage duration |
| 952 | already and are usually sufficient.</li> |
| 953 | <li>Maps, sets, and other dynamic containers: if you require a static, fixed |
| 954 | collection, such as a set to search against or a lookup table, you cannot |
| 955 | use the dynamic containers from the standard library as a static variable, |
| 956 | since they have non-trivial destructors. Instead, consider a simple array of |
| 957 | trivial types, e.g. an array of arrays of ints (for a "map from int to |
| 958 | int"), or an array of pairs (e.g. pairs of <code>int</code> and <code>const |
| 959 | char*</code>). For small collections, linear search is entirely sufficient |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 960 | (and efficient, due to memory locality); consider using the facilities from |
| 961 | |
| 962 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/algorithm/container.h">absl/algorithm/container.h</a> |
| 963 | |
| 964 | |
| 965 | for the standard operations. If necessary, keep the collection in sorted |
| 966 | order and use a binary search algorithm. If you do really prefer a dynamic |
| 967 | container from the standard library, consider using a function-local static |
| 968 | pointer, as described below.</li> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 969 | <li>Smart pointers (<code>unique_ptr</code>, <code>shared_ptr</code>): smart |
| 970 | pointers execute cleanup during destruction and are therefore forbidden. |
| 971 | Consider whether your use case fits into one of the other patterns described |
| 972 | in this section. One simple solution is to use a plain pointer to a |
| 973 | dynamically allocated object and never delete it (see last item).</li> |
| 974 | <li>Static variables of custom types: if you require static, constant data of |
| 975 | a type that you need to define yourself, give the type a trivial destructor |
| 976 | and a <code>constexpr</code> constructor.</li> |
| 977 | <li>If all else fails, you can create an object dynamically and never delete |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 978 | it by using a function-local static pointer or reference (e.g. <code>static |
| 979 | const auto& impl = *new T(args...);</code>).</li> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 980 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 981 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 982 | <h3 id="thread_local">thread_local Variables</h3> |
| 983 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 984 | <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] | 985 | must be initialized with a true compile-time constant, |
| 986 | and this must be enforced by using the |
| 987 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 988 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 989 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h"> |
| 990 | <code>ABSL_CONST_INIT</code></a> |
| 991 | attribute. Prefer |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 992 | <code>thread_local</code> over other ways of defining thread-local data.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 993 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 994 | <p class="definition"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 995 | <p>Starting with C++11, variables can be declared with the |
| 996 | <code>thread_local</code> specifier:</p> |
| 997 | <pre>thread_local Foo foo = ...; |
| 998 | </pre> |
| 999 | <p>Such a variable is actually a collection of objects, so that when different |
| 1000 | threads access it, they are actually accessing different objects. |
| 1001 | <code>thread_local</code> variables are much like |
| 1002 | <a href="#Static_and_Global_Variables">static storage duration variables</a> |
| 1003 | in many respects. For instance, they can be declared at namespace scope, |
| 1004 | inside functions, or as static class members, but not as ordinary class |
| 1005 | members.</p> |
| 1006 | |
| 1007 | <p><code>thread_local</code> variable instances are initialized much like |
| 1008 | static variables, except that they must be initialized separately for each |
| 1009 | thread, rather than once at program startup. This means that |
| 1010 | <code>thread_local</code> variables declared within a function are safe, but |
| 1011 | other <code>thread_local</code> variables are subject to the same |
| 1012 | initialization-order issues as static variables (and more besides).</p> |
| 1013 | |
| 1014 | <p><code>thread_local</code> variable instances are destroyed when their thread |
| 1015 | terminates, so they do not have the destruction-order issues of static |
| 1016 | variables.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1017 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1018 | <p class="pros"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1019 | <ul> |
| 1020 | <li>Thread-local data is inherently safe from races (because only one thread |
| 1021 | can ordinarily access it), which makes <code>thread_local</code> useful for |
| 1022 | concurrent programming.</li> |
| 1023 | <li><code>thread_local</code> is the only standard-supported way of creating |
| 1024 | thread-local data.</li> |
| 1025 | </ul> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1026 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1027 | <p class="cons"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1028 | <ul> |
| 1029 | <li>Accessing a <code>thread_local</code> variable may trigger execution of |
| 1030 | an unpredictable and uncontrollable amount of other code.</li> |
| 1031 | <li><code>thread_local</code> variables are effectively global variables, |
| 1032 | and have all the drawbacks of global variables other than lack of |
| 1033 | thread-safety.</li> |
| 1034 | <li>The memory consumed by a <code>thread_local</code> variable scales with |
| 1035 | the number of running threads (in the worst case), which can be quite large |
| 1036 | in a program.</li> |
| 1037 | <li>An ordinary class member cannot be <code>thread_local</code>.</li> |
| 1038 | <li><code>thread_local</code> may not be as efficient as certain compiler |
| 1039 | intrinsics.</li> |
| 1040 | </ul> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1041 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1042 | <p class="decision"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1043 | <p><code>thread_local</code> variables inside a function have no safety |
| 1044 | concerns, so they can be used without restriction. Note that you can use |
| 1045 | a function-scope <code>thread_local</code> to simulate a class- or |
| 1046 | namespace-scope <code>thread_local</code> by defining a function or |
| 1047 | static method that exposes it:</p> |
| 1048 | |
| 1049 | <pre>Foo& MyThreadLocalFoo() { |
| 1050 | thread_local Foo result = ComplicatedInitialization(); |
| 1051 | return result; |
| 1052 | } |
| 1053 | </pre> |
| 1054 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1055 | <p><code>thread_local</code> variables at class or namespace scope must be |
| 1056 | initialized with a true compile-time constant (i.e. they must have no |
| 1057 | dynamic initialization). To enforce this, <code>thread_local</code> variables |
| 1058 | at class or namespace scope must be annotated with |
| 1059 | |
| 1060 | |
| 1061 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/base/attributes.h"> |
| 1062 | <code>ABSL_CONST_INIT</code></a> |
| 1063 | (or <code>constexpr</code>, but that should be rare):</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1064 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1065 | <pre>ABSL_CONST_INIT thread_local Foo foo = ...; |
| 1066 | </pre> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1067 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1068 | <p><code>thread_local</code> should be preferred over other mechanisms for |
| 1069 | defining thread-local data.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1070 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1071 | <h2 id="Classes">Classes</h2> |
| 1072 | |
| 1073 | <p>Classes are the fundamental unit of code in C++. Naturally, |
| 1074 | we use them extensively. This section lists the main dos and |
| 1075 | don'ts you should follow when writing a class.</p> |
| 1076 | |
| 1077 | <h3 id="Doing_Work_in_Constructors">Doing Work in Constructors</h3> |
| 1078 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1079 | <p>Avoid virtual method calls in constructors, and avoid |
| 1080 | initialization that can fail if you can't signal an error.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1081 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1082 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1083 | <p>It is possible to perform arbitrary initialization in the body |
| 1084 | of the constructor.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1085 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1086 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1087 | <ul> |
| 1088 | <li>No need to worry about whether the class has been initialized or |
| 1089 | not.</li> |
| 1090 | |
| 1091 | <li>Objects that are fully initialized by constructor call can |
| 1092 | be <code>const</code> and may also be easier to use with standard containers |
| 1093 | or algorithms.</li> |
| 1094 | </ul> |
| 1095 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1096 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1097 | <ul> |
| 1098 | <li>If the work calls virtual functions, these calls |
| 1099 | will not get dispatched to the subclass |
| 1100 | implementations. Future modification to your class can |
| 1101 | quietly introduce this problem even if your class is |
| 1102 | not currently subclassed, causing much confusion.</li> |
| 1103 | |
| 1104 | <li>There is no easy way for constructors to signal errors, short of |
| 1105 | crashing the program (not always appropriate) or using exceptions |
| 1106 | (which are <a href="#Exceptions">forbidden</a>).</li> |
| 1107 | |
| 1108 | <li>If the work fails, we now have an object whose initialization |
| 1109 | code failed, so it may be an unusual state requiring a <code>bool |
| 1110 | IsValid()</code> state checking mechanism (or similar) which is easy |
| 1111 | to forget to call.</li> |
| 1112 | |
| 1113 | <li>You cannot take the address of a constructor, so whatever work |
| 1114 | is done in the constructor cannot easily be handed off to, for |
| 1115 | example, another thread.</li> |
| 1116 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1117 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1118 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1119 | <p>Constructors should never call virtual functions. If appropriate |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1120 | for your code , |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1121 | terminating the program may be an appropriate error handling |
| 1122 | response. Otherwise, consider a factory function |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1123 | or <code>Init()</code> method as described in |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1124 | <a href="https://abseil.io/tips/42">TotW #42</a> |
| 1125 | . |
| 1126 | Avoid <code>Init()</code> methods on objects with |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1127 | no other states that affect which public methods may be called |
| 1128 | (semi-constructed objects of this form are particularly hard to work |
| 1129 | with correctly).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1130 | |
| 1131 | <a id="Explicit_Constructors"></a> |
| 1132 | <h3 id="Implicit_Conversions">Implicit Conversions</h3> |
| 1133 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1134 | <p>Do not define implicit conversions. Use the <code>explicit</code> |
| 1135 | keyword for conversion operators and single-argument |
| 1136 | constructors.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1137 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1138 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1139 | <p>Implicit conversions allow an |
| 1140 | object of one type (called the <dfn>source type</dfn>) to |
| 1141 | be used where a different type (called the <dfn>destination |
| 1142 | type</dfn>) is expected, such as when passing an |
| 1143 | <code>int</code> argument to a function that takes a |
| 1144 | <code>double</code> parameter.</p> |
| 1145 | |
| 1146 | <p>In addition to the implicit conversions defined by the language, |
| 1147 | users can define their own, by adding appropriate members to the |
| 1148 | class definition of the source or destination type. An implicit |
| 1149 | conversion in the source type is defined by a type conversion operator |
| 1150 | named after the destination type (e.g. <code>operator |
| 1151 | bool()</code>). An implicit conversion in the destination |
| 1152 | type is defined by a constructor that can take the source type as |
| 1153 | its only argument (or only argument with no default value).</p> |
| 1154 | |
| 1155 | <p>The <code>explicit</code> keyword can be applied to a constructor |
| 1156 | or (since C++11) a conversion operator, to ensure that it can only be |
| 1157 | used when the destination type is explicit at the point of use, |
| 1158 | e.g. with a cast. This applies not only to implicit conversions, but to |
| 1159 | C++11's list initialization syntax:</p> |
| 1160 | <pre>class Foo { |
| 1161 | explicit Foo(int x, double y); |
| 1162 | ... |
| 1163 | }; |
| 1164 | |
| 1165 | void Func(Foo f); |
| 1166 | </pre> |
| 1167 | <pre class="badcode">Func({42, 3.14}); // Error |
| 1168 | </pre> |
| 1169 | This kind of code isn't technically an implicit conversion, but the |
| 1170 | language treats it as one as far as <code>explicit</code> is concerned. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1171 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1172 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1173 | <ul> |
| 1174 | <li>Implicit conversions can make a type more usable and |
| 1175 | expressive by eliminating the need to explicitly name a type |
| 1176 | when it's obvious.</li> |
| 1177 | <li>Implicit conversions can be a simpler alternative to |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1178 | overloading, such as when a single |
| 1179 | function with a <code>string_view</code> parameter takes the |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1180 | place of separate overloads for <code>std::string</code> and |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 1181 | <code>const char*</code>.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1182 | <li>List initialization syntax is a concise and expressive |
| 1183 | way of initializing objects.</li> |
| 1184 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1185 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1186 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1187 | <ul> |
| 1188 | <li>Implicit conversions can hide type-mismatch bugs, where the |
| 1189 | destination type does not match the user's expectation, or |
| 1190 | the user is unaware that any conversion will take place.</li> |
| 1191 | |
| 1192 | <li>Implicit conversions can make code harder to read, particularly |
| 1193 | in the presence of overloading, by making it less obvious what |
| 1194 | code is actually getting called.</li> |
| 1195 | |
| 1196 | <li>Constructors that take a single argument may accidentally |
| 1197 | be usable as implicit type conversions, even if they are not |
| 1198 | intended to do so.</li> |
| 1199 | |
| 1200 | <li>When a single-argument constructor is not marked |
| 1201 | <code>explicit</code>, there's no reliable way to tell whether |
| 1202 | it's intended to define an implicit conversion, or the author |
| 1203 | simply forgot to mark it.</li> |
| 1204 | |
| 1205 | <li>It's not always clear which type should provide the conversion, |
| 1206 | and if they both do, the code becomes ambiguous.</li> |
| 1207 | |
| 1208 | <li>List initialization can suffer from the same problems if |
| 1209 | the destination type is implicit, particularly if the |
| 1210 | list has only a single element.</li> |
| 1211 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1212 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1213 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1214 | <p>Type conversion operators, and constructors that are |
| 1215 | callable with a single argument, must be marked |
| 1216 | <code>explicit</code> in the class definition. As an |
| 1217 | exception, copy and move constructors should not be |
| 1218 | <code>explicit</code>, since they do not perform type |
| 1219 | conversion. Implicit conversions can sometimes be necessary and |
| 1220 | appropriate for types that are designed to transparently wrap other |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1221 | types. In that case, contact |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1222 | your project leads to request |
| 1223 | a waiver of this rule.</p> |
| 1224 | |
| 1225 | <p>Constructors that cannot be called with a single argument |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1226 | may omit <code>explicit</code>. Constructors that |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1227 | take a single <code>std::initializer_list</code> parameter should |
| 1228 | also omit <code>explicit</code>, in order to support copy-initialization |
| 1229 | (e.g. <code>MyType m = {1, 2};</code>).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1230 | |
| 1231 | <h3 id="Copyable_Movable_Types">Copyable and Movable Types</h3> |
| 1232 | <a id="Copy_Constructors"></a> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1233 | |
| 1234 | <p>A class's public API must make clear whether the class is copyable, |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1235 | move-only, or neither copyable nor movable. Support copying and/or |
| 1236 | moving if these operations are clear and meaningful for your type.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1237 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1238 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1239 | <p>A movable type is one that can be initialized and assigned |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1240 | from temporaries.</p> |
| 1241 | |
| 1242 | <p>A copyable type is one that can be initialized or assigned from |
| 1243 | any other object of the same type (so is also movable by definition), with the |
| 1244 | stipulation that the value of the source does not change. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1245 | <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] | 1246 | copyable type (since the value of the source |
| 1247 | <code>std::unique_ptr<int></code> must be modified during assignment to |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1248 | the destination). <code>int</code> and <code>std::string</code> are examples of |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1249 | movable types that are also copyable. (For <code>int</code>, the move and copy |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1250 | operations are the same; for <code>std::string</code>, there exists a move operation |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1251 | that is less expensive than a copy.)</p> |
| 1252 | |
| 1253 | <p>For user-defined types, the copy behavior is defined by the copy |
| 1254 | constructor and the copy-assignment operator. Move behavior is defined by the |
| 1255 | move constructor and the move-assignment operator, if they exist, or by the |
| 1256 | copy constructor and the copy-assignment operator otherwise.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1257 | |
| 1258 | <p>The copy/move constructors can be implicitly invoked by the compiler |
| 1259 | in some situations, e.g. when passing objects by value.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1260 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1261 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1262 | <p>Objects of copyable and movable types can be passed and returned by value, |
| 1263 | which makes APIs simpler, safer, and more general. Unlike when passing objects |
| 1264 | by pointer or reference, there's no risk of confusion over ownership, |
| 1265 | lifetime, mutability, and similar issues, and no need to specify them in the |
| 1266 | contract. It also prevents non-local interactions between the client and the |
| 1267 | implementation, which makes them easier to understand, maintain, and optimize by |
| 1268 | the compiler. Further, such objects can be used with generic APIs that |
| 1269 | require pass-by-value, such as most containers, and they allow for additional |
| 1270 | flexibility in e.g., type composition.</p> |
| 1271 | |
| 1272 | <p>Copy/move constructors and assignment operators are usually |
| 1273 | easier to define correctly than alternatives |
| 1274 | like <code>Clone()</code>, <code>CopyFrom()</code> or <code>Swap()</code>, |
| 1275 | because they can be generated by the compiler, either implicitly or |
| 1276 | with <code>= default</code>. They are concise, and ensure |
| 1277 | that all data members are copied. Copy and move |
| 1278 | constructors are also generally more efficient, because they don't |
| 1279 | require heap allocation or separate initialization and assignment |
| 1280 | steps, and they're eligible for optimizations such as |
| 1281 | |
| 1282 | <a href="http://en.cppreference.com/w/cpp/language/copy_elision"> |
| 1283 | copy elision</a>.</p> |
| 1284 | |
| 1285 | <p>Move operations allow the implicit and efficient transfer of |
| 1286 | resources out of rvalue objects. This allows a plainer coding style |
| 1287 | in some cases.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1288 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1289 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1290 | <p>Some types do not need to be copyable, and providing copy |
| 1291 | operations for such types can be confusing, nonsensical, or outright |
| 1292 | incorrect. Types representing singleton objects (<code>Registerer</code>), |
| 1293 | objects tied to a specific scope (<code>Cleanup</code>), or closely coupled to |
| 1294 | object identity (<code>Mutex</code>) cannot be copied meaningfully. |
| 1295 | Copy operations for base class types that are to be used |
| 1296 | polymorphically are hazardous, because use of them can lead to |
| 1297 | <a href="https://en.wikipedia.org/wiki/Object_slicing">object slicing</a>. |
| 1298 | Defaulted or carelessly-implemented copy operations can be incorrect, and the |
| 1299 | resulting bugs can be confusing and difficult to diagnose.</p> |
| 1300 | |
| 1301 | <p>Copy constructors are invoked implicitly, which makes the |
| 1302 | invocation easy to miss. This may cause confusion for programmers used to |
| 1303 | languages where pass-by-reference is conventional or mandatory. It may also |
| 1304 | encourage excessive copying, which can cause performance problems.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1305 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1306 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1307 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1308 | <p>Every class's public interface must make clear which copy and move |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1309 | operations the class supports. This should usually take the form of explicitly |
| 1310 | declaring and/or deleting the appropriate operations in the <code>public</code> |
| 1311 | section of the declaration.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1312 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1313 | <p>Specifically, a copyable class should explicitly declare the copy |
| 1314 | operations, a move-only class should explicitly declare the move operations, |
| 1315 | and a non-copyable/movable class should explicitly delete the copy operations. |
| 1316 | Explicitly declaring or deleting all four copy/move operations is permitted, |
| 1317 | but not required. If you provide a copy or move assignment operator, you |
| 1318 | must also provide the corresponding constructor.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1319 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1320 | <pre>class Copyable { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1321 | public: |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1322 | Copyable(const Copyable& other) = default; |
| 1323 | Copyable& operator=(const Copyable& other) = default; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1324 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1325 | // The implicit move operations are suppressed by the declarations above. |
| 1326 | }; |
| 1327 | |
| 1328 | class MoveOnly { |
| 1329 | public: |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1330 | MoveOnly(MoveOnly&& other); |
| 1331 | MoveOnly& operator=(MoveOnly&& other); |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1332 | |
| 1333 | // The copy operations are implicitly deleted, but you can |
| 1334 | // spell that out explicitly if you want: |
| 1335 | MoveOnly(const MoveOnly&) = delete; |
| 1336 | MoveOnly& operator=(const MoveOnly&) = delete; |
| 1337 | }; |
| 1338 | |
| 1339 | class NotCopyableOrMovable { |
| 1340 | public: |
| 1341 | // Not copyable or movable |
| 1342 | NotCopyableOrMovable(const NotCopyableOrMovable&) = delete; |
| 1343 | NotCopyableOrMovable& operator=(const NotCopyableOrMovable&) |
| 1344 | = delete; |
| 1345 | |
| 1346 | // The move operations are implicitly disabled, but you can |
| 1347 | // spell that out explicitly if you want: |
| 1348 | NotCopyableOrMovable(NotCopyableOrMovable&&) = delete; |
| 1349 | NotCopyableOrMovable& operator=(NotCopyableOrMovable&&) |
| 1350 | = delete; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1351 | }; |
| 1352 | </pre> |
| 1353 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1354 | <p>These declarations/deletions can be omitted only if they are obvious: |
| 1355 | </p><ul> |
| 1356 | <li>If the class has no <code>private</code> section, like a |
| 1357 | <a href="#Structs_vs._Classes">struct</a> or an interface-only base class, |
| 1358 | then the copyability/movability can be determined by the |
| 1359 | copyability/movability of any public data members. |
| 1360 | </li><li>If a base class clearly isn't copyable or movable, derived classes |
| 1361 | naturally won't be either. An interface-only base class that leaves these |
| 1362 | operations implicit is not sufficient to make concrete subclasses clear. |
| 1363 | </li><li>Note that if you explicitly declare or delete either the constructor or |
| 1364 | assignment operation for copy, the other copy operation is not obvious and |
| 1365 | must be declared or deleted. Likewise for move operations. |
| 1366 | </li></ul> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1367 | |
| 1368 | <p>A type should not be copyable/movable if the meaning of |
| 1369 | copying/moving is unclear to a casual user, or if it incurs unexpected |
| 1370 | costs. Move operations for copyable types are strictly a performance |
| 1371 | optimization and are a potential source of bugs and complexity, so |
| 1372 | avoid defining them unless they are significantly more efficient than |
| 1373 | the corresponding copy operations. If your type provides copy operations, it is |
| 1374 | recommended that you design your class so that the default implementation of |
| 1375 | those operations is correct. Remember to review the correctness of any |
| 1376 | defaulted operations as you would any other code.</p> |
| 1377 | |
| 1378 | <p>Due to the risk of slicing, prefer to avoid providing a public assignment |
| 1379 | operator or copy/move constructor for a class that's |
| 1380 | 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] | 1381 | with such members). If your base class needs to be |
| 1382 | copyable, provide a public virtual <code>Clone()</code> |
| 1383 | method, and a protected copy constructor that derived classes |
| 1384 | can use to implement it.</p> |
| 1385 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1386 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1387 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1388 | <h3 id="Structs_vs._Classes">Structs vs. Classes</h3> |
| 1389 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1390 | <p>Use a <code>struct</code> only for passive objects that |
| 1391 | carry data; everything else is a <code>class</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1392 | |
| 1393 | <p>The <code>struct</code> and <code>class</code> |
| 1394 | keywords behave almost identically in C++. We add our own |
| 1395 | semantic meanings to each keyword, so you should use the |
| 1396 | appropriate keyword for the data-type you're |
| 1397 | defining.</p> |
| 1398 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1399 | <p><code>structs</code> should be used for passive objects that carry |
| 1400 | data, and may have associated constants, but lack any functionality |
| 1401 | other than access/setting the data members. All fields must be public, |
| 1402 | and accessed directly rather than through getter/setter methods. The |
| 1403 | struct must not have invariants that imply relationships between |
| 1404 | different fields, since direct user access to those fields may break |
| 1405 | those invariants. Methods should not provide behavior but should only |
| 1406 | be used to set up the data members, e.g., constructor, destructor, |
| 1407 | <code>Initialize()</code>, <code>Reset()</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1408 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1409 | <p>If more functionality or invariants are required, a |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1410 | <code>class</code> is more appropriate. If in doubt, make |
| 1411 | it a <code>class</code>.</p> |
| 1412 | |
| 1413 | <p>For consistency with STL, you can use |
| 1414 | <code>struct</code> instead of <code>class</code> for |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1415 | stateless types, such as traits, |
| 1416 | <a href="#Template_metaprogramming">template metafunctions</a>, |
| 1417 | and some functors.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1418 | |
| 1419 | <p>Note that member variables in structs and classes have |
| 1420 | <a href="#Variable_Names">different naming rules</a>.</p> |
| 1421 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1422 | <h3 id="Structs_vs._Tuples">Structs vs. Pairs and Tuples</h3> |
| 1423 | |
| 1424 | <p>Prefer to use a <code>struct</code> instead of a pair or a |
| 1425 | tuple whenever the elements can have meaningful names.</p> |
| 1426 | |
| 1427 | <p> |
| 1428 | While using pairs and tuples can avoid the need to define a custom type, |
| 1429 | potentially saving work when <em>writing</em> code, a meaningful field |
| 1430 | name will almost always be much clearer when <em>reading</em> code than |
| 1431 | <code>.first</code>, <code>.second</code>, or <code>std::get<X></code>. |
| 1432 | While C++14's introduction of <code>std::get<Type></code> to access a |
| 1433 | tuple element by type rather than index (when the type is unique) can |
| 1434 | sometimes partially mitigate this, a field name is usually substantially |
| 1435 | clearer and more informative than a type. |
| 1436 | </p> |
| 1437 | |
| 1438 | <p> |
| 1439 | Pairs and tuples may be appropriate in generic code where there are not |
| 1440 | specific meanings for the elements of the pair or tuple. Their use may |
| 1441 | also be required in order to interoperate with existing code or APIs. |
| 1442 | </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1443 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1444 | <a id="Multiple_Inheritance"></a> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1445 | <h3 id="Inheritance">Inheritance</h3> |
| 1446 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1447 | <p>Composition is often more appropriate than inheritance. |
| 1448 | When using inheritance, make it <code>public</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1449 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1450 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1451 | <p> When a sub-class |
| 1452 | inherits from a base class, it includes the definitions |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1453 | of all the data and operations that the base class |
| 1454 | defines. "Interface inheritance" is inheritance from a |
| 1455 | pure abstract base class (one with no state or defined |
| 1456 | methods); all other inheritance is "implementation |
| 1457 | inheritance".</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1458 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1459 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1460 | <p>Implementation inheritance reduces code size by re-using |
| 1461 | the base class code as it specializes an existing type. |
| 1462 | Because inheritance is a compile-time declaration, you |
| 1463 | and the compiler can understand the operation and detect |
| 1464 | errors. Interface inheritance can be used to |
| 1465 | programmatically enforce that a class expose a particular |
| 1466 | API. Again, the compiler can detect errors, in this case, |
| 1467 | when a class does not define a necessary method of the |
| 1468 | API.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1469 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1470 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1471 | <p>For implementation inheritance, because the code |
| 1472 | implementing a sub-class is spread between the base and |
| 1473 | the sub-class, it can be more difficult to understand an |
| 1474 | implementation. The sub-class cannot override functions |
| 1475 | that are not virtual, so the sub-class cannot change |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1476 | implementation.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1477 | |
| 1478 | <p>Multiple inheritance is especially problematic, because |
| 1479 | it often imposes a higher performance overhead (in fact, |
| 1480 | the performance drop from single inheritance to multiple |
| 1481 | inheritance can often be greater than the performance |
| 1482 | drop from ordinary to virtual dispatch), and because |
| 1483 | it risks leading to "diamond" inheritance patterns, |
| 1484 | which are prone to ambiguity, confusion, and outright bugs.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1485 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1486 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1487 | |
| 1488 | <p>All inheritance should be <code>public</code>. If you |
| 1489 | want to do private inheritance, you should be including |
| 1490 | an instance of the base class as a member instead.</p> |
| 1491 | |
| 1492 | <p>Do not overuse implementation inheritance. Composition |
| 1493 | is often more appropriate. Try to restrict use of |
| 1494 | inheritance to the "is-a" case: <code>Bar</code> |
| 1495 | subclasses <code>Foo</code> if it can reasonably be said |
| 1496 | that <code>Bar</code> "is a kind of" |
| 1497 | <code>Foo</code>.</p> |
| 1498 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1499 | <p>Limit the use of <code>protected</code> to those |
| 1500 | member functions that might need to be accessed from |
| 1501 | subclasses. Note that <a href="#Access_Control">data |
| 1502 | members should be private</a>.</p> |
| 1503 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1504 | <p>Explicitly annotate overrides of virtual functions or virtual |
| 1505 | destructors with exactly one of an <code>override</code> or (less |
| 1506 | frequently) <code>final</code> specifier. Do not |
| 1507 | use <code>virtual</code> when declaring an override. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1508 | Rationale: A function or destructor marked |
| 1509 | <code>override</code> or <code>final</code> that is |
| 1510 | not an override of a base class virtual function will |
| 1511 | not compile, and this helps catch common errors. The |
| 1512 | specifiers serve as documentation; if no specifier is |
| 1513 | present, the reader has to check all ancestors of the |
| 1514 | class in question to determine if the function or |
| 1515 | destructor is virtual or not.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1516 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1517 | <p>Multiple inheritance is permitted, but multiple <em>implementation</em> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1518 | inheritance is strongly discouraged.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1519 | |
| 1520 | <h3 id="Operator_Overloading">Operator Overloading</h3> |
| 1521 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1522 | <p>Overload operators judiciously. Do not use user-defined literals.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1523 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1524 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1525 | <p>C++ permits user code to |
| 1526 | <a href="http://en.cppreference.com/w/cpp/language/operators">declare |
| 1527 | overloaded versions of the built-in operators</a> using the |
| 1528 | <code>operator</code> keyword, so long as one of the parameters |
| 1529 | is a user-defined type. The <code>operator</code> keyword also |
| 1530 | permits user code to define new kinds of literals using |
| 1531 | <code>operator""</code>, and to define type-conversion functions |
| 1532 | such as <code>operator bool()</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1533 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1534 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1535 | <p>Operator overloading can make code more concise and |
| 1536 | intuitive by enabling user-defined types to behave the same |
| 1537 | as built-in types. Overloaded operators are the idiomatic names |
| 1538 | for certain operations (e.g. <code>==</code>, <code><</code>, |
| 1539 | <code>=</code>, and <code><<</code>), and adhering to |
| 1540 | those conventions can make user-defined types more readable |
| 1541 | and enable them to interoperate with libraries that expect |
| 1542 | those names.</p> |
| 1543 | |
| 1544 | <p>User-defined literals are a very concise notation for |
| 1545 | creating objects of user-defined types.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1546 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1547 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1548 | <ul> |
| 1549 | <li>Providing a correct, consistent, and unsurprising |
| 1550 | set of operator overloads requires some care, and failure |
| 1551 | to do so can lead to confusion and bugs.</li> |
| 1552 | |
| 1553 | <li>Overuse of operators can lead to obfuscated code, |
| 1554 | particularly if the overloaded operator's semantics |
| 1555 | don't follow convention.</li> |
| 1556 | |
| 1557 | <li>The hazards of function overloading apply just as |
| 1558 | much to operator overloading, if not more so.</li> |
| 1559 | |
| 1560 | <li>Operator overloads can fool our intuition into |
| 1561 | thinking that expensive operations are cheap, built-in |
| 1562 | operations.</li> |
| 1563 | |
| 1564 | <li>Finding the call sites for overloaded operators may |
| 1565 | require a search tool that's aware of C++ syntax, rather |
| 1566 | than e.g. grep.</li> |
| 1567 | |
| 1568 | <li>If you get the argument type of an overloaded operator |
| 1569 | wrong, you may get a different overload rather than a |
| 1570 | compiler error. For example, <code>foo < bar</code> |
| 1571 | may do one thing, while <code>&foo < &bar</code> |
| 1572 | does something totally different.</li> |
| 1573 | |
| 1574 | <li>Certain operator overloads are inherently hazardous. |
| 1575 | Overloading unary <code>&</code> can cause the same |
| 1576 | code to have different meanings depending on whether |
| 1577 | the overload declaration is visible. Overloads of |
| 1578 | <code>&&</code>, <code>||</code>, and <code>,</code> |
| 1579 | (comma) cannot match the evaluation-order semantics of the |
| 1580 | built-in operators.</li> |
| 1581 | |
| 1582 | <li>Operators are often defined outside the class, |
| 1583 | so there's a risk of different files introducing |
| 1584 | different definitions of the same operator. If both |
| 1585 | definitions are linked into the same binary, this results |
| 1586 | in undefined behavior, which can manifest as subtle |
| 1587 | run-time bugs.</li> |
| 1588 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1589 | <li>User-defined literals (UDLs) allow the creation of new |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1590 | syntactic forms that are unfamiliar even to experienced C++ |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1591 | programmers, such as <code>"Hello World"sv</code> as a |
| 1592 | shorthand for <code>std::string_view("Hello World")</code>. |
| 1593 | Existing notations are clearer, though less terse.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1594 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1595 | <li>Because they can't be namespace-qualified, uses of UDLs also require |
| 1596 | use of either using-directives (which <a href="#Namespaces">we ban</a>) or |
| 1597 | using-declarations (which <a href="#Aliases">we ban in header files</a> except |
| 1598 | when the imported names are part of the interface exposed by the header |
| 1599 | file in question). Given that header files would have to avoid UDL |
| 1600 | suffixes, we prefer to avoid having conventions for literals differ |
| 1601 | between header files and source files. |
| 1602 | </li> |
| 1603 | </ul> |
| 1604 | |
| 1605 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1606 | <p>Define overloaded operators only if their meaning is |
| 1607 | obvious, unsurprising, and consistent with the corresponding |
| 1608 | built-in operators. For example, use <code>|</code> as a |
| 1609 | bitwise- or logical-or, not as a shell-style pipe.</p> |
| 1610 | |
| 1611 | <p>Define operators only on your own types. More precisely, |
| 1612 | define them in the same headers, .cc files, and namespaces |
| 1613 | as the types they operate on. That way, the operators are available |
| 1614 | wherever the type is, minimizing the risk of multiple |
| 1615 | definitions. If possible, avoid defining operators as templates, |
| 1616 | because they must satisfy this rule for any possible template |
| 1617 | arguments. If you define an operator, also define |
| 1618 | any related operators that make sense, and make sure they |
| 1619 | are defined consistently. For example, if you overload |
| 1620 | <code><</code>, overload all the comparison operators, |
| 1621 | and make sure <code><</code> and <code>></code> never |
| 1622 | return true for the same arguments.</p> |
| 1623 | |
| 1624 | <p>Prefer to define non-modifying binary operators as |
| 1625 | non-member functions. If a binary operator is defined as a |
| 1626 | class member, implicit conversions will apply to the |
| 1627 | right-hand argument, but not the left-hand one. It will |
| 1628 | confuse your users if <code>a < b</code> compiles but |
| 1629 | <code>b < a</code> doesn't.</p> |
| 1630 | |
| 1631 | <p>Don't go out of your way to avoid defining operator |
| 1632 | overloads. For example, prefer to define <code>==</code>, |
| 1633 | <code>=</code>, and <code><<</code>, rather than |
| 1634 | <code>Equals()</code>, <code>CopyFrom()</code>, and |
| 1635 | <code>PrintTo()</code>. Conversely, don't define |
| 1636 | operator overloads just because other libraries expect |
| 1637 | them. For example, if your type doesn't have a natural |
| 1638 | ordering, but you want to store it in a <code>std::set</code>, |
| 1639 | use a custom comparator rather than overloading |
| 1640 | <code><</code>.</p> |
| 1641 | |
| 1642 | <p>Do not overload <code>&&</code>, <code>||</code>, |
| 1643 | <code>,</code> (comma), or unary <code>&</code>. Do not overload |
| 1644 | <code>operator""</code>, i.e. do not introduce user-defined |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1645 | literals. Do not use any such literals provided by others |
| 1646 | (including the standard library).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1647 | |
| 1648 | <p>Type conversion operators are covered in the section on |
| 1649 | <a href="#Implicit_Conversions">implicit conversions</a>. |
| 1650 | The <code>=</code> operator is covered in the section on |
| 1651 | <a href="#Copy_Constructors">copy constructors</a>. Overloading |
| 1652 | <code><<</code> for use with streams is covered in the |
| 1653 | section on <a href="#Streams">streams</a>. See also the rules on |
| 1654 | <a href="#Function_Overloading">function overloading</a>, which |
| 1655 | apply to operator overloading as well.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1656 | |
| 1657 | <h3 id="Access_Control">Access Control</h3> |
| 1658 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1659 | <p>Make classes' data members <code>private</code>, unless they are |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1660 | <a href="#Constant_Names">constants</a>. This simplifies reasoning about invariants, at the cost |
| 1661 | of some easy boilerplate in the form of accessors (usually <code>const</code>) if necessary.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1662 | |
| 1663 | <p>For technical |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1664 | 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] | 1665 | be <code>protected</code> when using |
| 1666 | |
| 1667 | |
| 1668 | <a href="https://github.com/google/googletest">Google |
| 1669 | Test</a>).</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1670 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1671 | <h3 id="Declaration_Order">Declaration Order</h3> |
| 1672 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1673 | <p>Group similar declarations together, placing public parts |
| 1674 | earlier.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1675 | |
| 1676 | <p>A class definition should usually start with a |
| 1677 | <code>public:</code> section, followed by |
| 1678 | <code>protected:</code>, then <code>private:</code>. Omit |
| 1679 | sections that would be empty.</p> |
| 1680 | |
| 1681 | <p>Within each section, generally prefer grouping similar |
| 1682 | kinds of declarations together, and generally prefer the |
| 1683 | following order: types (including <code>typedef</code>, |
| 1684 | <code>using</code>, and nested structs and classes), |
| 1685 | constants, factory functions, constructors, assignment |
| 1686 | operators, destructor, all other methods, data members.</p> |
| 1687 | |
| 1688 | <p>Do not put large method definitions inline in the |
| 1689 | class definition. Usually, only trivial or |
| 1690 | performance-critical, and very short, methods may be |
| 1691 | defined inline. See <a href="#Inline_Functions">Inline |
| 1692 | Functions</a> for more details.</p> |
| 1693 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1694 | <h2 id="Functions">Functions</h2> |
| 1695 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1696 | <a id="Function_Parameter_Ordering"></a> |
| 1697 | <h3 id="Output_Parameters">Output Parameters</h3> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1698 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1699 | <p>The output of a C++ function is naturally provided via |
| 1700 | a return value and sometimes via output parameters.</p> |
| 1701 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1702 | <p>Prefer using return values over output parameters: they |
| 1703 | improve readability, and often provide the same or better |
| 1704 | performance. If output-only parameters are used, |
| 1705 | they should appear after input parameters.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1706 | |
| 1707 | <p>Parameters are either input to the function, output from the |
| 1708 | function, or both. Input parameters are usually values or |
| 1709 | <code>const</code> references, while output and input/output |
| 1710 | parameters will be pointers to non-<code>const</code>.</p> |
| 1711 | |
| 1712 | <p>When ordering function parameters, put all input-only |
| 1713 | parameters before any output parameters. In particular, |
| 1714 | do not add new parameters to the end of the function just |
| 1715 | because they are new; place new input-only parameters before |
| 1716 | the output parameters.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1717 | |
| 1718 | <p>This is not a hard-and-fast rule. Parameters that are |
| 1719 | both input and output (often classes/structs) muddy the |
| 1720 | waters, and, as always, consistency with related |
| 1721 | functions may require you to bend the rule.</p> |
| 1722 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1723 | <h3 id="Write_Short_Functions">Write Short Functions</h3> |
| 1724 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1725 | <p>Prefer small and focused functions.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1726 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1727 | <p>We recognize that long functions are sometimes |
| 1728 | appropriate, so no hard limit is placed on functions |
| 1729 | length. If a function exceeds about 40 lines, think about |
| 1730 | whether it can be broken up without harming the structure |
| 1731 | of the program.</p> |
| 1732 | |
| 1733 | <p>Even if your long function works perfectly now, |
| 1734 | someone modifying it in a few months may add new |
| 1735 | behavior. This could result in bugs that are hard to |
| 1736 | find. Keeping your functions short and simple makes it |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1737 | easier for other people to read and modify your code. |
| 1738 | Small functions are also easier to test.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1739 | |
| 1740 | <p>You could find long and complicated functions when |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1741 | working with |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1742 | some code. Do not be |
| 1743 | intimidated by modifying existing code: if working with |
| 1744 | such a function proves to be difficult, you find that |
| 1745 | errors are hard to debug, or you want to use a piece of |
| 1746 | it in several different contexts, consider breaking up |
| 1747 | the function into smaller and more manageable pieces.</p> |
| 1748 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1749 | <h3 id="Reference_Arguments">Reference Arguments</h3> |
| 1750 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1751 | <p>All parameters passed by lvalue reference must be labeled |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1752 | <code>const</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1753 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1754 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1755 | <p>In C, if a |
| 1756 | function needs to modify a variable, the parameter must |
| 1757 | use a pointer, eg <code>int foo(int *pval)</code>. In |
| 1758 | C++, the function can alternatively declare a reference |
| 1759 | parameter: <code>int foo(int &val)</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1760 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1761 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1762 | <p>Defining a parameter as reference avoids ugly code like |
| 1763 | <code>(*pval)++</code>. Necessary for some applications |
| 1764 | like copy constructors. Makes it clear, unlike with |
| 1765 | pointers, that a null pointer is not a possible |
| 1766 | value.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1767 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1768 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1769 | <p>References can be confusing, as they have value syntax |
| 1770 | but pointer semantics.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1771 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1772 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1773 | <p>Within function parameter lists all references must be |
| 1774 | <code>const</code>:</p> |
| 1775 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1776 | <pre>void Foo(const std::string &in, std::string *out); |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1777 | </pre> |
| 1778 | |
| 1779 | <p>In fact it is a very strong convention in Google code |
| 1780 | that input arguments are values or <code>const</code> |
| 1781 | references while output arguments are pointers. Input |
| 1782 | parameters may be <code>const</code> pointers, but we |
| 1783 | never allow non-<code>const</code> reference parameters |
| 1784 | except when required by convention, e.g., |
| 1785 | <code>swap()</code>.</p> |
| 1786 | |
| 1787 | <p>However, there are some instances where using |
| 1788 | <code>const T*</code> is preferable to <code>const |
| 1789 | T&</code> for input parameters. For example:</p> |
| 1790 | |
| 1791 | <ul> |
| 1792 | <li>You want to pass in a null pointer.</li> |
| 1793 | |
| 1794 | <li>The function saves a pointer or reference to the |
| 1795 | input.</li> |
| 1796 | </ul> |
| 1797 | |
| 1798 | <p> Remember that most of the time input |
| 1799 | parameters are going to be specified as <code>const |
| 1800 | T&</code>. Using <code>const T*</code> instead |
| 1801 | communicates to the reader that the input is somehow |
| 1802 | treated differently. So if you choose <code>const |
| 1803 | T*</code> rather than <code>const T&</code>, do so |
| 1804 | for a concrete reason; otherwise it will likely confuse |
| 1805 | readers by making them look for an explanation that |
| 1806 | doesn't exist.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1807 | |
| 1808 | <h3 id="Function_Overloading">Function Overloading</h3> |
| 1809 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1810 | <p>Use overloaded functions (including constructors) only if a |
| 1811 | reader looking at a call site can get a good idea of what |
| 1812 | is happening without having to first figure out exactly |
| 1813 | which overload is being called.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1814 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1815 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1816 | <p>You may write a function that takes a <code>const |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1817 | std::string&</code> and overload it with another that |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1818 | takes <code>const char*</code>. However, in this case consider |
| 1819 | std::string_view |
| 1820 | instead.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1821 | |
| 1822 | <pre>class MyClass { |
| 1823 | public: |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1824 | void Analyze(const std::string &text); |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1825 | void Analyze(const char *text, size_t textlen); |
| 1826 | }; |
| 1827 | </pre> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1828 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1829 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1830 | <p>Overloading can make code more intuitive by allowing an |
| 1831 | identically-named function to take different arguments. |
| 1832 | It may be necessary for templatized code, and it can be |
| 1833 | convenient for Visitors.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1834 | <p>Overloading based on const or ref qualification may make utility |
| 1835 | code more usable, more efficient, or both. |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1836 | (See <a href="http://abseil.io/tips/148">TotW 148</a> for more.) |
| 1837 | </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1838 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1839 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1840 | <p>If a function is overloaded by the argument types alone, |
| 1841 | a reader may have to understand C++'s complex matching |
| 1842 | rules in order to tell what's going on. Also many people |
| 1843 | are confused by the semantics of inheritance if a derived |
| 1844 | class overrides only some of the variants of a |
| 1845 | function.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1846 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1847 | <p class="decision"></p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1848 | <p>You may overload a function when there are no semantic differences |
| 1849 | between variants. These overloads may vary in types, qualifiers, or |
| 1850 | argument count. However, a reader of such a call must not need to know |
| 1851 | which member of the overload set is chosen, only that <b>something</b> |
| 1852 | from the set is being called. If you can document all entries in the |
| 1853 | overload set with a single comment in the header, that is a good sign |
| 1854 | that it is a well-designed overload set.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1855 | |
| 1856 | <h3 id="Default_Arguments">Default Arguments</h3> |
| 1857 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1858 | <p>Default arguments are allowed on non-virtual functions |
| 1859 | when the default is guaranteed to always have the same |
| 1860 | value. Follow the same restrictions as for <a href="#Function_Overloading">function overloading</a>, and |
| 1861 | prefer overloaded functions if the readability gained with |
| 1862 | default arguments doesn't outweigh the downsides below.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1863 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1864 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1865 | <p>Often you have a function that uses default values, but |
| 1866 | occasionally you want to override the defaults. Default |
| 1867 | parameters allow an easy way to do this without having to |
| 1868 | define many functions for the rare exceptions. Compared |
| 1869 | to overloading the function, default arguments have a |
| 1870 | cleaner syntax, with less boilerplate and a clearer |
| 1871 | distinction between 'required' and 'optional' |
| 1872 | arguments.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1873 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1874 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1875 | <p>Defaulted arguments are another way to achieve the |
| 1876 | semantics of overloaded functions, so all the <a href="#Function_Overloading">reasons not to overload |
| 1877 | functions</a> apply.</p> |
| 1878 | |
| 1879 | <p>The defaults for arguments in a virtual function call are |
| 1880 | determined by the static type of the target object, and |
| 1881 | there's no guarantee that all overrides of a given function |
| 1882 | declare the same defaults.</p> |
| 1883 | |
| 1884 | <p>Default parameters are re-evaluated at each call site, |
| 1885 | which can bloat the generated code. Readers may also expect |
| 1886 | the default's value to be fixed at the declaration instead |
| 1887 | of varying at each call.</p> |
| 1888 | |
| 1889 | <p>Function pointers are confusing in the presence of |
| 1890 | default arguments, since the function signature often |
| 1891 | doesn't match the call signature. Adding |
| 1892 | function overloads avoids these problems.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1893 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1894 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1895 | <p>Default arguments are banned on virtual functions, where |
| 1896 | they don't work properly, and in cases where the specified |
| 1897 | default might not evaluate to the same value depending on |
| 1898 | when it was evaluated. (For example, don't write <code>void |
| 1899 | f(int n = counter++);</code>.)</p> |
| 1900 | |
| 1901 | <p>In some other cases, default arguments can improve the |
| 1902 | readability of their function declarations enough to |
| 1903 | overcome the downsides above, so they are allowed. When in |
| 1904 | doubt, use overloads.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1905 | |
| 1906 | <h3 id="trailing_return">Trailing Return Type Syntax</h3> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1907 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1908 | <p>Use trailing return types only where using the ordinary syntax (leading |
| 1909 | return types) is impractical or much less readable.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1910 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1911 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1912 | <p>C++ allows two different forms of function declarations. In the older |
| 1913 | form, the return type appears before the function name. For example:</p> |
| 1914 | <pre>int foo(int x); |
| 1915 | </pre> |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 1916 | <p>The newer form, introduced in C++11, uses the <code>auto</code> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1917 | keyword before the function name and a trailing return type after |
| 1918 | the argument list. For example, the declaration above could |
| 1919 | equivalently be written:</p> |
| 1920 | <pre>auto foo(int x) -> int; |
| 1921 | </pre> |
| 1922 | <p>The trailing return type is in the function's scope. This doesn't |
| 1923 | make a difference for a simple case like <code>int</code> but it matters |
| 1924 | for more complicated cases, like types declared in class scope or |
| 1925 | types written in terms of the function parameters.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1926 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1927 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1928 | <p>Trailing return types are the only way to explicitly specify the |
| 1929 | return type of a <a href="#Lambda_expressions">lambda expression</a>. |
| 1930 | In some cases the compiler is able to deduce a lambda's return type, |
| 1931 | but not in all cases. Even when the compiler can deduce it automatically, |
| 1932 | sometimes specifying it explicitly would be clearer for readers. |
| 1933 | </p> |
| 1934 | <p>Sometimes it's easier and more readable to specify a return type |
| 1935 | after the function's parameter list has already appeared. This is |
| 1936 | particularly true when the return type depends on template parameters. |
| 1937 | For example:</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1938 | <pre> template <typename T, typename U> |
| 1939 | auto add(T t, U u) -> decltype(t + u); |
| 1940 | </pre> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1941 | versus |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 1942 | <pre> template <typename T, typename U> |
| 1943 | decltype(declval<T&>() + declval<U&>()) add(T t, U u); |
| 1944 | </pre> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1945 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1946 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1947 | <p>Trailing return type syntax is relatively new and it has no |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 1948 | 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] | 1949 | find it unfamiliar.</p> |
| 1950 | <p>Existing code bases have an enormous number of function |
| 1951 | declarations that aren't going to get changed to use the new syntax, |
| 1952 | so the realistic choices are using the old syntax only or using a mixture |
| 1953 | of the two. Using a single version is better for uniformity of style.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1954 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1955 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1956 | <p>In most cases, continue to use the older style of function |
| 1957 | declaration where the return type goes before the function name. |
| 1958 | Use the new trailing-return-type form only in cases where it's |
| 1959 | required (such as lambdas) or where, by putting the type after the |
| 1960 | function's parameter list, it allows you to write the type in a much |
| 1961 | more readable way. The latter case should be rare; it's mostly an |
| 1962 | issue in fairly complicated template code, which is |
| 1963 | <a href="#Template_metaprogramming">discouraged in most cases</a>.</p> |
| 1964 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1965 | |
| 1966 | <h2 id="Google-Specific_Magic">Google-Specific Magic</h2> |
| 1967 | |
| 1968 | |
| 1969 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1970 | <div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1971 | <p>There are various tricks and utilities that |
| 1972 | we use to make C++ code more robust, and various ways we use |
| 1973 | C++ that may differ from what you see elsewhere.</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1974 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1975 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1976 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1977 | |
| 1978 | <h3 id="Ownership_and_Smart_Pointers">Ownership and Smart Pointers</h3> |
| 1979 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1980 | <p>Prefer to have single, fixed owners for dynamically |
| 1981 | allocated objects. Prefer to transfer ownership with smart |
| 1982 | pointers.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1983 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 1984 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 1985 | <p>"Ownership" is a bookkeeping technique for managing |
| 1986 | dynamically allocated memory (and other resources). The |
| 1987 | owner of a dynamically allocated object is an object or |
| 1988 | function that is responsible for ensuring that it is |
| 1989 | deleted when no longer needed. Ownership can sometimes be |
| 1990 | shared, in which case the last owner is typically |
| 1991 | responsible for deleting it. Even when ownership is not |
| 1992 | shared, it can be transferred from one piece of code to |
| 1993 | another.</p> |
| 1994 | |
| 1995 | <p>"Smart" pointers are classes that act like pointers, |
| 1996 | e.g. by overloading the <code>*</code> and |
| 1997 | <code>-></code> operators. Some smart pointer types |
| 1998 | can be used to automate ownership bookkeeping, to ensure |
| 1999 | these responsibilities are met. |
| 2000 | <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr"> |
| 2001 | <code>std::unique_ptr</code></a> is a smart pointer type |
| 2002 | introduced in C++11, which expresses exclusive ownership |
| 2003 | of a dynamically allocated object; the object is deleted |
| 2004 | when the <code>std::unique_ptr</code> goes out of scope. |
| 2005 | It cannot be copied, but can be <em>moved</em> to |
| 2006 | represent ownership transfer. |
| 2007 | <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr"> |
| 2008 | <code>std::shared_ptr</code></a> is a smart pointer type |
| 2009 | that expresses shared ownership of |
| 2010 | a dynamically allocated object. <code>std::shared_ptr</code>s |
| 2011 | can be copied; ownership of the object is shared among |
| 2012 | all copies, and the object is deleted when the last |
| 2013 | <code>std::shared_ptr</code> is destroyed. </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2014 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2015 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2016 | <ul> |
| 2017 | <li>It's virtually impossible to manage dynamically |
| 2018 | allocated memory without some sort of ownership |
| 2019 | logic.</li> |
| 2020 | |
| 2021 | <li>Transferring ownership of an object can be cheaper |
| 2022 | than copying it (if copying it is even possible).</li> |
| 2023 | |
| 2024 | <li>Transferring ownership can be simpler than |
| 2025 | 'borrowing' a pointer or reference, because it reduces |
| 2026 | the need to coordinate the lifetime of the object |
| 2027 | between the two users.</li> |
| 2028 | |
| 2029 | <li>Smart pointers can improve readability by making |
| 2030 | ownership logic explicit, self-documenting, and |
| 2031 | unambiguous.</li> |
| 2032 | |
| 2033 | <li>Smart pointers can eliminate manual ownership |
| 2034 | bookkeeping, simplifying the code and ruling out large |
| 2035 | classes of errors.</li> |
| 2036 | |
| 2037 | <li>For const objects, shared ownership can be a simple |
| 2038 | and efficient alternative to deep copying.</li> |
| 2039 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2040 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2041 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2042 | <ul> |
| 2043 | <li>Ownership must be represented and transferred via |
| 2044 | pointers (whether smart or plain). Pointer semantics |
| 2045 | are more complicated than value semantics, especially |
| 2046 | in APIs: you have to worry not just about ownership, |
| 2047 | but also aliasing, lifetime, and mutability, among |
| 2048 | other issues.</li> |
| 2049 | |
| 2050 | <li>The performance costs of value semantics are often |
| 2051 | overestimated, so the performance benefits of ownership |
| 2052 | transfer might not justify the readability and |
| 2053 | complexity costs.</li> |
| 2054 | |
| 2055 | <li>APIs that transfer ownership force their clients |
| 2056 | into a single memory management model.</li> |
| 2057 | |
| 2058 | <li>Code using smart pointers is less explicit about |
| 2059 | where the resource releases take place.</li> |
| 2060 | |
| 2061 | <li><code>std::unique_ptr</code> expresses ownership |
| 2062 | transfer using C++11's move semantics, which are |
| 2063 | relatively new and may confuse some programmers.</li> |
| 2064 | |
| 2065 | <li>Shared ownership can be a tempting alternative to |
| 2066 | careful ownership design, obfuscating the design of a |
| 2067 | system.</li> |
| 2068 | |
| 2069 | <li>Shared ownership requires explicit bookkeeping at |
| 2070 | run-time, which can be costly.</li> |
| 2071 | |
| 2072 | <li>In some cases (e.g. cyclic references), objects |
| 2073 | with shared ownership may never be deleted.</li> |
| 2074 | |
| 2075 | <li>Smart pointers are not perfect substitutes for |
| 2076 | plain pointers.</li> |
| 2077 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2078 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2079 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2080 | <p>If dynamic allocation is necessary, prefer to keep |
| 2081 | ownership with the code that allocated it. If other code |
| 2082 | needs access to the object, consider passing it a copy, |
| 2083 | or passing a pointer or reference without transferring |
| 2084 | ownership. Prefer to use <code>std::unique_ptr</code> to |
| 2085 | make ownership transfer explicit. For example:</p> |
| 2086 | |
| 2087 | <pre>std::unique_ptr<Foo> FooFactory(); |
| 2088 | void FooConsumer(std::unique_ptr<Foo> ptr); |
| 2089 | </pre> |
| 2090 | |
| 2091 | |
| 2092 | |
| 2093 | <p>Do not design your code to use shared ownership |
| 2094 | without a very good reason. One such reason is to avoid |
| 2095 | expensive copy operations, but you should only do this if |
| 2096 | the performance benefits are significant, and the |
| 2097 | underlying object is immutable (i.e. |
| 2098 | <code>std::shared_ptr<const Foo></code>). If you |
| 2099 | do use shared ownership, prefer to use |
| 2100 | <code>std::shared_ptr</code>.</p> |
| 2101 | |
| 2102 | <p>Never use <code>std::auto_ptr</code>. Instead, use |
| 2103 | <code>std::unique_ptr</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2104 | |
| 2105 | <h3 id="cpplint">cpplint</h3> |
| 2106 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2107 | <p>Use <code>cpplint.py</code> to detect style errors.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2108 | |
| 2109 | <p><code>cpplint.py</code> |
| 2110 | is a tool that reads a source file and identifies many |
| 2111 | style errors. It is not perfect, and has both false |
| 2112 | positives and false negatives, but it is still a valuable |
| 2113 | tool. False positives can be ignored by putting <code>// |
| 2114 | NOLINT</code> at the end of the line or |
| 2115 | <code>// NOLINTNEXTLINE</code> in the previous line.</p> |
| 2116 | |
| 2117 | |
| 2118 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2119 | <div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2120 | <p>Some projects have instructions on |
| 2121 | how to run <code>cpplint.py</code> from their project |
| 2122 | tools. If the project you are contributing to does not, |
| 2123 | you can download |
| 2124 | <a href="https://raw.githubusercontent.com/google/styleguide/gh-pages/cpplint/cpplint.py"> |
| 2125 | <code>cpplint.py</code></a> separately.</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2126 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2127 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2128 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2129 | |
| 2130 | <h2 id="Other_C++_Features">Other C++ Features</h2> |
| 2131 | |
| 2132 | <h3 id="Rvalue_references">Rvalue References</h3> |
| 2133 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2134 | <p>Use rvalue references to:</p> |
| 2135 | <ul> |
| 2136 | <li>Define move constructors and move assignment operators.</li> |
| 2137 | |
| 2138 | <li>Define <a href="#Function_Overloading">overload sets</a> with |
| 2139 | const& and && variants if you have evidence that this |
| 2140 | provides meaningfully better performance than passing by value, |
| 2141 | or if you're writing low-overhead generic code that needs to support |
| 2142 | arbitrary types. Beware combinatorial overload sets, that is, seldom |
| 2143 | overload more than one parameter.</li> |
| 2144 | |
| 2145 | <li>Support 'perfect forwarding' in generic code.</li> |
| 2146 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2147 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2148 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2149 | <p> Rvalue references |
| 2150 | are a type of reference that can only bind to temporary |
| 2151 | objects. The syntax is similar to traditional reference |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2152 | syntax. For example, <code>void f(std::string&& |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2153 | s);</code> declares a function whose argument is an |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2154 | rvalue reference to a std::string.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2155 | |
| 2156 | <p id="Forwarding_references"> When the token '&&' is applied to |
| 2157 | an unqualified template argument in a function |
| 2158 | parameter, special template argument deduction |
| 2159 | rules apply. Such a reference is called forwarding reference.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2160 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2161 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2162 | <ul> |
| 2163 | <li>Defining a move constructor (a constructor taking |
| 2164 | an rvalue reference to the class type) makes it |
| 2165 | possible to move a value instead of copying it. If |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2166 | <code>v1</code> is a <code>std::vector<std::string></code>, |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2167 | for example, then <code>auto v2(std::move(v1))</code> |
| 2168 | will probably just result in some simple pointer |
| 2169 | manipulation instead of copying a large amount of data. |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2170 | In many cases this can result in a major performance |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2171 | improvement.</li> |
| 2172 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2173 | <li>Rvalue references make it possible to implement |
| 2174 | types that are movable but not copyable, which can be |
| 2175 | useful for types that have no sensible definition of |
| 2176 | copying but where you might still want to pass them as |
| 2177 | function arguments, put them in containers, etc.</li> |
| 2178 | |
| 2179 | <li><code>std::move</code> is necessary to make |
| 2180 | effective use of some standard-library types, such as |
| 2181 | <code>std::unique_ptr</code>.</li> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2182 | |
| 2183 | <li><a href="#Forwarding_references">Forwarding references</a> which |
| 2184 | use the rvalue reference token, make it possible to write a |
| 2185 | generic function wrapper that forwards its arguments to |
| 2186 | another function, and works whether or not its |
| 2187 | arguments are temporary objects and/or const. |
| 2188 | This is called 'perfect forwarding'.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2189 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2190 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2191 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2192 | <ul> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2193 | <li>Rvalue references are not yet widely understood. Rules like reference |
| 2194 | collapsing and the special deduction rule for forwarding references |
| 2195 | are somewhat obscure.</li> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2196 | |
| 2197 | <li>Rvalue references are often misused. Using rvalue |
| 2198 | references is counter-intuitive in signatures where the argument is expected |
| 2199 | to have a valid specified state after the function call, or where no move |
| 2200 | operation is performed.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2201 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2202 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2203 | <p class="decision"></p> |
| 2204 | <p>You may use rvalue references to define move constructors and move |
| 2205 | assignment operators (as described in |
| 2206 | <a href="#Copyable_Movable_Types">Copyable and Movable Types</a>). See the |
| 2207 | <a href="primer#copying_moving">C++ Primer</a> for more information about |
| 2208 | move semantics and <code>std::move</code>.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2209 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2210 | <p>You may use rvalue references to define pairs of overloads, one taking |
| 2211 | <code>Foo&&</code> and the other taking <code>const Foo&</code>. |
| 2212 | Usually the preferred solution is just to pass by value, but an overloaded pair |
| 2213 | of functions sometimes yields better performance and is sometimes necessary in |
| 2214 | generic code that needs to support a wide variety of types. As always: if |
| 2215 | you're writing more complicated code for the sake of performance, make sure you |
| 2216 | have evidence that it actually helps.</p> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2217 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2218 | <p>You may use forwarding references in conjunction with <code> |
| 2219 | <a href="http://en.cppreference.com/w/cpp/utility/forward">std::forward</a></code>, |
| 2220 | to support perfect forwarding.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2221 | |
| 2222 | <h3 id="Friends">Friends</h3> |
| 2223 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2224 | <p>We allow use of <code>friend</code> classes and functions, |
| 2225 | within reason.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2226 | |
| 2227 | <p>Friends should usually be defined in the same file so |
| 2228 | that the reader does not have to look in another file to |
| 2229 | find uses of the private members of a class. A common use |
| 2230 | of <code>friend</code> is to have a |
| 2231 | <code>FooBuilder</code> class be a friend of |
| 2232 | <code>Foo</code> so that it can construct the inner state |
| 2233 | of <code>Foo</code> correctly, without exposing this |
| 2234 | state to the world. In some cases it may be useful to |
| 2235 | make a unittest class a friend of the class it tests.</p> |
| 2236 | |
| 2237 | <p>Friends extend, but do not break, the encapsulation |
| 2238 | boundary of a class. In some cases this is better than |
| 2239 | making a member public when you want to give only one |
| 2240 | other class access to it. However, most classes should |
| 2241 | interact with other classes solely through their public |
| 2242 | members.</p> |
| 2243 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2244 | <h3 id="Exceptions">Exceptions</h3> |
| 2245 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2246 | <p>We do not use C++ exceptions.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2247 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2248 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2249 | <ul> |
| 2250 | <li>Exceptions allow higher levels of an application to |
| 2251 | decide how to handle "can't happen" failures in deeply |
| 2252 | nested functions, without the obscuring and error-prone |
| 2253 | bookkeeping of error codes.</li> |
| 2254 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2255 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2256 | |
| 2257 | <div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2258 | <li>Exceptions are used by most other |
| 2259 | modern languages. Using them in C++ would make it more |
| 2260 | consistent with Python, Java, and the C++ that others |
| 2261 | are familiar with.</li> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2262 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2263 | |
| 2264 | <li>Some third-party C++ libraries use exceptions, and |
| 2265 | turning them off internally makes it harder to |
| 2266 | integrate with those libraries.</li> |
| 2267 | |
| 2268 | <li>Exceptions are the only way for a constructor to |
| 2269 | fail. We can simulate this with a factory function or |
| 2270 | an <code>Init()</code> method, but these require heap |
| 2271 | allocation or a new "invalid" state, respectively.</li> |
| 2272 | |
| 2273 | <li>Exceptions are really handy in testing |
| 2274 | frameworks.</li> |
| 2275 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2276 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2277 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2278 | <ul> |
| 2279 | <li>When you add a <code>throw</code> statement to an |
| 2280 | existing function, you must examine all of its |
| 2281 | transitive callers. Either they must make at least the |
| 2282 | basic exception safety guarantee, or they must never |
| 2283 | catch the exception and be happy with the program |
| 2284 | terminating as a result. For instance, if |
| 2285 | <code>f()</code> calls <code>g()</code> calls |
| 2286 | <code>h()</code>, and <code>h</code> throws an |
| 2287 | exception that <code>f</code> catches, <code>g</code> |
| 2288 | has to be careful or it may not clean up properly.</li> |
| 2289 | |
| 2290 | <li>More generally, exceptions make the control flow of |
| 2291 | programs difficult to evaluate by looking at code: |
| 2292 | functions may return in places you don't expect. This |
| 2293 | causes maintainability and debugging difficulties. You |
| 2294 | can minimize this cost via some rules on how and where |
| 2295 | exceptions can be used, but at the cost of more that a |
| 2296 | developer needs to know and understand.</li> |
| 2297 | |
| 2298 | <li>Exception safety requires both RAII and different |
| 2299 | coding practices. Lots of supporting machinery is |
| 2300 | needed to make writing correct exception-safe code |
| 2301 | easy. Further, to avoid requiring readers to understand |
| 2302 | the entire call graph, exception-safe code must isolate |
| 2303 | logic that writes to persistent state into a "commit" |
| 2304 | phase. This will have both benefits and costs (perhaps |
| 2305 | where you're forced to obfuscate code to isolate the |
| 2306 | commit). Allowing exceptions would force us to always |
| 2307 | pay those costs even when they're not worth it.</li> |
| 2308 | |
| 2309 | <li>Turning on exceptions adds data to each binary |
| 2310 | produced, increasing compile time (probably slightly) |
| 2311 | and possibly increasing address space pressure. |
| 2312 | </li> |
| 2313 | |
| 2314 | <li>The availability of exceptions may encourage |
| 2315 | developers to throw them when they are not appropriate |
| 2316 | or recover from them when it's not safe to do so. For |
| 2317 | example, invalid user input should not cause exceptions |
| 2318 | to be thrown. We would need to make the style guide |
| 2319 | even longer to document these restrictions!</li> |
| 2320 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2321 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2322 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2323 | <p>On their face, the benefits of using exceptions |
| 2324 | outweigh the costs, especially in new projects. However, |
| 2325 | for existing code, the introduction of exceptions has |
| 2326 | implications on all dependent code. If exceptions can be |
| 2327 | propagated beyond a new project, it also becomes |
| 2328 | problematic to integrate the new project into existing |
| 2329 | exception-free code. Because most existing C++ code at |
| 2330 | Google is not prepared to deal with exceptions, it is |
| 2331 | comparatively difficult to adopt new code that generates |
| 2332 | exceptions.</p> |
| 2333 | |
| 2334 | <p>Given that Google's existing code is not |
| 2335 | exception-tolerant, the costs of using exceptions are |
| 2336 | somewhat greater than the costs in a new project. The |
| 2337 | conversion process would be slow and error-prone. We |
| 2338 | don't believe that the available alternatives to |
| 2339 | exceptions, such as error codes and assertions, introduce |
| 2340 | a significant burden. </p> |
| 2341 | |
| 2342 | <p>Our advice against using exceptions is not predicated |
| 2343 | on philosophical or moral grounds, but practical ones. |
| 2344 | Because we'd like to use our open-source |
| 2345 | projects at Google and it's difficult to do so if those |
| 2346 | projects use exceptions, we need to advise against |
| 2347 | exceptions in Google open-source projects as well. |
| 2348 | Things would probably be different if we had to do it all |
| 2349 | over again from scratch.</p> |
| 2350 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2351 | <p>This prohibition also applies to the exception handling related |
| 2352 | features added in C++11, such as |
| 2353 | <code>std::exception_ptr</code> and |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2354 | <code>std::nested_exception</code>.</p> |
| 2355 | |
| 2356 | <p>There is an <a href="#Windows_Code">exception</a> to |
| 2357 | this rule (no pun intended) for Windows code.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2358 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2359 | <h3 id="noexcept"><code>noexcept</code></h3> |
| 2360 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2361 | <p>Specify <code>noexcept</code> when it is useful and correct.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2362 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2363 | <p class="definition"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2364 | <p>The <code>noexcept</code> specifier is used to specify whether |
| 2365 | a function will throw exceptions or not. If an exception |
| 2366 | escapes from a function marked <code>noexcept</code>, the program |
| 2367 | crashes via <code>std::terminate</code>.</p> |
| 2368 | |
| 2369 | <p>The <code>noexcept</code> operator performs a compile-time |
| 2370 | check that returns true if an expression is declared to not |
| 2371 | throw any exceptions.</p> |
| 2372 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2373 | <p class="pros"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2374 | <ul> |
| 2375 | <li>Specifying move constructors as <code>noexcept</code> |
| 2376 | improves performance in some cases, e.g. |
| 2377 | <code>std::vector<T>::resize()</code> moves rather than |
| 2378 | copies the objects if T's move constructor is |
| 2379 | <code>noexcept</code>.</li> |
| 2380 | |
| 2381 | <li>Specifying <code>noexcept</code> on a function can |
| 2382 | trigger compiler optimizations in environments where |
| 2383 | exceptions are enabled, e.g. compiler does not have to |
| 2384 | generate extra code for stack-unwinding, if it knows |
| 2385 | that no exceptions can be thrown due to a |
| 2386 | <code>noexcept</code> specifier.</li> |
| 2387 | </ul> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2388 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2389 | <p class="cons"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2390 | <ul> |
| 2391 | <li> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2392 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2393 | In projects following this guide |
| 2394 | that have exceptions disabled it is hard |
| 2395 | to ensure that <code>noexcept</code> |
| 2396 | specifiers are correct, and hard to define what |
| 2397 | correctness even means.</li> |
| 2398 | |
| 2399 | <li>It's hard, if not impossible, to undo <code>noexcept</code> |
| 2400 | because it eliminates a guarantee that callers may be relying |
| 2401 | on, in ways that are hard to detect.</li> |
| 2402 | </ul> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2403 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2404 | <p class="decision"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2405 | <p>You may use <code>noexcept</code> when it is useful for |
| 2406 | performance if it accurately reflects the intended semantics |
| 2407 | of your function, i.e. that if an exception is somehow thrown |
| 2408 | from within the function body then it represents a fatal error. |
| 2409 | You can assume that <code>noexcept</code> on move constructors |
| 2410 | has a meaningful performance benefit. If you think |
| 2411 | there is significant performance benefit from specifying |
| 2412 | <code>noexcept</code> on some other function, please discuss it |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2413 | with |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2414 | your project leads.</p> |
| 2415 | |
| 2416 | <p>Prefer unconditional <code>noexcept</code> if exceptions are |
| 2417 | completely disabled (i.e. most Google C++ environments). |
| 2418 | Otherwise, use conditional <code>noexcept</code> specifiers |
| 2419 | with simple conditions, in ways that evaluate false only in |
| 2420 | the few cases where the function could potentially throw. |
| 2421 | The tests might include type traits check on whether the |
| 2422 | involved operation might throw (e.g. |
| 2423 | <code>std::is_nothrow_move_constructible</code> for |
| 2424 | move-constructing objects), or on whether allocation can throw |
| 2425 | (e.g. <code>absl::default_allocator_is_nothrow</code> for |
| 2426 | standard default allocation). Note in many cases the only |
| 2427 | possible cause for an exception is allocation failure (we |
| 2428 | believe move constructors should not throw except due to |
| 2429 | allocation failure), and there are many applications where it’s |
| 2430 | appropriate to treat memory exhaustion as a fatal error rather |
| 2431 | than an exceptional condition that your program should attempt |
| 2432 | to recover from. Even for other |
| 2433 | potential failures you should prioritize interface simplicity |
| 2434 | over supporting all possible exception throwing scenarios: |
| 2435 | instead of writing a complicated <code>noexcept</code> clause |
| 2436 | that depends on whether a hash function can throw, for example, |
| 2437 | simply document that your component doesn’t support hash |
| 2438 | functions throwing and make it unconditionally |
| 2439 | <code>noexcept</code>.</p> |
| 2440 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2441 | <h3 id="Run-Time_Type_Information__RTTI_">Run-Time Type |
| 2442 | Information (RTTI)</h3> |
| 2443 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2444 | <p>Avoid using Run Time Type Information (RTTI).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2445 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2446 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2447 | <p> RTTI allows a |
| 2448 | programmer to query the C++ class of an object at run |
| 2449 | time. This is done by use of <code>typeid</code> or |
| 2450 | <code>dynamic_cast</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2451 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2452 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2453 | <p>The standard alternatives to RTTI (described below) |
| 2454 | require modification or redesign of the class hierarchy |
| 2455 | in question. Sometimes such modifications are infeasible |
| 2456 | or undesirable, particularly in widely-used or mature |
| 2457 | code.</p> |
| 2458 | |
| 2459 | <p>RTTI can be useful in some unit tests. For example, it |
| 2460 | is useful in tests of factory classes where the test has |
| 2461 | to verify that a newly created object has the expected |
| 2462 | dynamic type. It is also useful in managing the |
| 2463 | relationship between objects and their mocks.</p> |
| 2464 | |
| 2465 | <p>RTTI is useful when considering multiple abstract |
| 2466 | objects. Consider</p> |
| 2467 | |
| 2468 | <pre>bool Base::Equal(Base* other) = 0; |
| 2469 | bool Derived::Equal(Base* other) { |
| 2470 | Derived* that = dynamic_cast<Derived*>(other); |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2471 | if (that == nullptr) |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2472 | return false; |
| 2473 | ... |
| 2474 | } |
| 2475 | </pre> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2476 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2477 | <p class="cons"></p> |
| 2478 | <p>Querying the type of an object at run-time frequently |
| 2479 | means a design problem. Needing to know the type of an |
| 2480 | object at runtime is often an indication that the design |
| 2481 | of your class hierarchy is flawed.</p> |
| 2482 | |
| 2483 | <p>Undisciplined use of RTTI makes code hard to maintain. |
| 2484 | It can lead to type-based decision trees or switch |
| 2485 | statements scattered throughout the code, all of which |
| 2486 | must be examined when making further changes.</p> |
| 2487 | |
| 2488 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2489 | <p>RTTI has legitimate uses but is prone to abuse, so you |
| 2490 | must be careful when using it. You may use it freely in |
| 2491 | unittests, but avoid it when possible in other code. In |
| 2492 | particular, think twice before using RTTI in new code. If |
| 2493 | you find yourself needing to write code that behaves |
| 2494 | differently based on the class of an object, consider one |
| 2495 | of the following alternatives to querying the type:</p> |
| 2496 | |
| 2497 | <ul> |
| 2498 | <li>Virtual methods are the preferred way of executing |
| 2499 | different code paths depending on a specific subclass |
| 2500 | type. This puts the work within the object itself.</li> |
| 2501 | |
| 2502 | <li>If the work belongs outside the object and instead |
| 2503 | in some processing code, consider a double-dispatch |
| 2504 | solution, such as the Visitor design pattern. This |
| 2505 | allows a facility outside the object itself to |
| 2506 | determine the type of class using the built-in type |
| 2507 | system.</li> |
| 2508 | </ul> |
| 2509 | |
| 2510 | <p>When the logic of a program guarantees that a given |
| 2511 | instance of a base class is in fact an instance of a |
| 2512 | particular derived class, then a |
| 2513 | <code>dynamic_cast</code> may be used freely on the |
| 2514 | object. Usually one |
| 2515 | can use a <code>static_cast</code> as an alternative in |
| 2516 | such situations.</p> |
| 2517 | |
| 2518 | <p>Decision trees based on type are a strong indication |
| 2519 | that your code is on the wrong track.</p> |
| 2520 | |
| 2521 | <pre class="badcode">if (typeid(*data) == typeid(D1)) { |
| 2522 | ... |
| 2523 | } else if (typeid(*data) == typeid(D2)) { |
| 2524 | ... |
| 2525 | } else if (typeid(*data) == typeid(D3)) { |
| 2526 | ... |
| 2527 | </pre> |
| 2528 | |
| 2529 | <p>Code such as this usually breaks when additional |
| 2530 | subclasses are added to the class hierarchy. Moreover, |
| 2531 | when properties of a subclass change, it is difficult to |
| 2532 | find and modify all the affected code segments.</p> |
| 2533 | |
| 2534 | <p>Do not hand-implement an RTTI-like workaround. The |
| 2535 | arguments against RTTI apply just as much to workarounds |
| 2536 | like class hierarchies with type tags. Moreover, |
| 2537 | workarounds disguise your true intent.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2538 | |
| 2539 | <h3 id="Casting">Casting</h3> |
| 2540 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2541 | <p>Use C++-style casts |
| 2542 | like <code>static_cast<float>(double_value)</code>, or brace |
| 2543 | initialization for conversion of arithmetic types like |
| 2544 | <code>int64 y = int64{1} << 42</code>. Do not use |
| 2545 | cast formats like |
| 2546 | <code>int y = (int)x</code> or <code>int y = int(x)</code> (but the latter |
| 2547 | is okay when invoking a constructor of a class type).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2548 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2549 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2550 | <p> C++ introduced a |
| 2551 | different cast system from C that distinguishes the types |
| 2552 | of cast operations.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2553 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2554 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2555 | <p>The problem with C casts is the ambiguity of the operation; |
| 2556 | sometimes you are doing a <em>conversion</em> |
| 2557 | (e.g., <code>(int)3.5</code>) and sometimes you are doing |
| 2558 | a <em>cast</em> (e.g., <code>(int)"hello"</code>). Brace |
| 2559 | initialization and C++ casts can often help avoid this |
| 2560 | ambiguity. Additionally, C++ casts are more visible when searching for |
| 2561 | them.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2562 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2563 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2564 | <p>The C++-style cast syntax is verbose and cumbersome.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2565 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2566 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2567 | <p>Do not use C-style casts. Instead, use these C++-style casts when |
| 2568 | explicit type conversion is necessary. </p> |
| 2569 | |
| 2570 | <ul> |
| 2571 | <li>Use brace initialization to convert arithmetic types |
| 2572 | (e.g. <code>int64{x}</code>). This is the safest approach because code |
| 2573 | will not compile if conversion can result in information loss. The |
| 2574 | syntax is also concise.</li> |
| 2575 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2576 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2577 | |
| 2578 | <li>Use <code>static_cast</code> as the equivalent of a C-style cast |
| 2579 | that does value conversion, when you need to |
| 2580 | explicitly up-cast a pointer from a class to its superclass, or when |
| 2581 | you need to explicitly cast a pointer from a superclass to a |
| 2582 | subclass. In this last case, you must be sure your object is |
| 2583 | actually an instance of the subclass.</li> |
| 2584 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2585 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2586 | |
| 2587 | <li>Use <code>const_cast</code> to remove the |
| 2588 | <code>const</code> qualifier (see <a href="#Use_of_const">const</a>).</li> |
| 2589 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2590 | <li>Use <code>reinterpret_cast</code> to do unsafe conversions of |
| 2591 | pointer types to and from integer and other pointer |
| 2592 | types. Use this |
| 2593 | only if you know what you are doing and you understand the aliasing |
| 2594 | issues. Also, consider the alternative |
| 2595 | <code>absl::bit_cast</code>.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2596 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2597 | <li>Use <code>absl::bit_cast</code> to interpret the raw bits of a |
| 2598 | value using a different type of the same size (a type pun), such as |
| 2599 | interpreting the bits of a <code>double</code> as |
| 2600 | <code>int64</code>.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2601 | </ul> |
| 2602 | |
| 2603 | <p>See the <a href="#Run-Time_Type_Information__RTTI_"> |
| 2604 | RTTI section</a> for guidance on the use of |
| 2605 | <code>dynamic_cast</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2606 | |
| 2607 | <h3 id="Streams">Streams</h3> |
| 2608 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2609 | <p>Use streams where appropriate, and stick to "simple" |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2610 | usages. Overload <code><<</code> for streaming only for types |
| 2611 | representing values, and write only the user-visible value, not any |
| 2612 | implementation details.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2613 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2614 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2615 | <p>Streams are the standard I/O abstraction in C++, as |
| 2616 | exemplified by the standard header <code><iostream></code>. |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2617 | They are widely used in Google code, mostly for debug logging |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2618 | and test diagnostics.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2619 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2620 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2621 | <p>The <code><<</code> and <code>>></code> |
| 2622 | stream operators provide an API for formatted I/O that |
| 2623 | is easily learned, portable, reusable, and extensible. |
| 2624 | <code>printf</code>, by contrast, doesn't even support |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2625 | <code>std::string</code>, to say nothing of user-defined types, |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2626 | and is very difficult to use portably. |
| 2627 | <code>printf</code> also obliges you to choose among the |
| 2628 | numerous slightly different versions of that function, |
| 2629 | and navigate the dozens of conversion specifiers.</p> |
| 2630 | |
| 2631 | <p>Streams provide first-class support for console I/O |
| 2632 | via <code>std::cin</code>, <code>std::cout</code>, |
| 2633 | <code>std::cerr</code>, and <code>std::clog</code>. |
| 2634 | The C APIs do as well, but are hampered by the need to |
| 2635 | manually buffer the input. </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2636 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2637 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2638 | <ul> |
| 2639 | <li>Stream formatting can be configured by mutating the |
| 2640 | state of the stream. Such mutations are persistent, so |
| 2641 | the behavior of your code can be affected by the entire |
| 2642 | previous history of the stream, unless you go out of your |
| 2643 | way to restore it to a known state every time other code |
| 2644 | might have touched it. User code can not only modify the |
| 2645 | built-in state, it can add new state variables and behaviors |
| 2646 | through a registration system.</li> |
| 2647 | |
| 2648 | <li>It is difficult to precisely control stream output, due |
| 2649 | to the above issues, the way code and data are mixed in |
| 2650 | streaming code, and the use of operator overloading (which |
| 2651 | may select a different overload than you expect).</li> |
| 2652 | |
| 2653 | <li>The practice of building up output through chains |
| 2654 | of <code><<</code> operators interferes with |
| 2655 | internationalization, because it bakes word order into the |
| 2656 | 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"> |
| 2657 | flawed</a>.</li> |
| 2658 | |
| 2659 | |
| 2660 | |
| 2661 | |
| 2662 | |
| 2663 | <li>The streams API is subtle and complex, so programmers must |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2664 | develop experience with it in order to use it effectively.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2665 | |
| 2666 | <li>Resolving the many overloads of <code><<</code> is |
| 2667 | extremely costly for the compiler. When used pervasively in a |
| 2668 | large code base, it can consume as much as 20% of the parsing |
| 2669 | and semantic analysis time.</li> |
| 2670 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2671 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2672 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2673 | <p>Use streams only when they are the best tool for the job. |
| 2674 | This is typically the case when the I/O is ad-hoc, local, |
| 2675 | human-readable, and targeted at other developers rather than |
| 2676 | end-users. Be consistent with the code around you, and with the |
| 2677 | codebase as a whole; if there's an established tool for |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 2678 | your problem, use that tool instead. |
| 2679 | In particular, |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 2680 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 2681 | logging libraries are usually a better |
| 2682 | choice than <code>std::cerr</code> or <code>std::clog</code> |
| 2683 | for diagnostic output, and the libraries in |
| 2684 | |
| 2685 | <code>absl/strings</code> |
| 2686 | or the equivalent are usually a |
| 2687 | better choice than <code>std::stringstream</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2688 | |
| 2689 | <p>Avoid using streams for I/O that faces external users or |
| 2690 | handles untrusted data. Instead, find and use the appropriate |
| 2691 | templating libraries to handle issues like internationalization, |
| 2692 | localization, and security hardening.</p> |
| 2693 | |
| 2694 | <p>If you do use streams, avoid the stateful parts of the |
| 2695 | streams API (other than error state), such as <code>imbue()</code>, |
| 2696 | <code>xalloc()</code>, and <code>register_callback()</code>. |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 2697 | Use explicit formatting functions (see e.g. |
| 2698 | |
| 2699 | <code>absl/strings</code>) |
| 2700 | rather than |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2701 | stream manipulators or formatting flags to control formatting |
| 2702 | details such as number base, precision, or padding.</p> |
| 2703 | |
| 2704 | <p>Overload <code><<</code> as a streaming operator |
| 2705 | for your type only if your type represents a value, and |
| 2706 | <code><<</code> writes out a human-readable string |
| 2707 | representation of that value. Avoid exposing implementation |
| 2708 | details in the output of <code><<</code>; if you need to print |
| 2709 | object internals for debugging, use named functions instead |
| 2710 | (a method named <code>DebugString()</code> is the most common |
| 2711 | convention).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2712 | |
| 2713 | <h3 id="Preincrement_and_Predecrement">Preincrement and Predecrement</h3> |
| 2714 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2715 | <p>Use prefix form (<code>++i</code>) of the increment and |
| 2716 | decrement operators with iterators and other template |
| 2717 | objects.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2718 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2719 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2720 | <p> When a variable |
| 2721 | is incremented (<code>++i</code> or <code>i++</code>) or |
| 2722 | decremented (<code>--i</code> or <code>i--</code>) and |
| 2723 | the value of the expression is not used, one must decide |
| 2724 | whether to preincrement (decrement) or postincrement |
| 2725 | (decrement).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2726 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2727 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2728 | <p>When the return value is ignored, the "pre" form |
| 2729 | (<code>++i</code>) is never less efficient than the |
| 2730 | "post" form (<code>i++</code>), and is often more |
| 2731 | efficient. This is because post-increment (or decrement) |
| 2732 | requires a copy of <code>i</code> to be made, which is |
| 2733 | the value of the expression. If <code>i</code> is an |
| 2734 | iterator or other non-scalar type, copying <code>i</code> |
| 2735 | could be expensive. Since the two types of increment |
| 2736 | behave the same when the value is ignored, why not just |
| 2737 | always pre-increment?</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2738 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2739 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2740 | <p>The tradition developed, in C, of using post-increment |
| 2741 | when the expression value is not used, especially in |
| 2742 | <code>for</code> loops. Some find post-increment easier |
| 2743 | to read, since the "subject" (<code>i</code>) precedes |
| 2744 | the "verb" (<code>++</code>), just like in English.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2745 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2746 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2747 | <p> For simple scalar |
| 2748 | (non-object) values there is no reason to prefer one form |
| 2749 | and we allow either. For iterators and other template |
| 2750 | types, use pre-increment.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2751 | |
| 2752 | <h3 id="Use_of_const">Use of const</h3> |
| 2753 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 2754 | <p>In APIs, use <code>const</code> whenever it makes sense. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2755 | <code>constexpr</code> is a better choice for some uses of |
| 2756 | const.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2757 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2758 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2759 | <p> Declared variables and parameters can be preceded |
| 2760 | by the keyword <code>const</code> to indicate the variables |
| 2761 | are not changed (e.g., <code>const int foo</code>). Class |
| 2762 | functions can have the <code>const</code> qualifier to |
| 2763 | indicate the function does not change the state of the |
| 2764 | class member variables (e.g., <code>class Foo { int |
| 2765 | Bar(char c) const; };</code>).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2766 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2767 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2768 | <p>Easier for people to understand how variables are being |
| 2769 | used. Allows the compiler to do better type checking, |
| 2770 | and, conceivably, generate better code. Helps people |
| 2771 | convince themselves of program correctness because they |
| 2772 | know the functions they call are limited in how they can |
| 2773 | modify your variables. Helps people know what functions |
| 2774 | are safe to use without locks in multi-threaded |
| 2775 | programs.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2776 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2777 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2778 | <p><code>const</code> is viral: if you pass a |
| 2779 | <code>const</code> variable to a function, that function |
| 2780 | must have <code>const</code> in its prototype (or the |
| 2781 | variable will need a <code>const_cast</code>). This can |
| 2782 | be a particular problem when calling library |
| 2783 | functions.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2784 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2785 | <p class="decision"></p> |
| 2786 | <p>We strongly recommend using <code>const</code> |
| 2787 | in APIs (i.e. on function parameters, methods, and |
| 2788 | non-local variables) wherever it is meaningful and accurate. This |
| 2789 | provides consistent, mostly compiler-verified documentation |
| 2790 | of what objects an operation can mutate. Having |
| 2791 | a consistent and reliable way to distinguish reads from writes |
| 2792 | is critical to writing thread-safe code, and is useful in |
| 2793 | many other contexts as well. In particular:</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2794 | |
| 2795 | <ul> |
| 2796 | <li>If a function guarantees that it will not modify an argument |
| 2797 | passed by reference or by pointer, the corresponding function parameter |
| 2798 | should be a reference-to-const (<code>const T&</code>) or |
| 2799 | pointer-to-const (<code>const T*</code>), respectively.</li> |
| 2800 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2801 | <li>For a function parameter passed by value, <code>const</code> has |
| 2802 | no effect on the caller, thus is not recommended in function |
| 2803 | declarations. See |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2804 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2805 | |
| 2806 | <a href="https://abseil.io/tips/109">TotW #109</a>. |
| 2807 | |
| 2808 | |
| 2809 | </li><li>Declare methods to be <code>const</code> unless they |
| 2810 | alter the logical state of the object (or enable the user to modify |
| 2811 | that state, e.g. by returning a non-const reference, but that's |
| 2812 | rare), or they can't safely be invoked concurrently.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2813 | </ul> |
| 2814 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2815 | <p>Using <code>const</code> on local variables is neither encouraged |
| 2816 | nor discouraged.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2817 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2818 | <p>All of a class's <code>const</code> operations should be safe |
| 2819 | to invoke concurrently with each other. If that's not feasible, the class must |
| 2820 | be clearly documented as "thread-unsafe".</p> |
| 2821 | |
| 2822 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2823 | <h4>Where to put the const</h4> |
| 2824 | |
| 2825 | <p>Some people favor the form <code>int const *foo</code> |
| 2826 | to <code>const int* foo</code>. They argue that this is |
| 2827 | more readable because it's more consistent: it keeps the |
| 2828 | rule that <code>const</code> always follows the object |
| 2829 | it's describing. However, this consistency argument |
| 2830 | doesn't apply in codebases with few deeply-nested pointer |
| 2831 | expressions since most <code>const</code> expressions |
| 2832 | have only one <code>const</code>, and it applies to the |
| 2833 | underlying value. In such cases, there's no consistency |
| 2834 | to maintain. Putting the <code>const</code> first is |
| 2835 | arguably more readable, since it follows English in |
| 2836 | putting the "adjective" (<code>const</code>) before the |
| 2837 | "noun" (<code>int</code>).</p> |
| 2838 | |
| 2839 | <p>That said, while we encourage putting |
| 2840 | <code>const</code> first, we do not require it. But be |
| 2841 | consistent with the code around you!</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2842 | |
| 2843 | <h3 id="Use_of_constexpr">Use of constexpr</h3> |
| 2844 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 2845 | <p>Use <code>constexpr</code> to define true |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2846 | constants or to ensure constant initialization.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2847 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2848 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2849 | <p> Some variables can be declared <code>constexpr</code> |
| 2850 | to indicate the variables are true constants, i.e. fixed at |
| 2851 | compilation/link time. Some functions and constructors |
| 2852 | can be declared <code>constexpr</code> which enables them |
| 2853 | to be used in defining a <code>constexpr</code> |
| 2854 | variable.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2855 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2856 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2857 | <p>Use of <code>constexpr</code> enables definition of |
| 2858 | constants with floating-point expressions rather than |
| 2859 | just literals; definition of constants of user-defined |
| 2860 | types; and definition of constants with function |
| 2861 | calls.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2862 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2863 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2864 | <p>Prematurely marking something as constexpr may cause |
| 2865 | migration problems if later on it has to be downgraded. |
| 2866 | Current restrictions on what is allowed in constexpr |
| 2867 | functions and constructors may invite obscure workarounds |
| 2868 | in these definitions.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2869 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2870 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2871 | <p><code>constexpr</code> definitions enable a more |
| 2872 | robust specification of the constant parts of an |
| 2873 | interface. Use <code>constexpr</code> to specify true |
| 2874 | constants and the functions that support their |
| 2875 | definitions. Avoid complexifying function definitions to |
| 2876 | enable their use with <code>constexpr</code>. Do not use |
| 2877 | <code>constexpr</code> to force inlining.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2878 | |
| 2879 | <h3 id="Integer_Types">Integer Types</h3> |
| 2880 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2881 | <p>Of the built-in C++ integer types, the only one used |
| 2882 | is |
| 2883 | <code>int</code>. If a program needs a variable of a |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2884 | different size, use |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2885 | a precise-width integer type from |
| 2886 | <code><stdint.h></code>, such as |
| 2887 | <code>int16_t</code>. If your variable represents a |
| 2888 | value that could ever be greater than or equal to 2^31 |
| 2889 | (2GiB), use a 64-bit type such as |
| 2890 | <code>int64_t</code>. |
| 2891 | Keep in mind that even if your value won't ever be too large |
| 2892 | for an <code>int</code>, it may be used in intermediate |
| 2893 | calculations which may require a larger type. When in doubt, |
| 2894 | choose a larger type.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2895 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2896 | <p class="definition"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2897 | <p> C++ does not specify the sizes of integer types |
| 2898 | like <code>int</code>. Typically people assume |
| 2899 | that <code>short</code> is 16 bits, |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2900 | <code>int</code> is 32 bits, <code>long</code> is 32 bits |
| 2901 | and <code>long long</code> is 64 bits.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2902 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2903 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2904 | <p>Uniformity of declaration.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2905 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2906 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2907 | <p>The sizes of integral types in C++ can vary based on |
| 2908 | compiler and architecture.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2909 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2910 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2911 | |
| 2912 | <p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2913 | <code><cstdint></code> defines types |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2914 | like <code>int16_t</code>, <code>uint32_t</code>, |
| 2915 | <code>int64_t</code>, etc. You should always use |
| 2916 | those in preference to <code>short</code>, <code>unsigned |
| 2917 | long long</code> and the like, when you need a guarantee |
| 2918 | on the size of an integer. Of the C integer types, only |
| 2919 | <code>int</code> should be used. When appropriate, you |
| 2920 | are welcome to use standard types like |
| 2921 | <code>size_t</code> and <code>ptrdiff_t</code>.</p> |
| 2922 | |
| 2923 | <p>We use <code>int</code> very often, for integers we |
| 2924 | know are not going to be too big, e.g., loop counters. |
| 2925 | Use plain old <code>int</code> for such things. You |
| 2926 | should assume that an <code>int</code> is |
| 2927 | |
| 2928 | at least 32 bits, but don't |
| 2929 | assume that it has more than 32 bits. If you need a 64-bit |
| 2930 | integer type, use |
| 2931 | <code>int64_t</code> |
| 2932 | or |
| 2933 | <code>uint64_t</code>.</p> |
| 2934 | |
| 2935 | <p>For integers we know can be "big", |
| 2936 | use |
| 2937 | <code>int64_t</code>. |
| 2938 | </p> |
| 2939 | |
| 2940 | <p>You should not use the unsigned integer types such as |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2941 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2942 | <code>uint32_t</code>, unless there is a valid |
| 2943 | reason such as representing a bit pattern rather than a |
| 2944 | number, or you need defined overflow modulo 2^N. In |
| 2945 | particular, do not use unsigned types to say a number |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2946 | will never be negative. Instead, use |
| 2947 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2948 | assertions for this.</p> |
| 2949 | |
| 2950 | |
| 2951 | |
| 2952 | <p>If your code is a container that returns a size, be |
| 2953 | sure to use a type that will accommodate any possible |
| 2954 | usage of your container. When in doubt, use a larger type |
| 2955 | rather than a smaller type.</p> |
| 2956 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2957 | <p>Use care when converting integer types. Integer conversions and |
| 2958 | promotions can cause undefined behavior, leading to security bugs and |
| 2959 | other problems.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2960 | |
| 2961 | <h4>On Unsigned Integers</h4> |
| 2962 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2963 | <p>Unsigned integers are good for representing bitfields and modular |
| 2964 | arithmetic. Because of historical accident, the C++ standard also uses |
| 2965 | unsigned integers to represent the size of containers - many members |
| 2966 | of the standards body believe this to be a mistake, but it is |
| 2967 | effectively impossible to fix at this point. The fact that unsigned |
| 2968 | arithmetic doesn't model the behavior of a simple integer, but is |
| 2969 | instead defined by the standard to model modular arithmetic (wrapping |
| 2970 | around on overflow/underflow), means that a significant class of bugs |
| 2971 | cannot be diagnosed by the compiler. In other cases, the defined |
| 2972 | behavior impedes optimization.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2973 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2974 | <p>That said, mixing signedness of integer types is responsible for an |
| 2975 | equally large class of problems. The best advice we can provide: try |
| 2976 | to use iterators and containers rather than pointers and sizes, try |
| 2977 | not to mix signedness, and try to avoid unsigned types (except for |
| 2978 | representing bitfields or modular arithmetic). Do not use an unsigned |
| 2979 | type merely to assert that a variable is non-negative.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2980 | |
| 2981 | <h3 id="64-bit_Portability">64-bit Portability</h3> |
| 2982 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2983 | <p>Code should be 64-bit and 32-bit friendly. Bear in mind |
| 2984 | problems of printing, comparisons, and structure alignment.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 2985 | |
| 2986 | <ul> |
| 2987 | <li> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 2988 | <p>Correct portable <code>printf()</code> conversion specifiers for |
| 2989 | some integral typedefs rely on macro expansions that we find unpleasant to |
| 2990 | use and impractical to require (the <code>PRI</code> macros from |
| 2991 | <code><cinttypes></code>). Unless there is no reasonable alternative |
| 2992 | for your particular case, try to avoid or even upgrade APIs that rely on the |
| 2993 | <code>printf</code> family. Instead use a library supporting typesafe numeric |
| 2994 | formatting, such as |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2995 | |
| 2996 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 2997 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/strings/str_cat.h"><code>StrCat</code></a> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 2998 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 2999 | or |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3000 | |
| 3001 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 3002 | <a href="https://github.com/abseil/abseil-cpp/blob/master/absl/strings/substitute.h"><code>Substitute</code></a> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3003 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 3004 | for fast simple conversions, |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3005 | |
| 3006 | or <a href="#Streams"><code>std::ostream</code></a>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3007 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3008 | <p>Unfortunately, the <code>PRI</code> macros are the only portable way to |
| 3009 | specify a conversion for the standard bitwidth typedefs (e.g. |
| 3010 | <code>int64_t</code>, <code>uint64_t</code>, <code>int32_t</code>, |
| 3011 | <code>uint32_t</code>, etc). |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3012 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3013 | Where possible, avoid passing arguments of types specified by bitwidth |
| 3014 | typedefs to <code>printf</code>-based APIs. Note that it is acceptable |
| 3015 | to use typedefs for which printf has dedicated length modifiers, such as |
| 3016 | <code>size_t</code> (<code>z</code>), |
| 3017 | <code>ptrdiff_t</code> (<code>t</code>), and |
| 3018 | <code>maxint_t</code> (<code>j</code>).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3019 | </li> |
| 3020 | |
| 3021 | <li>Remember that <code>sizeof(void *)</code> != |
| 3022 | <code>sizeof(int)</code>. Use <code>intptr_t</code> if |
| 3023 | you want a pointer-sized integer.</li> |
| 3024 | |
| 3025 | <li>You may need to be careful with structure |
| 3026 | alignments, particularly for structures being stored on |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3027 | disk. Any class/structure with a |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3028 | <code>int64_t</code>/<code>uint64_t</code> |
| 3029 | member will by default end up being 8-byte aligned on a |
| 3030 | 64-bit system. If you have such structures being shared |
| 3031 | on disk between 32-bit and 64-bit code, you will need |
| 3032 | to ensure that they are packed the same on both |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3033 | architectures. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3034 | Most compilers offer a way to |
| 3035 | alter structure alignment. For gcc, you can use |
| 3036 | <code>__attribute__((packed))</code>. MSVC offers |
| 3037 | <code>#pragma pack()</code> and |
| 3038 | <code>__declspec(align())</code>.</li> |
| 3039 | |
| 3040 | <li> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3041 | <p>Use <a href="#Casting">braced-initialization</a> as needed to create |
| 3042 | 64-bit constants. For example:</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3043 | |
| 3044 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3045 | <div> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3046 | <pre>int64_t my_value{0x123456789}; |
| 3047 | uint64_t my_mask{3ULL << 48}; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3048 | </pre> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3049 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3050 | </li> |
| 3051 | </ul> |
| 3052 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3053 | <h3 id="Preprocessor_Macros">Preprocessor Macros</h3> |
| 3054 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3055 | <p>Avoid defining macros, especially in headers; prefer |
| 3056 | inline functions, enums, and <code>const</code> variables. |
| 3057 | Name macros with a project-specific prefix. Do not use |
| 3058 | macros to define pieces of a C++ API.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3059 | |
| 3060 | <p>Macros mean that the code you see is not the same as |
| 3061 | the code the compiler sees. This can introduce unexpected |
| 3062 | behavior, especially since macros have global scope.</p> |
| 3063 | |
| 3064 | <p>The problems introduced by macros are especially severe |
| 3065 | when they are used to define pieces of a C++ API, |
| 3066 | and still more so for public APIs. Every error message from |
| 3067 | the compiler when developers incorrectly use that interface |
| 3068 | now must explain how the macros formed the interface. |
| 3069 | Refactoring and analysis tools have a dramatically harder |
| 3070 | time updating the interface. As a consequence, we |
| 3071 | specifically disallow using macros in this way. |
| 3072 | For example, avoid patterns like:</p> |
| 3073 | |
| 3074 | <pre class="badcode">class WOMBAT_TYPE(Foo) { |
| 3075 | // ... |
| 3076 | |
| 3077 | public: |
| 3078 | EXPAND_PUBLIC_WOMBAT_API(Foo) |
| 3079 | |
| 3080 | EXPAND_WOMBAT_COMPARISONS(Foo, ==, <) |
| 3081 | }; |
| 3082 | </pre> |
| 3083 | |
| 3084 | <p>Luckily, macros are not nearly as necessary in C++ as |
| 3085 | they are in C. Instead of using a macro to inline |
| 3086 | performance-critical code, use an inline function. |
| 3087 | Instead of using a macro to store a constant, use a |
| 3088 | <code>const</code> variable. Instead of using a macro to |
| 3089 | "abbreviate" a long variable name, use a reference. |
| 3090 | Instead of using a macro to conditionally compile code |
| 3091 | ... well, don't do that at all (except, of course, for |
| 3092 | the <code>#define</code> guards to prevent double |
| 3093 | inclusion of header files). It makes testing much more |
| 3094 | difficult.</p> |
| 3095 | |
| 3096 | <p>Macros can do things these other techniques cannot, |
| 3097 | and you do see them in the codebase, especially in the |
| 3098 | lower-level libraries. And some of their special features |
| 3099 | (like stringifying, concatenation, and so forth) are not |
| 3100 | available through the language proper. But before using a |
| 3101 | macro, consider carefully whether there's a non-macro way |
| 3102 | to achieve the same result. If you need to use a macro to |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3103 | define an interface, contact |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3104 | your project leads to request |
| 3105 | a waiver of this rule.</p> |
| 3106 | |
| 3107 | <p>The following usage pattern will avoid many problems |
| 3108 | with macros; if you use macros, follow it whenever |
| 3109 | possible:</p> |
| 3110 | |
| 3111 | <ul> |
| 3112 | <li>Don't define macros in a <code>.h</code> file.</li> |
| 3113 | |
| 3114 | <li><code>#define</code> macros right before you use |
| 3115 | them, and <code>#undef</code> them right after.</li> |
| 3116 | |
| 3117 | <li>Do not just <code>#undef</code> an existing macro |
| 3118 | before replacing it with your own; instead, pick a name |
| 3119 | that's likely to be unique.</li> |
| 3120 | |
| 3121 | <li>Try not to use macros that expand to unbalanced C++ |
| 3122 | constructs, or at least document that behavior |
| 3123 | well.</li> |
| 3124 | |
| 3125 | <li>Prefer not using <code>##</code> to generate |
| 3126 | function/class/variable names.</li> |
| 3127 | </ul> |
| 3128 | |
| 3129 | <p>Exporting macros from headers (i.e. defining them in a header |
| 3130 | without <code>#undef</code>ing them before the end of the header) |
| 3131 | is extremely strongly discouraged. If you do export a macro from a |
| 3132 | header, it must have a globally unique name. To achieve this, it |
| 3133 | must be named with a prefix consisting of your project's namespace |
| 3134 | name (but upper case). </p> |
| 3135 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3136 | <h3 id="0_and_nullptr/NULL">0 and nullptr/NULL</h3> |
| 3137 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3138 | <p>Use <code>nullptr</code> for pointers, and <code>'\0'</code> for chars (and |
| 3139 | not the <code>0</code> literal).</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3140 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 3141 | <p>For pointers (address values), use <code>nullptr</code>, as this |
| 3142 | provides type-safety.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3143 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3144 | <p>For C++03 projects, prefer <code>NULL</code> to <code>0</code>. While the |
| 3145 | values are equivalent, <code>NULL</code> looks more like a pointer to the |
| 3146 | reader, and some C++ compilers provide special definitions of <code>NULL</code> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3147 | which enable them to give useful warnings. Never use <code>NULL</code> for |
| 3148 | numeric (integer or floating-point) values.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3149 | |
| 3150 | <p>Use <code>'\0'</code> for the null character. Using the correct type makes |
| 3151 | the code more readable.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3152 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3153 | <h3 id="sizeof">sizeof</h3> |
| 3154 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3155 | <p>Prefer <code>sizeof(<var>varname</var>)</code> to |
| 3156 | <code>sizeof(<var>type</var>)</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3157 | |
| 3158 | <p>Use <code>sizeof(<var>varname</var>)</code> when you |
| 3159 | take the size of a particular variable. |
| 3160 | <code>sizeof(<var>varname</var>)</code> will update |
| 3161 | appropriately if someone changes the variable type either |
| 3162 | now or later. You may use |
| 3163 | <code>sizeof(<var>type</var>)</code> for code unrelated |
| 3164 | to any particular variable, such as code that manages an |
| 3165 | external or internal data format where a variable of an |
| 3166 | appropriate C++ type is not convenient.</p> |
| 3167 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3168 | <pre>struct data; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3169 | memset(&data, 0, sizeof(data)); |
| 3170 | </pre> |
| 3171 | |
| 3172 | <pre class="badcode">memset(&data, 0, sizeof(Struct)); |
| 3173 | </pre> |
| 3174 | |
| 3175 | <pre>if (raw_size < sizeof(int)) { |
| 3176 | LOG(ERROR) << "compressed record not big enough for count: " << raw_size; |
| 3177 | return false; |
| 3178 | } |
| 3179 | </pre> |
| 3180 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3181 | <a name="auto"></a> |
| 3182 | <h3 id="Type_deduction">Type deduction</h3> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3183 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3184 | <p>Use type deduction only if it makes the code clearer to readers who aren't |
| 3185 | familiar with the project, or if it makes the code safer. Do not use it |
| 3186 | merely to avoid the inconvenience of writing an explicit type.</p> |
| 3187 | |
| 3188 | <p class="definition"></p> |
| 3189 | |
| 3190 | <p>There are several contexts in which C++ allows (or even requires) types to |
| 3191 | be deduced by the compiler, rather than spelled out explicitly in the code:</p> |
| 3192 | <dl> |
| 3193 | <dt><a href="https://en.cppreference.com/w/cpp/language/template_argument_deduction">Function template argument deduction</a></dt> |
| 3194 | <dd>A function template can be invoked without explicit template arguments. |
| 3195 | The compiler deduces those arguments from the types of the function |
| 3196 | arguments: |
| 3197 | <pre class="neutralcode">template <typename T> |
| 3198 | void f(T t); |
| 3199 | |
| 3200 | f(0); // Invokes f<int>(0)</pre> |
| 3201 | </dd> |
| 3202 | <dt><a href="https://en.cppreference.com/w/cpp/language/auto"><code>auto</code> variable declarations</a></dt> |
| 3203 | <dd>A variable declaration can use the <code>auto</code> keyword in place |
| 3204 | of the type. The compiler deduces the type from the variable's |
| 3205 | initializer, following the same rules as function template argument |
| 3206 | deduction with the same initializer (so long as you don't use curly braces |
| 3207 | instead of parentheses). |
| 3208 | <pre class="neutralcode">auto a = 42; // a is an int |
| 3209 | auto& b = a; // b is an int& |
| 3210 | auto c = b; // c is an int |
| 3211 | auto d{42}; // d is an int, not a std::initializer_list<int> |
| 3212 | </pre> |
| 3213 | <code>auto</code> can be qualified with <code>const</code>, and can be |
| 3214 | used as part of a pointer or reference type, but it can't be used as a |
| 3215 | template argument. A rare variant of this syntax uses |
| 3216 | <code>decltype(auto)</code> instead of <code>auto</code>, in which case |
| 3217 | the deduced type is the result of applying |
| 3218 | <a href="https://en.cppreference.com/w/cpp/language/decltype"><code>decltype</code></a> |
| 3219 | to the initializer. |
| 3220 | </dd> |
| 3221 | <dt><a href="https://en.cppreference.com/w/cpp/language/function#Return_type_deduction">Function return type deduction</a></dt> |
| 3222 | <dd><code>auto</code> (and <code>decltype(auto)</code>) can also be used in |
| 3223 | place of a function return type. The compiler deduces the return type from |
| 3224 | the <code>return</code> statements in the function body, following the same |
| 3225 | rules as for variable declarations: |
| 3226 | <pre class="neutralcode">auto f() { return 0; } // The return type of f is int</pre> |
| 3227 | <a href="#Lambda_expressions">Lambda expression</a> return types can be |
| 3228 | deduced in the same way, but this is triggered by omitting the return type, |
| 3229 | rather than by an explicit <code>auto</code>. Confusingly, |
| 3230 | <a href="trailing_return">trailing return type</a> syntax for functions |
| 3231 | also uses <code>auto</code> in the return-type position, but that doesn't |
| 3232 | rely on type deduction; it's just an alternate syntax for an explicit |
| 3233 | return type. |
| 3234 | </dd> |
| 3235 | <dt><a href="https://isocpp.org/wiki/faq/cpp14-language#generic-lambdas">Generic lambdas</a></dt> |
| 3236 | <dd>A lambda expression can use the <code>auto</code> keyword in place of |
| 3237 | one or more of its parameter types. This causes the lambda's call operator |
| 3238 | to be a function template instead of an ordinary function, with a separate |
| 3239 | template parameter for each <code>auto</code> function parameter: |
| 3240 | <pre class="neutralcode">// Sort `vec` in increasing order |
| 3241 | std::sort(vec.begin(), vec.end(), [](auto lhs, auto rhs) { return lhs > rhs; });</pre> |
| 3242 | </dd> |
| 3243 | <dt><a href="https://isocpp.org/wiki/faq/cpp14-language#lambda-captures">Lambda init captures</a></dt> |
| 3244 | <dd>Lambda captures can have explicit initializers, which can be used to |
| 3245 | declare wholly new variables rather than only capturing existing ones: |
| 3246 | <pre class="neutralcode">[x = 42, y = "foo"] { ... } // x is an int, and y is a const char*</pre> |
| 3247 | This syntax doesn't allow the type to be specified; instead, it's deduced |
| 3248 | using the rules for <code>auto</code> variables. |
| 3249 | </dd> |
| 3250 | <dt><a href="https://en.cppreference.com/w/cpp/language/class_template_argument_deduction">Class template argument deduction</a></dt> |
| 3251 | <dd>See <a href="#CTAD">below</a>.</dd> |
| 3252 | <dt><a href="https://en.cppreference.com/w/cpp/language/structured_binding">Structured bindings</a></dt> |
| 3253 | <dd>When declaring a tuple, struct, or array using <code>auto</code>, you can |
| 3254 | specify names for the individual elements instead of a name for the whole |
| 3255 | object; these names are called "structured bindings", and the whole |
| 3256 | declaration is called a "structured binding declaration". This syntax |
| 3257 | provides no way of specifying the type of either the enclosing object |
| 3258 | or the individual names: |
| 3259 | <pre class="neutralcode">auto [iter, success] = my_map.insert({key, value}); |
| 3260 | if (!success) { |
| 3261 | iter->second = value; |
| 3262 | }</pre> |
| 3263 | The <code>auto</code> can also be qualified with <code>const</code>, |
| 3264 | <code>&</code>, and <code>&&</code>, but note that these qualifiers |
| 3265 | technically apply to the anonymous tuple/struct/array, rather than the |
| 3266 | individual bindings. The rules that determine the types of the bindings |
| 3267 | are quite complex; the results tend to be unsurprising, except that |
| 3268 | the binding types typically won't be references even if the declaration |
| 3269 | declares a reference (but they will usually behave like references anyway). |
| 3270 | </dd> |
| 3271 | |
| 3272 | <p>(These summaries omit many details and caveats; see the links for further |
| 3273 | information.)</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3274 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3275 | <p class="pros"></p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3276 | |
| 3277 | <ul> |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3278 | <li>C++ type names can be long and cumbersome, especially when they |
| 3279 | involve templates or namespaces.</li> |
| 3280 | <li>When a C++ type name is repeated within a single declaration or a |
| 3281 | small code region, the repetition may not be aiding readability.</li> |
| 3282 | <li>It is sometimes safer to let the type be deduced, since that avoids |
| 3283 | the possibility of unintended copies or type conversions.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3284 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3285 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3286 | <p class="cons"></p> |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3287 | <p>C++ code is usually clearer when types are explicit, |
| 3288 | especially when type deduction would depend on information from |
| 3289 | distant parts of the code. In expressions like:</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3290 | |
| 3291 | <pre class="badcode">auto foo = x.add_foo(); |
| 3292 | auto i = y.Find(key); |
| 3293 | </pre> |
| 3294 | |
| 3295 | <p>it may not be obvious what the resulting types are if the type |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3296 | of <code>y</code> isn't very well known, or if <code>y</code> was |
| 3297 | declared many lines earlier.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3298 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3299 | <p>Programmers have to understand when type deduction will or won't |
| 3300 | produce a reference type, or they'll get copies when they didn't |
| 3301 | mean to.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3302 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3303 | <p>If a deduced type is used as part of an interface, then a |
| 3304 | programmer might change its type while only intending to |
| 3305 | change its value, leading to a more radical API change |
| 3306 | than intended.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3307 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3308 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3309 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3310 | <p>The fundamental rule is: use type deduction only to make the code |
| 3311 | clearer or safer, and do not use it merely to avoid the |
| 3312 | inconvenience of writing an explicit type. When judging whether the |
| 3313 | code is clearer, keep in mind that your readers are not necessarily |
| 3314 | on your team, or familiar with your project, so types that you and |
| 3315 | your reviewer experience as as unnecessary clutter will very often |
| 3316 | provide useful information to others. For example, you can assume that |
| 3317 | the return type of <code>make_unique<Foo>()</code> is obvious, |
| 3318 | but the return type of <code>MyWidgetFactory()</code> probably isn't.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3319 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3320 | <p>These principles applies to all forms of type deduction, but the |
| 3321 | details vary, as described in the following sections.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3322 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3323 | <h4>Function template argument deduction</h4> |
| 3324 | |
| 3325 | <p>Function template argument deduction is almost always OK. Type deduction |
| 3326 | is the expected default way of interacting with function templates, |
| 3327 | because it allows function templates to act like infinite sets of ordinary |
| 3328 | function overloads. Consequently, function templates are almost always |
| 3329 | designed so that template argument deduction is clear and safe, or |
| 3330 | doesn't compile.</p> |
| 3331 | |
| 3332 | <h4>Local variable type deduction</h4> |
| 3333 | |
| 3334 | <p>For local variables, you can use type deduction to make the code clearer |
| 3335 | by eliminating type information that is obvious or irrelevant, so that |
| 3336 | the reader can focus on the meaningful parts of the code: |
| 3337 | </p><pre class="neutralcode">std::unique_ptr<WidgetWithBellsAndWhistles> widget_ptr = |
| 3338 | absl::make_unique<WidgetWithBellsAndWhistles>(arg1, arg2); |
| 3339 | absl::flat_hash_map<std::string, |
| 3340 | std::unique_ptr<WidgetWithBellsAndWhistles>>::const_iterator |
| 3341 | it = my_map_.find(key); |
| 3342 | std::array<int, 0> numbers = {4, 8, 15, 16, 23, 42};</pre> |
| 3343 | |
| 3344 | <pre class="goodcode">auto widget_ptr = absl::make_unique<WidgetWithBellsAndWhistles>(arg1, arg2); |
| 3345 | auto it = my_map_.find(key); |
| 3346 | std::array numbers = {4, 8, 15, 16, 23, 42};</pre> |
| 3347 | |
| 3348 | <p>Types sometimes contain a mixture of useful information and boilerplate, |
| 3349 | such as <code>it</code> in the example above: it's obvious that the |
| 3350 | type is an iterator, and in many contexts the container type and even the |
| 3351 | key type aren't relevant, but the type of the values is probably useful. |
| 3352 | In such situations, it's often possible to define local variables with |
| 3353 | explicit types that convey the relevant information: |
| 3354 | </p><pre class="goodcode">auto it = my_map_.find(key); |
| 3355 | if (it != my_map_.end()) { |
| 3356 | WidgetWithBellsAndWhistles& widget = *it->second; |
| 3357 | // Do stuff with `widget` |
| 3358 | }</pre> |
| 3359 | If the type is a template instance, and the parameters are |
| 3360 | boilerplate but the template itself is informative, you can use |
| 3361 | class template argument deduction to suppress the boilerplate. However, |
| 3362 | cases where this actually provides a meaningful benefit are quite rare. |
| 3363 | Note that class template argument deduction is also subject to a |
| 3364 | <a href="#CTAD">separate style rule</a>. |
| 3365 | |
| 3366 | <p>Do not use <code>decltype(auto)</code> if a simpler option will work, |
| 3367 | because it's a fairly obscure feature, so it has a high cost in code |
| 3368 | clarity.</p> |
| 3369 | |
| 3370 | <h4>Return type deduction</h4> |
| 3371 | |
| 3372 | <p>Use return type deduction (for both functions and lambdas) only if the |
| 3373 | function body has a very small number of <code>return</code> statements, |
| 3374 | and very little other code, because otherwise the reader may not be able |
| 3375 | to tell at a glance what the return type is. Furthermore, use it only |
| 3376 | if the function or lambda has a very narrow scope, because functions with |
| 3377 | deduced return types don't define abstraction boundaries: the implementation |
| 3378 | <em>is</em> the interface. In particular, public functions in header files |
| 3379 | should almost never have deduced return types.</p> |
| 3380 | |
| 3381 | <h4>Parameter type deduction</h4> |
| 3382 | |
| 3383 | <p><code>auto</code> parameter types for lambdas should be used with caution, |
| 3384 | because the actual type is determined by the code that calls the lambda, |
| 3385 | rather than by the definition of the lambda. Consequently, an explicit |
| 3386 | type will almost always be clearer unless the lambda is explicitly called |
| 3387 | very close to where it's defined (so that the reader can easily see both), |
| 3388 | or the lambda is passed to an interface so well-known that it's |
| 3389 | obvious what arguments it will eventually be called with (e.g. |
| 3390 | the <code>std::sort</code> example above).</p> |
| 3391 | |
| 3392 | <h4>Lambda init captures</h4> |
| 3393 | |
| 3394 | <p>Init captures are covered by a <a href="#Lambda_expressions">more specific |
| 3395 | style rule</a>, which largely supersedes the general rules for |
| 3396 | type deduction.</p> |
| 3397 | |
| 3398 | <h4>Structured bindings</h4> |
| 3399 | |
| 3400 | <p>Unlike other forms of type deduction, structured bindings can actually |
| 3401 | give the reader additional information, by giving meaningful names to the |
| 3402 | elements of a larger object. This means that a structured binding declaration |
| 3403 | may provide a net readability improvement over an explicit type, even in cases |
| 3404 | where <code>auto</code> would not. Structured bindings are especially |
| 3405 | beneficial when the object is a pair or tuple (as in the <code>insert</code> |
| 3406 | example above), because they don't have meaningful field names to begin with, |
| 3407 | but note that you generally <a href="#Structs_vs._Tuples">shouldn't use |
| 3408 | pairs or tuples</a> unless a pre-existing API like <code>insert</code> |
| 3409 | forces you to.</p> |
| 3410 | |
| 3411 | <p>If the object being bound is a struct, it may sometimes be helpful to |
| 3412 | provide names that are more specific to your usage, but keep in mind that |
| 3413 | this may also mean the names are less recognizable to your reader than the |
| 3414 | field names. We recommend using a comment to indicate the name of the |
| 3415 | underlying field, if it doesn't match the name of the binding, using the |
| 3416 | same syntax as for function parameter comments: |
| 3417 | </p><pre>auto [/*field_name1=*/ bound_name1, /*field_name2=*/ bound_name2] = ...</pre> |
| 3418 | As with function parameter comments, this can enable tools to detect if |
| 3419 | you get the order of the fields wrong. |
| 3420 | |
| 3421 | <h3 id="CTAD">Class template argument deduction</h3> |
| 3422 | |
| 3423 | <p>Use class template argument deduction only with templates that have |
| 3424 | explicitly opted into supporting it.</p> |
| 3425 | |
| 3426 | <p class="definition"></p> |
| 3427 | <p><a href="https://en.cppreference.com/w/cpp/language/class_template_argument_deduction">Class |
| 3428 | template argument deduction</a> (often abbreviated "CTAD") occurs when |
| 3429 | a variable is declared with a type that names a template, and the template |
| 3430 | argument list is not provided (not even empty angle brackets): |
| 3431 | </p><pre class="neutralcode">std::array a = {1, 2, 3}; // `a` is a std::array<int, 3></pre> |
| 3432 | The compiler deduces the arguments from the initializer using the |
| 3433 | template's "deduction guides", which can be explicit or implicit. |
| 3434 | |
| 3435 | <p>Explicit deduction guides look like function declarations with trailing |
| 3436 | return types, except that there's no leading <code>auto</code>, and the |
| 3437 | function name is the name of the template. For example, the above example |
| 3438 | relies on this deduction guide for <code>std::array</code>: |
| 3439 | </p><pre class="neutralcode">namespace std { |
| 3440 | template <class T, class... U> |
| 3441 | array(T, U...) -> std::array<T, 1 + sizeof...(U)>; |
| 3442 | }</pre> |
| 3443 | Constructors in a primary template (as opposed to a template specialization) |
| 3444 | also implicitly define deduction guides. |
| 3445 | |
| 3446 | <p>When you declare a variable that relies on CTAD, the compiler selects |
| 3447 | a deduction guide using the rules of constructor overload resolution, |
| 3448 | and that guide's return type becomes the type of the variable.</p> |
| 3449 | |
| 3450 | <p class="pros"></p> |
| 3451 | <p>CTAD can sometimes allow you to omit boilerplate from your code.</p> |
| 3452 | |
| 3453 | <p class="cons"></p> |
| 3454 | <p>The implicit deduction guides that are generated from constructors |
| 3455 | may have undesirable behavior, or be outright incorrect. This is |
| 3456 | particularly problematic for constructors written before CTAD was |
| 3457 | introduced in C++17, because the authors of those constructors had no |
| 3458 | way of knowing about (much less fixing) any problems that their |
| 3459 | constructors would cause for CTAD. Furthermore, adding explicit deduction |
| 3460 | guides to fix those problems might break any existing code that relies on |
| 3461 | the implicit deduction guides.</p> |
| 3462 | |
| 3463 | <p>CTAD also suffers from many of the same drawbacks as <code>auto</code>, |
| 3464 | because they are both mechanisms for deducing all or part of a variable's |
| 3465 | type from its initializer. CTAD does give the reader more information |
| 3466 | than <code>auto</code>, but it also doesn't give the reader an obvious |
| 3467 | cue that information has been omitted.</p> |
| 3468 | |
| 3469 | <p class="decision"></p> |
| 3470 | <p>Do not use CTAD with a given template unless the template's maintainers |
| 3471 | have opted into supporting use of CTAD by providing at least one explicit |
| 3472 | deduction guide (all templates in the <code>std</code> namespace are |
| 3473 | also presumed to have opted in). This should be enforced with a compiler |
| 3474 | warning if available.</p> |
| 3475 | |
| 3476 | <p>Uses of CTAD must also follow the general rules on |
| 3477 | <a href="#Type_deduction">Type deduction</a>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3478 | |
| 3479 | <h3 id="Lambda_expressions">Lambda expressions</h3> |
| 3480 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3481 | <p>Use lambda expressions where appropriate. Prefer explicit captures |
| 3482 | when the lambda will escape the current scope.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3483 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3484 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3485 | <p> Lambda expressions are a concise way of creating anonymous |
| 3486 | function objects. They're often useful when passing |
| 3487 | functions as arguments. For example:</p> |
| 3488 | |
| 3489 | <pre>std::sort(v.begin(), v.end(), [](int x, int y) { |
| 3490 | return Weight(x) < Weight(y); |
| 3491 | }); |
| 3492 | </pre> |
| 3493 | |
| 3494 | <p> They further allow capturing variables from the enclosing scope either |
| 3495 | explicitly by name, or implicitly using a default capture. Explicit captures |
| 3496 | require each variable to be listed, as |
| 3497 | either a value or reference capture:</p> |
| 3498 | |
| 3499 | <pre>int weight = 3; |
| 3500 | int sum = 0; |
| 3501 | // Captures `weight` by value and `sum` by reference. |
| 3502 | std::for_each(v.begin(), v.end(), [weight, &sum](int x) { |
| 3503 | sum += weight * x; |
| 3504 | }); |
| 3505 | </pre> |
| 3506 | |
| 3507 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3508 | <p>Default captures implicitly capture any variable referenced in the |
| 3509 | lambda body, including <code>this</code> if any members are used:</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3510 | |
| 3511 | <pre>const std::vector<int> lookup_table = ...; |
| 3512 | std::vector<int> indices = ...; |
| 3513 | // Captures `lookup_table` by reference, sorts `indices` by the value |
| 3514 | // of the associated element in `lookup_table`. |
| 3515 | std::sort(indices.begin(), indices.end(), [&](int a, int b) { |
| 3516 | return lookup_table[a] < lookup_table[b]; |
| 3517 | }); |
| 3518 | </pre> |
| 3519 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3520 | <p>A variable capture can also have an explicit initializer, which can |
| 3521 | be used for capturing move-only variables by value, or for other situations |
| 3522 | not handled by ordinary reference or value captures: |
| 3523 | </p><pre>std::unique_ptr<Foo> foo = ...; |
| 3524 | [foo = std::move(foo)] () { |
| 3525 | ... |
| 3526 | }</pre> |
| 3527 | Such captures (often called "init captures" or "generalized lambda captures") |
| 3528 | need not actually "capture" anything from the enclosing scope, or even have |
| 3529 | a name from the enclosing scope; this syntax is a fully general way to define |
| 3530 | members of a lambda object: |
| 3531 | <pre class="neutralcode">[foo = std::vector<int>({1, 2, 3})] () { |
| 3532 | ... |
| 3533 | }</pre> |
| 3534 | The type of a capture with an initializer is deduced using the same rules |
| 3535 | as <code>auto</code>. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3536 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3537 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3538 | <ul> |
| 3539 | <li>Lambdas are much more concise than other ways of |
| 3540 | defining function objects to be passed to STL |
| 3541 | algorithms, which can be a readability |
| 3542 | improvement.</li> |
| 3543 | |
| 3544 | <li>Appropriate use of default captures can remove |
| 3545 | redundancy and highlight important exceptions from |
| 3546 | the default.</li> |
| 3547 | |
| 3548 | <li>Lambdas, <code>std::function</code>, and |
| 3549 | <code>std::bind</code> can be used in combination as a |
| 3550 | general purpose callback mechanism; they make it easy |
| 3551 | to write functions that take bound functions as |
| 3552 | arguments.</li> |
| 3553 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3554 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3555 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3556 | <ul> |
| 3557 | <li>Variable capture in lambdas can be a source of dangling-pointer |
| 3558 | bugs, particularly if a lambda escapes the current scope.</li> |
| 3559 | |
| 3560 | <li>Default captures by value can be misleading because they do not prevent |
| 3561 | dangling-pointer bugs. Capturing a pointer by value doesn't cause a deep |
| 3562 | copy, so it often has the same lifetime issues as capture by reference. |
| 3563 | This is especially confusing when capturing 'this' by value, since the use |
| 3564 | of 'this' is often implicit.</li> |
| 3565 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3566 | <li>Captures actually declare new variables (whether or not the captures have |
| 3567 | initializers), but they look nothing like any other variable declaration |
| 3568 | syntax in C++. In particular, there's no place for the variable's type, |
| 3569 | or even an <code>auto</code> placeholder (although init captures can |
| 3570 | indicate it indirectly, e.g. with a cast). This can make it difficult to |
| 3571 | even recognize them as declarations.</li> |
| 3572 | |
| 3573 | <li>Init captures inherently rely on <a href="#Type_deduction">type |
| 3574 | deduction</a>, and suffer from many of the same drawbacks as |
| 3575 | <code>auto</code>, with the additional problem that the syntax doesn't |
| 3576 | even cue the reader that deduction is taking place.</li> |
| 3577 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3578 | <li>It's possible for use of lambdas to get out of |
| 3579 | hand; very long nested anonymous functions can make |
| 3580 | code harder to understand.</li> |
| 3581 | |
| 3582 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3583 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3584 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3585 | <ul> |
| 3586 | <li>Use lambda expressions where appropriate, with formatting as |
| 3587 | described <a href="#Formatting_Lambda_Expressions">below</a>.</li> |
| 3588 | <li>Prefer explicit captures if the lambda may escape the current scope. |
| 3589 | For example, instead of: |
| 3590 | <pre class="badcode">{ |
| 3591 | Foo foo; |
| 3592 | ... |
| 3593 | executor->Schedule([&] { Frobnicate(foo); }) |
| 3594 | ... |
| 3595 | } |
| 3596 | // BAD! The fact that the lambda makes use of a reference to `foo` and |
| 3597 | // possibly `this` (if `Frobnicate` is a member function) may not be |
| 3598 | // apparent on a cursory inspection. If the lambda is invoked after |
| 3599 | // the function returns, that would be bad, because both `foo` |
| 3600 | // and the enclosing object could have been destroyed. |
| 3601 | </pre> |
| 3602 | prefer to write: |
| 3603 | <pre>{ |
| 3604 | Foo foo; |
| 3605 | ... |
| 3606 | executor->Schedule([&foo] { Frobnicate(foo); }) |
| 3607 | ... |
| 3608 | } |
| 3609 | // BETTER - The compile will fail if `Frobnicate` is a member |
| 3610 | // function, and it's clearer that `foo` is dangerously captured by |
| 3611 | // reference. |
| 3612 | </pre> |
| 3613 | </li> |
| 3614 | <li>Use default capture by reference ([&]) only when the |
| 3615 | lifetime of the lambda is obviously shorter than any potential |
| 3616 | captures. |
| 3617 | </li> |
| 3618 | <li>Use default capture by value ([=]) only as a means of binding a |
| 3619 | few variables for a short lambda, where the set of captured |
| 3620 | variables is obvious at a glance. Prefer not to write long or |
| 3621 | complex lambdas with default capture by value. |
| 3622 | </li> |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3623 | <li>Use captures only to actually capture variables from the enclosing scope. |
| 3624 | Do not use captures with initializers to introduce new names, or |
| 3625 | to substantially change the meaning of an existing name. Instead, |
| 3626 | declare a new variable in the conventional way and then capture it, |
| 3627 | or avoid the lambda shorthand and define a function object explicitly.</li> |
| 3628 | <li>See the section on <a href="#Type_deduction">type deduction</a> |
| 3629 | for guidance on specifying the parameter and return types.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3630 | |
| 3631 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3632 | |
| 3633 | <h3 id="Template_metaprogramming">Template metaprogramming</h3> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3634 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3635 | <p>Avoid complicated template programming.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3636 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3637 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3638 | <p>Template metaprogramming refers to a family of techniques that |
| 3639 | exploit the fact that the C++ template instantiation mechanism is |
| 3640 | Turing complete and can be used to perform arbitrary compile-time |
| 3641 | computation in the type domain.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3642 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3643 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3644 | <p>Template metaprogramming allows extremely flexible interfaces that |
| 3645 | are type safe and high performance. Facilities like |
| 3646 | |
| 3647 | <a href="https://code.google.com/p/googletest/">Google Test</a>, |
| 3648 | <code>std::tuple</code>, <code>std::function</code>, and |
| 3649 | Boost.Spirit would be impossible without it.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3650 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3651 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3652 | <p>The techniques used in template metaprogramming are often obscure |
| 3653 | to anyone but language experts. Code that uses templates in |
| 3654 | complicated ways is often unreadable, and is hard to debug or |
| 3655 | maintain.</p> |
| 3656 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3657 | <p>Template metaprogramming often leads to extremely poor compile |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3658 | time error messages: even if an interface is simple, the complicated |
| 3659 | implementation details become visible when the user does something |
| 3660 | wrong.</p> |
| 3661 | |
| 3662 | <p>Template metaprogramming interferes with large scale refactoring by |
| 3663 | making the job of refactoring tools harder. First, the template code |
| 3664 | is expanded in multiple contexts, and it's hard to verify that the |
| 3665 | transformation makes sense in all of them. Second, some refactoring |
| 3666 | tools work with an AST that only represents the structure of the code |
| 3667 | after template expansion. It can be difficult to automatically work |
| 3668 | back to the original source construct that needs to be |
| 3669 | rewritten.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3670 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3671 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3672 | <p>Template metaprogramming sometimes allows cleaner and easier-to-use |
| 3673 | interfaces than would be possible without it, but it's also often a |
| 3674 | temptation to be overly clever. It's best used in a small number of |
| 3675 | low level components where the extra maintenance burden is spread out |
| 3676 | over a large number of uses.</p> |
| 3677 | |
| 3678 | <p>Think twice before using template metaprogramming or other |
| 3679 | complicated template techniques; think about whether the average |
| 3680 | member of your team will be able to understand your code well enough |
| 3681 | to maintain it after you switch to another project, or whether a |
| 3682 | non-C++ programmer or someone casually browsing the code base will be |
| 3683 | able to understand the error messages or trace the flow of a function |
| 3684 | they want to call. If you're using recursive template instantiations |
| 3685 | or type lists or metafunctions or expression templates, or relying on |
| 3686 | SFINAE or on the <code>sizeof</code> trick for detecting function |
| 3687 | overload resolution, then there's a good chance you've gone too |
| 3688 | far.</p> |
| 3689 | |
| 3690 | <p>If you use template metaprogramming, you should expect to put |
| 3691 | considerable effort into minimizing and isolating the complexity. You |
| 3692 | should hide metaprogramming as an implementation detail whenever |
| 3693 | possible, so that user-facing headers are readable, and you should |
| 3694 | make sure that tricky code is especially well commented. You should |
| 3695 | carefully document how the code is used, and you should say something |
| 3696 | about what the "generated" code looks like. Pay extra attention to the |
| 3697 | error messages that the compiler emits when users make mistakes. The |
| 3698 | error messages are part of your user interface, and your code should |
| 3699 | be tweaked as necessary so that the error messages are understandable |
| 3700 | and actionable from a user point of view.</p> |
| 3701 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3702 | <h3 id="Boost">Boost</h3> |
| 3703 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3704 | <p>Use only approved libraries from the Boost library |
| 3705 | collection.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3706 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3707 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3708 | <p> The |
| 3709 | <a href="https://www.boost.org/"> |
| 3710 | Boost library collection</a> is a popular collection of |
| 3711 | peer-reviewed, free, open-source C++ libraries.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3712 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3713 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3714 | <p>Boost code is generally very high-quality, is widely |
| 3715 | portable, and fills many important gaps in the C++ |
| 3716 | standard library, such as type traits and better binders.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3717 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3718 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3719 | <p>Some Boost libraries encourage coding practices which can |
| 3720 | hamper readability, such as metaprogramming and other |
| 3721 | advanced template techniques, and an excessively |
| 3722 | "functional" style of programming. </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3723 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3724 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3725 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3726 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3727 | |
| 3728 | <div> |
| 3729 | <p>In order to maintain a high level of readability for |
| 3730 | all contributors who might read and maintain code, we |
| 3731 | only allow an approved subset of Boost features. |
| 3732 | Currently, the following libraries are permitted:</p> |
| 3733 | |
| 3734 | <ul> |
| 3735 | <li> |
| 3736 | <a href="https://www.boost.org/libs/utility/call_traits.htm"> |
| 3737 | Call Traits</a> from <code>boost/call_traits.hpp</code></li> |
| 3738 | |
| 3739 | <li><a href="https://www.boost.org/libs/utility/compressed_pair.htm"> |
| 3740 | Compressed Pair</a> from <code>boost/compressed_pair.hpp</code></li> |
| 3741 | |
| 3742 | <li><a href="https://www.boost.org/libs/graph/"> |
| 3743 | The Boost Graph Library (BGL)</a> from <code>boost/graph</code>, |
| 3744 | except serialization (<code>adj_list_serialize.hpp</code>) and |
| 3745 | parallel/distributed algorithms and data structures |
| 3746 | (<code>boost/graph/parallel/*</code> and |
| 3747 | <code>boost/graph/distributed/*</code>).</li> |
| 3748 | |
| 3749 | <li><a href="https://www.boost.org/libs/property_map/"> |
| 3750 | Property Map</a> from <code>boost/property_map</code>, except |
| 3751 | parallel/distributed property maps (<code>boost/property_map/parallel/*</code>).</li> |
| 3752 | |
| 3753 | <li><a href="https://www.boost.org/libs/iterator/"> |
| 3754 | Iterator</a> from <code>boost/iterator</code></li> |
| 3755 | |
| 3756 | <li>The part of <a href="https://www.boost.org/libs/polygon/"> |
| 3757 | Polygon</a> that deals with Voronoi diagram |
| 3758 | construction and doesn't depend on the rest of |
| 3759 | Polygon: |
| 3760 | <code>boost/polygon/voronoi_builder.hpp</code>, |
| 3761 | <code>boost/polygon/voronoi_diagram.hpp</code>, and |
| 3762 | <code>boost/polygon/voronoi_geometry_type.hpp</code></li> |
| 3763 | |
| 3764 | <li><a href="https://www.boost.org/libs/bimap/"> |
| 3765 | Bimap</a> from <code>boost/bimap</code></li> |
| 3766 | |
| 3767 | <li><a href="https://www.boost.org/libs/math/doc/html/dist.html"> |
| 3768 | Statistical Distributions and Functions</a> from |
| 3769 | <code>boost/math/distributions</code></li> |
| 3770 | |
| 3771 | <li><a href="https://www.boost.org/libs/math/doc/html/special.html"> |
| 3772 | Special Functions</a> from <code>boost/math/special_functions</code></li> |
| 3773 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3774 | <li><a href="https://www.boost.org/libs/math/doc/html/root_finding.html"> |
| 3775 | Root Finding Functions</a> from <code>boost/math/tools</code></li> |
| 3776 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3777 | <li><a href="https://www.boost.org/libs/multi_index/"> |
| 3778 | Multi-index</a> from <code>boost/multi_index</code></li> |
| 3779 | |
| 3780 | <li><a href="https://www.boost.org/libs/heap/"> |
| 3781 | Heap</a> from <code>boost/heap</code></li> |
| 3782 | |
| 3783 | <li>The flat containers from |
| 3784 | <a href="https://www.boost.org/libs/container/">Container</a>: |
| 3785 | <code>boost/container/flat_map</code>, and |
| 3786 | <code>boost/container/flat_set</code></li> |
| 3787 | |
| 3788 | <li><a href="https://www.boost.org/libs/intrusive/">Intrusive</a> |
| 3789 | from <code>boost/intrusive</code>.</li> |
| 3790 | |
| 3791 | <li><a href="https://www.boost.org/libs/sort/">The |
| 3792 | <code>boost/sort</code> library</a>.</li> |
| 3793 | |
| 3794 | <li><a href="https://www.boost.org/libs/preprocessor/">Preprocessor</a> |
| 3795 | from <code>boost/preprocessor</code>.</li> |
| 3796 | </ul> |
| 3797 | |
| 3798 | <p>We are actively considering adding other Boost |
| 3799 | features to the list, so this list may be expanded in |
| 3800 | the future.</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3801 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3802 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3803 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3804 | |
| 3805 | <h3 id="std_hash">std::hash</h3> |
| 3806 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3807 | <p>Do not define specializations of <code>std::hash</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3808 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3809 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3810 | <p><code>std::hash<T></code> is the function object that the |
| 3811 | C++11 hash containers use to hash keys of type <code>T</code>, |
| 3812 | unless the user explicitly specifies a different hash function. For |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3813 | example, <code>std::unordered_map<int, std::string></code> is a hash |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3814 | map that uses <code>std::hash<int></code> to hash its keys, |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3815 | whereas <code>std::unordered_map<int, std::string, MyIntHash></code> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3816 | uses <code>MyIntHash</code>.</p> |
| 3817 | |
| 3818 | <p><code>std::hash</code> is defined for all integral, floating-point, |
| 3819 | pointer, and <code>enum</code> types, as well as some standard library |
| 3820 | types such as <code>string</code> and <code>unique_ptr</code>. Users |
| 3821 | can enable it to work for their own types by defining specializations |
| 3822 | of it for those types.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3823 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3824 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3825 | <p><code>std::hash</code> is easy to use, and simplifies the code |
| 3826 | since you don't have to name it explicitly. Specializing |
| 3827 | <code>std::hash</code> is the standard way of specifying how to |
| 3828 | hash a type, so it's what outside resources will teach, and what |
| 3829 | new engineers will expect.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3830 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3831 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3832 | <p><code>std::hash</code> is hard to specialize. It requires a lot |
| 3833 | of boilerplate code, and more importantly, it combines responsibility |
| 3834 | for identifying the hash inputs with responsibility for executing the |
| 3835 | hashing algorithm itself. The type author has to be responsible for |
| 3836 | the former, but the latter requires expertise that a type author |
| 3837 | usually doesn't have, and shouldn't need. The stakes here are high |
| 3838 | because low-quality hash functions can be security vulnerabilities, |
| 3839 | due to the emergence of |
| 3840 | <a href="https://emboss.github.io/blog/2012/12/14/breaking-murmur-hash-flooding-dos-reloaded/"> |
| 3841 | hash flooding attacks</a>.</p> |
| 3842 | |
| 3843 | <p>Even for experts, <code>std::hash</code> specializations are |
| 3844 | inordinately difficult to implement correctly for compound types, |
| 3845 | because the implementation cannot recursively call <code>std::hash</code> |
| 3846 | on data members. High-quality hash algorithms maintain large |
| 3847 | amounts of internal state, and reducing that state to the |
| 3848 | <code>size_t</code> bytes that <code>std::hash</code> |
| 3849 | returns is usually the slowest part of the computation, so it |
| 3850 | should not be done more than once.</p> |
| 3851 | |
| 3852 | <p>Due to exactly that issue, <code>std::hash</code> does not work |
| 3853 | with <code>std::pair</code> or <code>std::tuple</code>, and the |
| 3854 | language does not allow us to extend it to support them.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3855 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3856 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3857 | <p>You can use <code>std::hash</code> with the types that it supports |
| 3858 | "out of the box", but do not specialize it to support additional types. |
| 3859 | If you need a hash table with a key type that <code>std::hash</code> |
| 3860 | does not support, consider using legacy hash containers (e.g. |
| 3861 | <code>hash_map</code>) for now; they use a different default hasher, |
| 3862 | which is unaffected by this prohibition.</p> |
| 3863 | |
| 3864 | <p>If you want to use the standard hash containers anyway, you will |
| 3865 | need to specify a custom hasher for the key type, e.g.</p> |
| 3866 | <pre>std::unordered_map<MyKeyType, Value, MyKeyTypeHasher> my_map; |
| 3867 | </pre><p> |
| 3868 | Consult with the type's owners to see if there is an existing hasher |
| 3869 | that you can use; otherwise work with them to provide one, |
| 3870 | or roll your own.</p> |
| 3871 | |
| 3872 | <p>We are planning to provide a hash function that can work with any type, |
| 3873 | using a new customization mechanism that doesn't have the drawbacks of |
| 3874 | <code>std::hash</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3875 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3876 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3877 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3878 | <h3 id="Other_Features"><a name="C++11">Other C++ Features</a></h3> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3879 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3880 | <p>As with <a href="#Boost">Boost</a>, some modern C++ |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3881 | extensions encourage coding practices that hamper |
| 3882 | readability—for example by removing |
| 3883 | checked redundancy (such as type names) that may be |
| 3884 | helpful to readers, or by encouraging template |
| 3885 | metaprogramming. Other extensions duplicate functionality |
| 3886 | available through existing mechanisms, which may lead to confusion |
| 3887 | and conversion costs.</p> |
| 3888 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3889 | <p class="decision"></p> |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3890 | <p>In addition to what's described in the rest of the style |
| 3891 | guide, the following C++ features may not be used:</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3892 | |
| 3893 | <ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3894 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3895 | |
| 3896 | <li>Compile-time rational numbers |
| 3897 | (<code><ratio></code>), because of concerns that |
| 3898 | it's tied to a more template-heavy interface |
| 3899 | style.</li> |
| 3900 | |
| 3901 | <li>The <code><cfenv></code> and |
| 3902 | <code><fenv.h></code> headers, because many |
| 3903 | compilers do not support those features reliably.</li> |
| 3904 | |
Victor Costan | 967e157 | 2019-09-05 05:09:38 -0700 | [diff] [blame] | 3905 | <li>The <code><filesystem></code> header, which |
| 3906 | |
| 3907 | does not have sufficient support for testing, and suffers |
| 3908 | from inherent security vulnerabilities.</li> |
| 3909 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3910 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3911 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3912 | |
| 3913 | <h3 id="Nonstandard_Extensions">Nonstandard Extensions</h3> |
| 3914 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3915 | <p>Nonstandard extensions to C++ may not be used unless otherwise specified.</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3916 | |
| 3917 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3918 | <p>Compilers support various extensions that are not part of standard C++. Such |
| 3919 | extensions include GCC's <code>__attribute__</code>, intrinsic functions such |
| 3920 | as <code>__builtin_prefetch</code>, designated initializers (e.g. |
| 3921 | <code>Foo f = {.field = 3}</code>), inline assembly, <code>__COUNTER__</code>, |
| 3922 | <code>__PRETTY_FUNCTION__</code>, compound statement expressions (e.g. |
| 3923 | <code>foo = ({ int x; Bar(&x); x })</code>, variable-length arrays and |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3924 | <code>alloca()</code>, and the "<a href="https://en.wikipedia.org/wiki/Elvis_operator">Elvis Operator</a>" |
| 3925 | <code>a?:b</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3926 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3927 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3928 | <ul> |
| 3929 | <li>Nonstandard extensions may provide useful features that do not exist |
| 3930 | in standard C++. For example, some people think that designated |
| 3931 | initializers are more readable than standard C++ features like |
| 3932 | constructors.</li> |
| 3933 | <li>Important performance guidance to the compiler can only be specified |
| 3934 | using extensions.</li> |
| 3935 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3936 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3937 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3938 | <ul> |
| 3939 | <li>Nonstandard extensions do not work in all compilers. Use of nonstandard |
| 3940 | extensions reduces portability of code.</li> |
| 3941 | <li>Even if they are supported in all targeted compilers, the extensions |
| 3942 | are often not well-specified, and there may be subtle behavior differences |
| 3943 | between compilers.</li> |
| 3944 | <li>Nonstandard extensions add to the language features that a reader must |
| 3945 | know to understand the code.</li> |
| 3946 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3947 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3948 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3949 | <p>Do not use nonstandard extensions. You may use portability wrappers that |
| 3950 | are implemented using nonstandard extensions, so long as those wrappers |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3951 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3952 | are provided by a designated project-wide |
| 3953 | portability header.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3954 | |
| 3955 | <h3 id="Aliases">Aliases</h3> |
| 3956 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3957 | <p>Public aliases are for the benefit of an API's user, and should be clearly documented.</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3958 | |
| 3959 | <p class="definition"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3960 | <p>There are several ways to create names that are aliases of other entities:</p> |
| 3961 | <pre>typedef Foo Bar; |
| 3962 | using Bar = Foo; |
| 3963 | using other_namespace::Foo; |
| 3964 | </pre> |
| 3965 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 3966 | <p>In new code, <code>using</code> is preferable to <code>typedef</code>, |
| 3967 | because it provides a more consistent syntax with the rest of C++ and works |
| 3968 | with templates.</p> |
| 3969 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3970 | <p>Like other declarations, aliases declared in a header file are part of that |
| 3971 | header's public API unless they're in a function definition, in the private portion of a class, |
| 3972 | or in an explicitly-marked internal namespace. Aliases in such areas or in .cc files are |
| 3973 | implementation details (because client code can't refer to them), and are not restricted by this |
| 3974 | rule.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3975 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3976 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3977 | <ul> |
| 3978 | <li>Aliases can improve readability by simplifying a long or complicated name.</li> |
| 3979 | <li>Aliases can reduce duplication by naming in one place a type used repeatedly in an API, |
| 3980 | which <em>might</em> make it easier to change the type later. |
| 3981 | </li> |
| 3982 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3983 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3984 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3985 | <ul> |
| 3986 | <li>When placed in a header where client code can refer to them, aliases increase the |
| 3987 | number of entities in that header's API, increasing its complexity.</li> |
| 3988 | <li>Clients can easily rely on unintended details of public aliases, making |
| 3989 | changes difficult.</li> |
| 3990 | <li>It can be tempting to create a public alias that is only intended for use |
| 3991 | in the implementation, without considering its impact on the API, or on maintainability.</li> |
| 3992 | <li>Aliases can create risk of name collisions</li> |
| 3993 | <li>Aliases can reduce readability by giving a familiar construct an unfamiliar name</li> |
| 3994 | <li>Type aliases can create an unclear API contract: |
| 3995 | it is unclear whether the alias is guaranteed to be identical to the type it aliases, |
| 3996 | to have the same API, or only to be usable in specified narrow ways</li> |
| 3997 | </ul> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 3998 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 3999 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4000 | <p>Don't put an alias in your public API just to save typing in the implementation; |
| 4001 | do so only if you intend it to be used by your clients.</p> |
| 4002 | <p>When defining a public alias, document the intent of |
| 4003 | the new name, including whether it is guaranteed to always be the same as the type |
| 4004 | it's currently aliased to, or whether a more limited compatibility is |
| 4005 | intended. This lets the user know whether they can treat the types as |
| 4006 | substitutable or whether more specific rules must be followed, and can help the |
| 4007 | implementation retain some degree of freedom to change the alias.</p> |
| 4008 | <p>Don't put namespace aliases in your public API. (See also <a href="#Namespaces">Namespaces</a>). |
| 4009 | </p> |
| 4010 | |
| 4011 | <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] | 4012 | <pre>namespace mynamespace { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4013 | // Used to store field measurements. DataPoint may change from Bar* to some internal type. |
| 4014 | // Client code should treat it as an opaque pointer. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4015 | using DataPoint = foo::Bar*; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4016 | |
| 4017 | // A set of measurements. Just an alias for user convenience. |
| 4018 | using TimeSeries = std::unordered_set<DataPoint, std::hash<DataPoint>, DataPointComparator>; |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4019 | } // namespace mynamespace |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4020 | </pre> |
| 4021 | |
| 4022 | <p>These aliases don't document intended use, and half of them aren't meant for client use:</p> |
| 4023 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4024 | <pre class="badcode">namespace mynamespace { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4025 | // Bad: none of these say how they should be used. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4026 | using DataPoint = foo::Bar*; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4027 | using std::unordered_set; // Bad: just for local convenience |
| 4028 | using std::hash; // Bad: just for local convenience |
| 4029 | typedef unordered_set<DataPoint, hash<DataPoint>, DataPointComparator> TimeSeries; |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4030 | } // namespace mynamespace |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4031 | </pre> |
| 4032 | |
| 4033 | <p>However, local convenience aliases are fine in function definitions, private sections of |
| 4034 | classes, explicitly marked internal namespaces, and in .cc files:</p> |
| 4035 | |
| 4036 | <pre>// In a .cc file |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4037 | using foo::Bar; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4038 | </pre> |
| 4039 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4040 | <h2 id="Naming">Naming</h2> |
| 4041 | |
| 4042 | <p>The most important consistency rules are those that govern |
| 4043 | naming. The style of a name immediately informs us what sort of |
| 4044 | thing the named entity is: a type, a variable, a function, a |
| 4045 | constant, a macro, etc., without requiring us to search for the |
| 4046 | declaration of that entity. The pattern-matching engine in our |
| 4047 | brains relies a great deal on these naming rules. |
| 4048 | </p> |
| 4049 | |
| 4050 | <p>Naming rules are pretty arbitrary, but |
| 4051 | we feel that |
| 4052 | consistency is more important than individual preferences in this |
| 4053 | area, so regardless of whether you find them sensible or not, |
| 4054 | the rules are the rules.</p> |
| 4055 | |
| 4056 | <h3 id="General_Naming_Rules">General Naming Rules</h3> |
| 4057 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4058 | <p>Optimize for readability using names that would be clear |
| 4059 | even to people on a different team.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4060 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4061 | <p>Use names that describe the purpose or intent of the object. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4062 | Do not worry about saving horizontal space as it is far |
| 4063 | more important to make your code immediately |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4064 | understandable by a new reader. Minimize the use of |
| 4065 | abbreviations that would likely be unknown to someone outside |
| 4066 | your project (especially acronyms and initialisms). Do not |
| 4067 | abbreviate by deleting letters within a word. As a rule of thumb, |
| 4068 | an abbreviation is probably OK if it's listed in |
| 4069 | Wikipedia. Generally speaking, descriptiveness should be |
| 4070 | proportional to the name's scope of visibility. For example, |
| 4071 | <code>n</code> may be a fine name within a 5-line function, |
| 4072 | but within the scope of a class, it's likely too vague.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4073 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4074 | <pre>class MyClass { |
| 4075 | public: |
| 4076 | int CountFooErrors(const std::vector<Foo>& foos) { |
| 4077 | int n = 0; // Clear meaning given limited scope and context |
| 4078 | for (const auto& foo : foos) { |
| 4079 | ... |
| 4080 | ++n; |
| 4081 | } |
| 4082 | return n; |
| 4083 | } |
| 4084 | void DoSomethingImportant() { |
| 4085 | std::string fqdn = ...; // Well-known abbreviation for Fully Qualified Domain Name |
| 4086 | } |
| 4087 | private: |
| 4088 | const int kMaxAllowedConnections = ...; // Clear meaning within context |
| 4089 | }; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4090 | </pre> |
| 4091 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4092 | <pre class="badcode">class MyClass { |
| 4093 | public: |
| 4094 | int CountFooErrors(const std::vector<Foo>& foos) { |
| 4095 | int total_number_of_foo_errors = 0; // Overly verbose given limited scope and context |
| 4096 | for (int foo_index = 0; foo_index < foos.size(); ++foo_index) { // Use idiomatic `i` |
| 4097 | ... |
| 4098 | ++total_number_of_foo_errors; |
| 4099 | } |
| 4100 | return total_number_of_foo_errors; |
| 4101 | } |
| 4102 | void DoSomethingImportant() { |
| 4103 | int cstmr_id = ...; // Deletes internal letters |
| 4104 | } |
| 4105 | private: |
| 4106 | const int kNum = ...; // Unclear meaning within broad scope |
| 4107 | }; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4108 | </pre> |
| 4109 | |
| 4110 | <p>Note that certain universally-known abbreviations are OK, such as |
| 4111 | <code>i</code> for an iteration variable and <code>T</code> for a |
| 4112 | template parameter.</p> |
| 4113 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4114 | <p>For the purposes of the naming rules below, a "word" is anything that you |
| 4115 | would write in English without internal spaces. This includes abbreviations and |
| 4116 | acronyms; e.g., for "<a href="https://en.wikipedia.org/wiki/Camel_case">camel |
| 4117 | case</a>" or "Pascal case," in which the first letter of each word is |
| 4118 | capitalized, use a name like <code>StartRpc()</code>, not |
| 4119 | <code>StartRPC()</code>.</p> |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4120 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4121 | <p>Template parameters should follow the naming style for their |
| 4122 | category: type template parameters should follow the rules for |
| 4123 | <a href="#Type_Names">type names</a>, and non-type template |
| 4124 | parameters should follow the rules for <a href="#Variable_Names"> |
| 4125 | variable names</a>. |
| 4126 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4127 | </p><h3 id="File_Names">File Names</h3> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4128 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4129 | <p>Filenames should be all lowercase and can include |
| 4130 | underscores (<code>_</code>) or dashes (<code>-</code>). |
| 4131 | Follow the convention that your |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4132 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4133 | project uses. If there is no consistent |
| 4134 | local pattern to follow, prefer "_".</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4135 | |
| 4136 | <p>Examples of acceptable file names:</p> |
| 4137 | |
| 4138 | <ul> |
| 4139 | <li><code>my_useful_class.cc</code></li> |
| 4140 | <li><code>my-useful-class.cc</code></li> |
| 4141 | <li><code>myusefulclass.cc</code></li> |
| 4142 | <li><code>myusefulclass_test.cc // _unittest and _regtest are deprecated.</code></li> |
| 4143 | </ul> |
| 4144 | |
| 4145 | <p>C++ files should end in <code>.cc</code> and header files should end in |
| 4146 | <code>.h</code>. Files that rely on being textually included at specific points |
| 4147 | should end in <code>.inc</code> (see also the section on |
| 4148 | <a href="#Self_contained_Headers">self-contained headers</a>).</p> |
| 4149 | |
| 4150 | <p>Do not use filenames that already exist in |
| 4151 | <code>/usr/include</code>, such as <code>db.h</code>.</p> |
| 4152 | |
| 4153 | <p>In general, make your filenames very specific. For |
| 4154 | example, use <code>http_server_logs.h</code> rather than |
| 4155 | <code>logs.h</code>. A very common case is to have a pair |
| 4156 | of files called, e.g., <code>foo_bar.h</code> and |
| 4157 | <code>foo_bar.cc</code>, defining a class called |
| 4158 | <code>FooBar</code>.</p> |
| 4159 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4160 | <h3 id="Type_Names">Type Names</h3> |
| 4161 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4162 | <p>Type names start with a capital letter and have a capital |
| 4163 | letter for each new word, with no underscores: |
| 4164 | <code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4165 | |
| 4166 | <p>The names of all types — classes, structs, type aliases, |
| 4167 | enums, and type template parameters — have the same naming convention. |
| 4168 | Type names should start with a capital letter and have a capital letter |
| 4169 | for each new word. No underscores. For example:</p> |
| 4170 | |
| 4171 | <pre>// classes and structs |
| 4172 | class UrlTable { ... |
| 4173 | class UrlTableTester { ... |
| 4174 | struct UrlTableProperties { ... |
| 4175 | |
| 4176 | // typedefs |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4177 | typedef hash_map<UrlTableProperties *, std::string> PropertiesMap; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4178 | |
| 4179 | // using aliases |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4180 | using PropertiesMap = hash_map<UrlTableProperties *, std::string>; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4181 | |
| 4182 | // enums |
| 4183 | enum UrlTableErrors { ... |
| 4184 | </pre> |
| 4185 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4186 | <h3 id="Variable_Names">Variable Names</h3> |
| 4187 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4188 | <p>The names of variables (including function parameters) and data members are |
| 4189 | all lowercase, with underscores between words. Data members of classes (but not |
| 4190 | structs) additionally have trailing underscores. For instance: |
| 4191 | <code>a_local_variable</code>, <code>a_struct_data_member</code>, |
| 4192 | <code>a_class_data_member_</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4193 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4194 | <h4>Common Variable names</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4195 | |
| 4196 | <p>For example:</p> |
| 4197 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4198 | <pre>std::string table_name; // OK - lowercase with underscore. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4199 | </pre> |
| 4200 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4201 | <pre class="badcode">std::string tableName; // Bad - mixed case. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4202 | </pre> |
| 4203 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4204 | <h4>Class Data Members</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4205 | |
| 4206 | <p>Data members of classes, both static and non-static, are |
| 4207 | named like ordinary nonmember variables, but with a |
| 4208 | trailing underscore.</p> |
| 4209 | |
| 4210 | <pre>class TableInfo { |
| 4211 | ... |
| 4212 | private: |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4213 | std::string table_name_; // OK - underscore at end. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4214 | static Pool<TableInfo>* pool_; // OK. |
| 4215 | }; |
| 4216 | </pre> |
| 4217 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4218 | <h4>Struct Data Members</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4219 | |
| 4220 | <p>Data members of structs, both static and non-static, |
| 4221 | are named like ordinary nonmember variables. They do not have |
| 4222 | the trailing underscores that data members in classes have.</p> |
| 4223 | |
| 4224 | <pre>struct UrlTableProperties { |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4225 | std::string name; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4226 | int num_entries; |
| 4227 | static Pool<UrlTableProperties>* pool; |
| 4228 | }; |
| 4229 | </pre> |
| 4230 | |
| 4231 | |
| 4232 | <p>See <a href="#Structs_vs._Classes">Structs vs. |
| 4233 | Classes</a> for a discussion of when to use a struct |
| 4234 | versus a class.</p> |
| 4235 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4236 | <h3 id="Constant_Names">Constant Names</h3> |
| 4237 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4238 | <p>Variables declared constexpr or const, and whose value is fixed for |
| 4239 | the duration of the program, are named with a leading "k" followed |
| 4240 | by mixed case. Underscores can be used as separators in the rare cases |
| 4241 | where capitalization cannot be used for separation. For example:</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4242 | |
| 4243 | <pre>const int kDaysInAWeek = 7; |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4244 | const int kAndroid8_0_0 = 24; // Android 8.0.0 |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4245 | </pre> |
| 4246 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4247 | <p>All such variables with static storage duration (i.e. statics and globals, |
| 4248 | see <a href="http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration"> |
| 4249 | Storage Duration</a> for details) should be named this way. This |
| 4250 | convention is optional for variables of other storage classes, e.g. automatic |
| 4251 | variables, otherwise the usual variable naming rules apply.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4252 | |
| 4253 | <h3 id="Function_Names">Function Names</h3> |
| 4254 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4255 | <p>Regular functions have mixed case; accessors and mutators may be named |
| 4256 | like variables.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4257 | |
| 4258 | <p>Ordinarily, functions should start with a capital letter and have a |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4259 | capital letter for each new word.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4260 | |
| 4261 | <pre>AddTableEntry() |
| 4262 | DeleteUrl() |
| 4263 | OpenFileOrDie() |
| 4264 | </pre> |
| 4265 | |
| 4266 | <p>(The same naming rule applies to class- and namespace-scope |
| 4267 | 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] | 4268 | like functions, because the fact that they're objects rather than functions |
| 4269 | is an unimportant implementation detail.)</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4270 | |
| 4271 | <p>Accessors and mutators (get and set functions) may be named like |
| 4272 | variables. These often correspond to actual member variables, but this is |
| 4273 | not required. For example, <code>int count()</code> and <code>void |
| 4274 | set_count(int count)</code>.</p> |
| 4275 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4276 | <h3 id="Namespace_Names">Namespace Names</h3> |
| 4277 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4278 | Namespace names are all lower-case. Top-level namespace names are |
| 4279 | based on the project name |
| 4280 | . Avoid collisions |
| 4281 | between nested namespaces and well-known top-level namespaces. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4282 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4283 | <p>The name of a top-level namespace should usually be the |
| 4284 | name of the project or team whose code is contained in that |
| 4285 | namespace. The code in that namespace should usually be in |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4286 | a directory whose basename matches the namespace name (or in |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4287 | subdirectories thereof).</p> |
| 4288 | |
| 4289 | |
| 4290 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4291 | <p>Keep in mind that the <a href="#General_Naming_Rules">rule |
| 4292 | against abbreviated names</a> applies to namespaces just as much |
| 4293 | as variable names. Code inside the namespace seldom needs to |
| 4294 | mention the namespace name, so there's usually no particular need |
| 4295 | for abbreviation anyway.</p> |
| 4296 | |
| 4297 | <p>Avoid nested namespaces that match well-known top-level |
| 4298 | namespaces. Collisions between namespace names can lead to surprising |
| 4299 | build breaks because of name lookup rules. In particular, do not |
| 4300 | create any nested <code>std</code> namespaces. Prefer unique project |
| 4301 | identifiers |
| 4302 | (<code>websearch::index</code>, <code>websearch::index_util</code>) |
| 4303 | over collision-prone names like <code>websearch::util</code>.</p> |
| 4304 | |
| 4305 | <p>For <code>internal</code> namespaces, be wary of other code being |
| 4306 | added to the same <code>internal</code> namespace causing a collision |
| 4307 | (internal helpers within a team tend to be related and may lead to |
| 4308 | collisions). In such a situation, using the filename to make a unique |
| 4309 | internal name is helpful |
| 4310 | (<code>websearch::index::frobber_internal</code> for use |
| 4311 | in <code>frobber.h</code>)</p> |
| 4312 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4313 | <h3 id="Enumerator_Names">Enumerator Names</h3> |
| 4314 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4315 | <p>Enumerators (for both scoped and unscoped enums) should be named <i>either</i> like |
| 4316 | <a href="#Constant_Names">constants</a> or like |
| 4317 | <a href="#Macro_Names">macros</a>: either <code>kEnumName</code> or |
| 4318 | <code>ENUM_NAME</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4319 | |
| 4320 | <p>Preferably, the individual enumerators should be named |
| 4321 | like <a href="#Constant_Names">constants</a>. However, it |
| 4322 | is also acceptable to name them like |
| 4323 | <a href="#Macro_Names">macros</a>. The enumeration name, |
| 4324 | <code>UrlTableErrors</code> (and |
| 4325 | <code>AlternateUrlTableErrors</code>), is a type, and |
| 4326 | therefore mixed case.</p> |
| 4327 | |
| 4328 | <pre>enum UrlTableErrors { |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4329 | kOk = 0, |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4330 | kErrorOutOfMemory, |
| 4331 | kErrorMalformedInput, |
| 4332 | }; |
| 4333 | enum AlternateUrlTableErrors { |
| 4334 | OK = 0, |
| 4335 | OUT_OF_MEMORY = 1, |
| 4336 | MALFORMED_INPUT = 2, |
| 4337 | }; |
| 4338 | </pre> |
| 4339 | |
| 4340 | <p>Until January 2009, the style was to name enum values |
| 4341 | like <a href="#Macro_Names">macros</a>. This caused |
| 4342 | problems with name collisions between enum values and |
| 4343 | macros. Hence, the change to prefer constant-style naming |
| 4344 | was put in place. New code should prefer constant-style |
| 4345 | naming if possible. However, there is no reason to change |
| 4346 | old code to use constant-style names, unless the old |
| 4347 | names are actually causing a compile-time problem.</p> |
| 4348 | |
| 4349 | |
| 4350 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4351 | <h3 id="Macro_Names">Macro Names</h3> |
| 4352 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4353 | <p>You're not really going to <a href="#Preprocessor_Macros"> |
| 4354 | 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] | 4355 | <code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN_AND_ADULTS_ALIKE</code>. |
| 4356 | </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4357 | |
| 4358 | <p>Please see the <a href="#Preprocessor_Macros">description |
| 4359 | of macros</a>; in general macros should <em>not</em> be used. |
| 4360 | However, if they are absolutely needed, then they should be |
| 4361 | named with all capitals and underscores.</p> |
| 4362 | |
| 4363 | <pre>#define ROUND(x) ... |
| 4364 | #define PI_ROUNDED 3.0 |
| 4365 | </pre> |
| 4366 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4367 | <h3 id="Exceptions_to_Naming_Rules">Exceptions to Naming Rules</h3> |
| 4368 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4369 | <p>If you are naming something that is analogous to an |
| 4370 | existing C or C++ entity then you can follow the existing |
| 4371 | naming convention scheme.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4372 | |
| 4373 | <dl> |
| 4374 | <dt><code>bigopen()</code></dt> |
| 4375 | <dd>function name, follows form of <code>open()</code></dd> |
| 4376 | |
| 4377 | <dt><code>uint</code></dt> |
| 4378 | <dd><code>typedef</code></dd> |
| 4379 | |
| 4380 | <dt><code>bigpos</code></dt> |
| 4381 | <dd><code>struct</code> or <code>class</code>, follows |
| 4382 | form of <code>pos</code></dd> |
| 4383 | |
| 4384 | <dt><code>sparse_hash_map</code></dt> |
| 4385 | <dd>STL-like entity; follows STL naming conventions</dd> |
| 4386 | |
| 4387 | <dt><code>LONGLONG_MAX</code></dt> |
| 4388 | <dd>a constant, as in <code>INT_MAX</code></dd> |
| 4389 | </dl> |
| 4390 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4391 | <h2 id="Comments">Comments</h2> |
| 4392 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4393 | <p>Comments are absolutely vital to keeping our code readable. The following rules describe what you |
| 4394 | should comment and where. But remember: while comments are very important, the best code is |
| 4395 | self-documenting. Giving sensible names to types and variables is much better than using obscure |
| 4396 | names that you must then explain through comments.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4397 | |
| 4398 | <p>When writing your comments, write for your audience: the |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4399 | next |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4400 | contributor who will need to |
| 4401 | understand your code. Be generous — the next |
| 4402 | one may be you!</p> |
| 4403 | |
| 4404 | <h3 id="Comment_Style">Comment Style</h3> |
| 4405 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4406 | <p>Use either the <code>//</code> or <code>/* */</code> |
| 4407 | syntax, as long as you are consistent.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4408 | |
| 4409 | <p>You can use either the <code>//</code> or the <code>/* |
| 4410 | */</code> syntax; however, <code>//</code> is |
| 4411 | <em>much</em> more common. Be consistent with how you |
| 4412 | comment and what style you use where.</p> |
| 4413 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4414 | <h3 id="File_Comments">File Comments</h3> |
| 4415 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4416 | <div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4417 | <p>Start each file with license boilerplate.</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4418 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4419 | |
| 4420 | <p>File comments describe the contents of a file. If a file declares, |
| 4421 | implements, or tests exactly one abstraction that is documented by a comment |
| 4422 | at the point of declaration, file comments are not required. All other files |
| 4423 | must have file comments.</p> |
| 4424 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4425 | <h4>Legal Notice and Author |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4426 | Line</h4> |
| 4427 | |
| 4428 | |
| 4429 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4430 | <div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4431 | <p>Every file should contain license |
| 4432 | boilerplate. Choose the appropriate boilerplate for the |
| 4433 | license used by the project (for example, Apache 2.0, |
| 4434 | BSD, LGPL, GPL).</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4435 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4436 | |
| 4437 | <p>If you make significant changes to a file with an |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4438 | author line, consider deleting the author line. |
| 4439 | New files should usually not contain copyright notice or |
| 4440 | author line.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4441 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4442 | <h4>File Contents</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4443 | |
| 4444 | <p>If a <code>.h</code> declares multiple abstractions, the file-level comment |
| 4445 | should broadly describe the contents of the file, and how the abstractions are |
| 4446 | related. A 1 or 2 sentence file-level comment may be sufficient. The detailed |
| 4447 | documentation about individual abstractions belongs with those abstractions, |
| 4448 | not at the file level.</p> |
| 4449 | |
| 4450 | <p>Do not duplicate comments in both the <code>.h</code> and the |
| 4451 | <code>.cc</code>. Duplicated comments diverge.</p> |
| 4452 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4453 | <h3 id="Class_Comments">Class Comments</h3> |
| 4454 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4455 | <p>Every non-obvious class declaration should have an accompanying |
| 4456 | comment that describes what it is for and how it should be used.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4457 | |
| 4458 | <pre>// Iterates over the contents of a GargantuanTable. |
| 4459 | // Example: |
| 4460 | // GargantuanTableIterator* iter = table->NewIterator(); |
| 4461 | // for (iter->Seek("foo"); !iter->done(); iter->Next()) { |
| 4462 | // process(iter->key(), iter->value()); |
| 4463 | // } |
| 4464 | // delete iter; |
| 4465 | class GargantuanTableIterator { |
| 4466 | ... |
| 4467 | }; |
| 4468 | </pre> |
| 4469 | |
| 4470 | <p>The class comment should provide the reader with enough information to know |
| 4471 | how and when to use the class, as well as any additional considerations |
| 4472 | necessary to correctly use the class. Document the synchronization assumptions |
| 4473 | the class makes, if any. If an instance of the class can be accessed by |
| 4474 | multiple threads, take extra care to document the rules and invariants |
| 4475 | surrounding multithreaded use.</p> |
| 4476 | |
| 4477 | <p>The class comment is often a good place for a small example code snippet |
| 4478 | demonstrating a simple and focused usage of the class.</p> |
| 4479 | |
| 4480 | <p>When sufficiently separated (e.g. <code>.h</code> and <code>.cc</code> |
| 4481 | files), comments describing the use of the class should go together with its |
| 4482 | interface definition; comments about the class operation and implementation |
| 4483 | should accompany the implementation of the class's methods.</p> |
| 4484 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4485 | <h3 id="Function_Comments">Function Comments</h3> |
| 4486 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4487 | <p>Declaration comments describe use of the function (when it is |
| 4488 | non-obvious); comments at the definition of a function describe |
| 4489 | operation.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4490 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4491 | <h4>Function Declarations</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4492 | |
| 4493 | <p>Almost every function declaration should have comments immediately |
| 4494 | preceding it that describe what the function does and how to use |
| 4495 | it. These comments may be omitted only if the function is simple and |
| 4496 | obvious (e.g. simple accessors for obvious properties of the |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4497 | class). These comments should open with descriptive verbs in the |
| 4498 | indicative mood ("Opens the file") rather than verbs in the imperative |
| 4499 | ("Open the file"). The comment describes the function; it does not |
| 4500 | tell the function what to do. In general, these comments do not |
| 4501 | describe how the function performs its task. Instead, that should be |
| 4502 | left to comments in the function definition.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4503 | |
| 4504 | <p>Types of things to mention in comments at the function |
| 4505 | declaration:</p> |
| 4506 | |
| 4507 | <ul> |
| 4508 | <li>What the inputs and outputs are.</li> |
| 4509 | |
| 4510 | <li>For class member functions: whether the object |
| 4511 | remembers reference arguments beyond the duration of |
| 4512 | the method call, and whether it will free them or |
| 4513 | not.</li> |
| 4514 | |
| 4515 | <li>If the function allocates memory that the caller |
| 4516 | must free.</li> |
| 4517 | |
| 4518 | <li>Whether any of the arguments can be a null |
| 4519 | pointer.</li> |
| 4520 | |
| 4521 | <li>If there are any performance implications of how a |
| 4522 | function is used.</li> |
| 4523 | |
| 4524 | <li>If the function is re-entrant. What are its |
| 4525 | synchronization assumptions?</li> |
| 4526 | </ul> |
| 4527 | |
| 4528 | <p>Here is an example:</p> |
| 4529 | |
| 4530 | <pre>// Returns an iterator for this table. It is the client's |
| 4531 | // responsibility to delete the iterator when it is done with it, |
| 4532 | // and it must not use the iterator once the GargantuanTable object |
| 4533 | // on which the iterator was created has been deleted. |
| 4534 | // |
| 4535 | // The iterator is initially positioned at the beginning of the table. |
| 4536 | // |
| 4537 | // This method is equivalent to: |
| 4538 | // Iterator* iter = table->NewIterator(); |
| 4539 | // iter->Seek(""); |
| 4540 | // return iter; |
| 4541 | // If you are going to immediately seek to another place in the |
| 4542 | // returned iterator, it will be faster to use NewIterator() |
| 4543 | // and avoid the extra seek. |
| 4544 | Iterator* GetIterator() const; |
| 4545 | </pre> |
| 4546 | |
| 4547 | <p>However, do not be unnecessarily verbose or state the |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4548 | completely obvious.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4549 | |
| 4550 | <p>When documenting function overrides, focus on the |
| 4551 | specifics of the override itself, rather than repeating |
| 4552 | the comment from the overridden function. In many of these |
| 4553 | cases, the override needs no additional documentation and |
| 4554 | thus no comment is required.</p> |
| 4555 | |
| 4556 | <p>When commenting constructors and destructors, remember |
| 4557 | that the person reading your code knows what constructors |
| 4558 | and destructors are for, so comments that just say |
| 4559 | something like "destroys this object" are not useful. |
| 4560 | Document what constructors do with their arguments (for |
| 4561 | example, if they take ownership of pointers), and what |
| 4562 | cleanup the destructor does. If this is trivial, just |
| 4563 | skip the comment. It is quite common for destructors not |
| 4564 | to have a header comment.</p> |
| 4565 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4566 | <h4>Function Definitions</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4567 | |
| 4568 | <p>If there is anything tricky about how a function does |
| 4569 | its job, the function definition should have an |
| 4570 | explanatory comment. For example, in the definition |
| 4571 | comment you might describe any coding tricks you use, |
| 4572 | give an overview of the steps you go through, or explain |
| 4573 | why you chose to implement the function in the way you |
| 4574 | did rather than using a viable alternative. For instance, |
| 4575 | you might mention why it must acquire a lock for the |
| 4576 | first half of the function but why it is not needed for |
| 4577 | the second half.</p> |
| 4578 | |
| 4579 | <p>Note you should <em>not</em> just repeat the comments |
| 4580 | given with the function declaration, in the |
| 4581 | <code>.h</code> file or wherever. It's okay to |
| 4582 | recapitulate briefly what the function does, but the |
| 4583 | focus of the comments should be on how it does it.</p> |
| 4584 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4585 | <h3 id="Variable_Comments">Variable Comments</h3> |
| 4586 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4587 | <p>In general the actual name of the variable should be |
| 4588 | descriptive enough to give a good idea of what the variable |
| 4589 | is used for. In certain cases, more comments are required.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4590 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4591 | <h4>Class Data Members</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4592 | |
| 4593 | <p>The purpose of each class data member (also called an instance |
| 4594 | variable or member variable) must be clear. If there are any |
| 4595 | invariants (special values, relationships between members, lifetime |
| 4596 | requirements) not clearly expressed by the type and name, they must be |
| 4597 | commented. However, if the type and name suffice (<code>int |
| 4598 | num_events_;</code>), no comment is needed.</p> |
| 4599 | |
| 4600 | <p>In particular, add comments to describe the existence and meaning |
| 4601 | of sentinel values, such as nullptr or -1, when they are not |
| 4602 | obvious. For example:</p> |
| 4603 | |
| 4604 | <pre>private: |
| 4605 | // Used to bounds-check table accesses. -1 means |
| 4606 | // that we don't yet know how many entries the table has. |
| 4607 | int num_total_entries_; |
| 4608 | </pre> |
| 4609 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4610 | <h4>Global Variables</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4611 | |
| 4612 | <p>All global variables should have a comment describing what they |
| 4613 | are, what they are used for, and (if unclear) why it needs to be |
| 4614 | global. For example:</p> |
| 4615 | |
| 4616 | <pre>// The total number of tests cases that we run through in this regression test. |
| 4617 | const int kNumTestCases = 6; |
| 4618 | </pre> |
| 4619 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4620 | <h3 id="Implementation_Comments">Implementation Comments</h3> |
| 4621 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4622 | <p>In your implementation you should have comments in tricky, |
| 4623 | non-obvious, interesting, or important parts of your code.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4624 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4625 | <h4>Explanatory Comments</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4626 | |
| 4627 | <p>Tricky or complicated code blocks should have comments |
| 4628 | before them. Example:</p> |
| 4629 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4630 | <pre>// Divide result by two, taking into account that x |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4631 | // contains the carry from the add. |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4632 | for (int i = 0; i < result->size(); ++i) { |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4633 | x = (x << 8) + (*result)[i]; |
| 4634 | (*result)[i] = x >> 1; |
| 4635 | x &= 1; |
| 4636 | } |
| 4637 | </pre> |
| 4638 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4639 | <h4>Line-end Comments</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4640 | |
| 4641 | <p>Also, lines that are non-obvious should get a comment |
| 4642 | at the end of the line. These end-of-line comments should |
| 4643 | be separated from the code by 2 spaces. Example:</p> |
| 4644 | |
| 4645 | <pre>// If we have enough memory, mmap the data portion too. |
| 4646 | mmap_budget = max<int64>(0, mmap_budget - index_->length()); |
| 4647 | if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock)) |
| 4648 | return; // Error already logged. |
| 4649 | </pre> |
| 4650 | |
| 4651 | <p>Note that there are both comments that describe what |
| 4652 | the code is doing, and comments that mention that an |
| 4653 | error has already been logged when the function |
| 4654 | returns.</p> |
| 4655 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4656 | <h4 id="Function_Argument_Comments" class="stylepoint_subsection">Function Argument Comments</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4657 | |
| 4658 | <p>When the meaning of a function argument is nonobvious, consider |
| 4659 | one of the following remedies:</p> |
| 4660 | |
| 4661 | <ul> |
| 4662 | <li>If the argument is a literal constant, and the same constant is |
| 4663 | used in multiple function calls in a way that tacitly assumes they're |
| 4664 | the same, you should use a named constant to make that constraint |
| 4665 | explicit, and to guarantee that it holds.</li> |
| 4666 | |
| 4667 | <li>Consider changing the function signature to replace a <code>bool</code> |
| 4668 | argument with an <code>enum</code> argument. This will make the argument |
| 4669 | values self-describing.</li> |
| 4670 | |
| 4671 | <li>For functions that have several configuration options, consider |
| 4672 | defining a single class or struct to hold all the options |
| 4673 | , |
| 4674 | and pass an instance of that. |
| 4675 | This approach has several advantages. Options are referenced by name |
| 4676 | at the call site, which clarifies their meaning. It also reduces |
| 4677 | function argument count, which makes function calls easier to read and |
| 4678 | write. As an added benefit, you don't have to change call sites when |
| 4679 | you add another option. |
| 4680 | </li> |
| 4681 | |
| 4682 | <li>Replace large or complex nested expressions with named variables.</li> |
| 4683 | |
| 4684 | <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] | 4685 | call site. </li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4686 | </ul> |
| 4687 | |
| 4688 | Consider the following example: |
| 4689 | |
| 4690 | <pre class="badcode">// What are these arguments? |
| 4691 | const DecimalNumber product = CalculateProduct(values, 7, false, nullptr); |
| 4692 | </pre> |
| 4693 | |
| 4694 | <p>versus:</p> |
| 4695 | |
| 4696 | <pre>ProductOptions options; |
| 4697 | options.set_precision_decimals(7); |
| 4698 | options.set_use_cache(ProductOptions::kDontUseCache); |
| 4699 | const DecimalNumber product = |
| 4700 | CalculateProduct(values, options, /*completion_callback=*/nullptr); |
| 4701 | </pre> |
| 4702 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4703 | <h4 id="Implementation_Comment_Donts">Don'ts</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4704 | |
| 4705 | <p>Do not state the obvious. In particular, don't literally describe what |
| 4706 | code does, unless the behavior is nonobvious to a reader who understands |
| 4707 | C++ well. Instead, provide higher level comments that describe <i>why</i> |
| 4708 | the code does what it does, or make the code self describing.</p> |
| 4709 | |
| 4710 | Compare this: |
| 4711 | |
| 4712 | <pre class="badcode">// Find the element in the vector. <-- Bad: obvious! |
| 4713 | auto iter = std::find(v.begin(), v.end(), element); |
| 4714 | if (iter != v.end()) { |
| 4715 | Process(element); |
| 4716 | } |
| 4717 | </pre> |
| 4718 | |
| 4719 | To this: |
| 4720 | |
| 4721 | <pre>// Process "element" unless it was already processed. |
| 4722 | auto iter = std::find(v.begin(), v.end(), element); |
| 4723 | if (iter != v.end()) { |
| 4724 | Process(element); |
| 4725 | } |
| 4726 | </pre> |
| 4727 | |
| 4728 | Self-describing code doesn't need a comment. The comment from |
| 4729 | the example above would be obvious: |
| 4730 | |
| 4731 | <pre>if (!IsAlreadyProcessed(element)) { |
| 4732 | Process(element); |
| 4733 | } |
| 4734 | </pre> |
| 4735 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4736 | <h3 id="Punctuation,_Spelling_and_Grammar">Punctuation, Spelling, and Grammar</h3> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4737 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4738 | <p>Pay attention to punctuation, spelling, and grammar; it is |
| 4739 | easier to read well-written comments than badly written |
| 4740 | ones.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4741 | |
| 4742 | <p>Comments should be as readable as narrative text, with |
| 4743 | proper capitalization and punctuation. In many cases, |
| 4744 | complete sentences are more readable than sentence |
| 4745 | fragments. Shorter comments, such as comments at the end |
| 4746 | of a line of code, can sometimes be less formal, but you |
| 4747 | should be consistent with your style.</p> |
| 4748 | |
| 4749 | <p>Although it can be frustrating to have a code reviewer |
| 4750 | point out that you are using a comma when you should be |
| 4751 | using a semicolon, it is very important that source code |
| 4752 | maintain a high level of clarity and readability. Proper |
| 4753 | punctuation, spelling, and grammar help with that |
| 4754 | goal.</p> |
| 4755 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4756 | <h3 id="TODO_Comments">TODO Comments</h3> |
| 4757 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4758 | <p>Use <code>TODO</code> comments for code that is temporary, |
| 4759 | a short-term solution, or good-enough but not perfect.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4760 | |
| 4761 | <p><code>TODO</code>s should include the string |
| 4762 | <code>TODO</code> in all caps, followed by the |
| 4763 | |
| 4764 | name, e-mail address, bug ID, or other |
| 4765 | identifier |
| 4766 | of the person or issue with the best context |
| 4767 | about the problem referenced by the <code>TODO</code>. The |
| 4768 | main purpose is to have a consistent <code>TODO</code> that |
| 4769 | can be searched to find out how to get more details upon |
| 4770 | request. A <code>TODO</code> is not a commitment that the |
| 4771 | person referenced will fix the problem. Thus when you create |
| 4772 | a <code>TODO</code> with a name, it is almost always your |
| 4773 | name that is given.</p> |
| 4774 | |
| 4775 | |
| 4776 | |
| 4777 | <div> |
| 4778 | <pre>// TODO(kl@gmail.com): Use a "*" here for concatenation operator. |
| 4779 | // TODO(Zeke) change this to use relations. |
| 4780 | // TODO(bug 12345): remove the "Last visitors" feature |
| 4781 | </pre> |
| 4782 | </div> |
| 4783 | |
| 4784 | <p>If your <code>TODO</code> is of the form "At a future |
| 4785 | date do something" make sure that you either include a |
| 4786 | very specific date ("Fix by November 2005") or a very |
| 4787 | specific event ("Remove this code when all clients can |
| 4788 | handle XML responses.").</p> |
| 4789 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4790 | <h2 id="Formatting">Formatting</h2> |
| 4791 | |
| 4792 | <p>Coding style and formatting are pretty arbitrary, but a |
| 4793 | |
| 4794 | project is much easier to follow |
| 4795 | if everyone uses the same style. Individuals may not agree with every |
| 4796 | aspect of the formatting rules, and some of the rules may take |
| 4797 | some getting used to, but it is important that all |
| 4798 | |
| 4799 | project contributors follow the |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4800 | style rules so that |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4801 | they can all read and understand |
| 4802 | everyone's code easily.</p> |
| 4803 | |
| 4804 | |
| 4805 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4806 | <div> |
| 4807 | <p>To help you format code correctly, we've created a |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4808 | <a href="https://raw.githubusercontent.com/google/styleguide/gh-pages/google-c-style.el"> |
| 4809 | settings file for emacs</a>.</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4810 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4811 | |
| 4812 | <h3 id="Line_Length">Line Length</h3> |
| 4813 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4814 | <p>Each line of text in your code should be at most 80 |
| 4815 | characters long.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4816 | |
| 4817 | |
| 4818 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4819 | <div> |
| 4820 | <p>We recognize that this rule is |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4821 | controversial, but so much existing code already adheres |
| 4822 | to it, and we feel that consistency is important.</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4823 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4824 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4825 | <p class="pros"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4826 | <p>Those who favor this rule |
| 4827 | argue that it is rude to force them to resize |
| 4828 | their windows and there is no need for anything longer. |
| 4829 | Some folks are used to having several code windows |
| 4830 | side-by-side, and thus don't have room to widen their |
| 4831 | windows in any case. People set up their work environment |
| 4832 | assuming a particular maximum window width, and 80 |
| 4833 | columns has been the traditional standard. Why change |
| 4834 | it?</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4835 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4836 | <p class="cons"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4837 | <p>Proponents of change argue that a wider line can make |
| 4838 | code more readable. The 80-column limit is an hidebound |
| 4839 | throwback to 1960s mainframes; modern equipment has wide screens that |
| 4840 | can easily show longer lines.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4841 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4842 | <p class="decision"></p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4843 | <p> 80 characters is the maximum.</p> |
| 4844 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4845 | <p>A line may exceed 80 characters if it is</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4846 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4847 | <ul> |
| 4848 | <li>a comment line which is not feasible to split without harming |
| 4849 | readability, ease of cut and paste or auto-linking -- e.g. if a line |
| 4850 | 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] | 4851 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4852 | <li>a raw-string literal with content that exceeds 80 characters. Except for |
| 4853 | 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] | 4854 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 4855 | <li>an include statement.</li> |
| 4856 | |
| 4857 | <li>a <a href="#The__define_Guard">header guard</a></li> |
| 4858 | |
| 4859 | <li>a using-declaration</li> |
| 4860 | </ul> |
| 4861 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4862 | <h3 id="Non-ASCII_Characters">Non-ASCII Characters</h3> |
| 4863 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4864 | <p>Non-ASCII characters should be rare, and must use UTF-8 |
| 4865 | formatting.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4866 | |
| 4867 | <p>You shouldn't hard-code user-facing text in source, |
| 4868 | even English, so use of non-ASCII characters should be |
| 4869 | rare. However, in certain cases it is appropriate to |
| 4870 | include such words in your code. For example, if your |
| 4871 | code parses data files from foreign sources, it may be |
| 4872 | appropriate to hard-code the non-ASCII string(s) used in |
| 4873 | those data files as delimiters. More commonly, unittest |
| 4874 | code (which does not need to be localized) might |
| 4875 | contain non-ASCII strings. In such cases, you should use |
| 4876 | UTF-8, since that is an encoding |
| 4877 | understood by most tools able to handle more than just |
| 4878 | ASCII.</p> |
| 4879 | |
| 4880 | <p>Hex encoding is also OK, and encouraged where it |
| 4881 | enhances readability — for example, |
| 4882 | <code>"\xEF\xBB\xBF"</code>, or, even more simply, |
| 4883 | <code>u8"\uFEFF"</code>, is the Unicode zero-width |
| 4884 | no-break space character, which would be invisible if |
| 4885 | included in the source as straight UTF-8.</p> |
| 4886 | |
| 4887 | <p>Use the <code>u8</code> prefix |
| 4888 | to guarantee that a string literal containing |
| 4889 | <code>\uXXXX</code> escape sequences is encoded as UTF-8. |
| 4890 | Do not use it for strings containing non-ASCII characters |
| 4891 | encoded as UTF-8, because that will produce incorrect |
| 4892 | output if the compiler does not interpret the source file |
| 4893 | as UTF-8. </p> |
| 4894 | |
| 4895 | <p>You shouldn't use the C++11 <code>char16_t</code> and |
| 4896 | <code>char32_t</code> character types, since they're for |
| 4897 | non-UTF-8 text. For similar reasons you also shouldn't |
| 4898 | use <code>wchar_t</code> (unless you're writing code that |
| 4899 | interacts with the Windows API, which uses |
| 4900 | <code>wchar_t</code> extensively).</p> |
| 4901 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4902 | <h3 id="Spaces_vs._Tabs">Spaces vs. Tabs</h3> |
| 4903 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4904 | <p>Use only spaces, and indent 2 spaces at a time.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4905 | |
| 4906 | <p>We use spaces for indentation. Do not use tabs in your |
| 4907 | code. You should set your editor to emit spaces when you |
| 4908 | hit the tab key.</p> |
| 4909 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4910 | <h3 id="Function_Declarations_and_Definitions">Function Declarations and Definitions</h3> |
| 4911 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4912 | <p>Return type on the same line as function name, parameters |
| 4913 | on the same line if they fit. Wrap parameter lists which do |
| 4914 | not fit on a single line as you would wrap arguments in a |
| 4915 | <a href="#Function_Calls">function call</a>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4916 | |
| 4917 | <p>Functions look like this:</p> |
| 4918 | |
| 4919 | |
| 4920 | <pre>ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) { |
| 4921 | DoSomething(); |
| 4922 | ... |
| 4923 | } |
| 4924 | </pre> |
| 4925 | |
| 4926 | <p>If you have too much text to fit on one line:</p> |
| 4927 | |
| 4928 | <pre>ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2, |
| 4929 | Type par_name3) { |
| 4930 | DoSomething(); |
| 4931 | ... |
| 4932 | } |
| 4933 | </pre> |
| 4934 | |
| 4935 | <p>or if you cannot fit even the first parameter:</p> |
| 4936 | |
| 4937 | <pre>ReturnType LongClassName::ReallyReallyReallyLongFunctionName( |
| 4938 | Type par_name1, // 4 space indent |
| 4939 | Type par_name2, |
| 4940 | Type par_name3) { |
| 4941 | DoSomething(); // 2 space indent |
| 4942 | ... |
| 4943 | } |
| 4944 | </pre> |
| 4945 | |
| 4946 | <p>Some points to note:</p> |
| 4947 | |
| 4948 | <ul> |
| 4949 | <li>Choose good parameter names.</li> |
| 4950 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 4951 | <li>A parameter name may be omitted only if the parameter is not used in the |
| 4952 | function's definition.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4953 | |
| 4954 | <li>If you cannot fit the return type and the function |
| 4955 | name on a single line, break between them.</li> |
| 4956 | |
| 4957 | <li>If you break after the return type of a function |
| 4958 | declaration or definition, do not indent.</li> |
| 4959 | |
| 4960 | <li>The open parenthesis is always on the same line as |
| 4961 | the function name.</li> |
| 4962 | |
| 4963 | <li>There is never a space between the function name |
| 4964 | and the open parenthesis.</li> |
| 4965 | |
| 4966 | <li>There is never a space between the parentheses and |
| 4967 | the parameters.</li> |
| 4968 | |
| 4969 | <li>The open curly brace is always on the end of the last line of the function |
| 4970 | declaration, not the start of the next line.</li> |
| 4971 | |
| 4972 | <li>The close curly brace is either on the last line by |
| 4973 | itself or on the same line as the open curly brace.</li> |
| 4974 | |
| 4975 | <li>There should be a space between the close |
| 4976 | parenthesis and the open curly brace.</li> |
| 4977 | |
| 4978 | <li>All parameters should be aligned if possible.</li> |
| 4979 | |
| 4980 | <li>Default indentation is 2 spaces.</li> |
| 4981 | |
| 4982 | <li>Wrapped parameters have a 4 space indent.</li> |
| 4983 | </ul> |
| 4984 | |
| 4985 | <p>Unused parameters that are obvious from context may be omitted:</p> |
| 4986 | |
| 4987 | <pre>class Foo { |
| 4988 | public: |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 4989 | Foo(const Foo&) = delete; |
| 4990 | Foo& operator=(const Foo&) = delete; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 4991 | }; |
| 4992 | </pre> |
| 4993 | |
| 4994 | <p>Unused parameters that might not be obvious should comment out the variable |
| 4995 | name in the function definition:</p> |
| 4996 | |
| 4997 | <pre>class Shape { |
| 4998 | public: |
| 4999 | virtual void Rotate(double radians) = 0; |
| 5000 | }; |
| 5001 | |
| 5002 | class Circle : public Shape { |
| 5003 | public: |
| 5004 | void Rotate(double radians) override; |
| 5005 | }; |
| 5006 | |
| 5007 | void Circle::Rotate(double /*radians*/) {} |
| 5008 | </pre> |
| 5009 | |
| 5010 | <pre class="badcode">// Bad - if someone wants to implement later, it's not clear what the |
| 5011 | // variable means. |
| 5012 | void Circle::Rotate(double) {} |
| 5013 | </pre> |
| 5014 | |
| 5015 | <p>Attributes, and macros that expand to attributes, appear at the very |
| 5016 | beginning of the function declaration or definition, before the |
| 5017 | return type:</p> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5018 | <pre>ABSL_MUST_USE_RESULT bool IsOk(); |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5019 | </pre> |
| 5020 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5021 | <h3 id="Formatting_Lambda_Expressions">Lambda Expressions</h3> |
| 5022 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5023 | <p>Format parameters and bodies as for any other function, and capture |
| 5024 | lists like other comma-separated lists.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5025 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5026 | <p>For by-reference captures, do not leave a space between the |
| 5027 | ampersand (&) and the variable name.</p> |
| 5028 | <pre>int x = 0; |
| 5029 | auto x_plus_n = [&x](int n) -> int { return x + n; } |
| 5030 | </pre> |
| 5031 | <p>Short lambdas may be written inline as function arguments.</p> |
| 5032 | <pre>std::set<int> blacklist = {7, 8, 9}; |
| 5033 | std::vector<int> digits = {3, 9, 1, 8, 4, 7, 1}; |
| 5034 | digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) { |
| 5035 | return blacklist.find(i) != blacklist.end(); |
| 5036 | }), |
| 5037 | digits.end()); |
| 5038 | </pre> |
| 5039 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5040 | <h3 id="Floating_Literals">Floating-point Literals</h3> |
| 5041 | |
| 5042 | <p>Floating-point literals should always have a radix point, with digits on both |
| 5043 | sides, even if they use exponential notation. Readability is improved if all |
| 5044 | floating-point literals take this familiar form, as this helps ensure that they |
| 5045 | are not mistaken for integer literals, and that the |
| 5046 | <code>E</code>/<code>e</code> of the exponential notation is not mistaken for a |
| 5047 | hexadecimal digit. It is fine to initialize a floating-point variable with an |
| 5048 | integer literal (assuming the variable type can exactly represent that integer), |
| 5049 | but note that a number in exponential notation is never an integer literal. |
| 5050 | </p> |
| 5051 | |
| 5052 | <pre class="badcode">float f = 1.f; |
| 5053 | long double ld = -.5L; |
| 5054 | double d = 1248e6; |
| 5055 | </pre> |
| 5056 | |
| 5057 | <pre class="goodcode">float f = 1.0f; |
| 5058 | float f2 = 1; // Also OK |
| 5059 | long double ld = -0.5L; |
| 5060 | double d = 1248.0e6; |
| 5061 | </pre> |
| 5062 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5063 | |
| 5064 | <h3 id="Function_Calls">Function Calls</h3> |
| 5065 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5066 | <p>Either write the call all on a single line, wrap the |
| 5067 | arguments at the parenthesis, or start the arguments on a new |
| 5068 | line indented by four spaces and continue at that 4 space |
| 5069 | indent. In the absence of other considerations, use the |
| 5070 | minimum number of lines, including placing multiple arguments |
| 5071 | on each line where appropriate.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5072 | |
| 5073 | <p>Function calls have the following format:</p> |
| 5074 | <pre>bool result = DoSomething(argument1, argument2, argument3); |
| 5075 | </pre> |
| 5076 | |
| 5077 | <p>If the arguments do not all fit on one line, they |
| 5078 | should be broken up onto multiple lines, with each |
| 5079 | subsequent line aligned with the first argument. Do not |
| 5080 | add spaces after the open paren or before the close |
| 5081 | paren:</p> |
| 5082 | <pre>bool result = DoSomething(averyveryveryverylongargument1, |
| 5083 | argument2, argument3); |
| 5084 | </pre> |
| 5085 | |
| 5086 | <p>Arguments may optionally all be placed on subsequent |
| 5087 | lines with a four space indent:</p> |
| 5088 | <pre>if (...) { |
| 5089 | ... |
| 5090 | ... |
| 5091 | if (...) { |
| 5092 | bool result = DoSomething( |
| 5093 | argument1, argument2, // 4 space indent |
| 5094 | argument3, argument4); |
| 5095 | ... |
| 5096 | } |
| 5097 | </pre> |
| 5098 | |
| 5099 | <p>Put multiple arguments on a single line to reduce the |
| 5100 | number of lines necessary for calling a function unless |
| 5101 | there is a specific readability problem. Some find that |
| 5102 | formatting with strictly one argument on each line is |
| 5103 | more readable and simplifies editing of the arguments. |
| 5104 | However, we prioritize for the reader over the ease of |
| 5105 | editing arguments, and most readability problems are |
| 5106 | better addressed with the following techniques.</p> |
| 5107 | |
| 5108 | <p>If having multiple arguments in a single line decreases |
| 5109 | readability due to the complexity or confusing nature of the |
| 5110 | expressions that make up some arguments, try creating |
| 5111 | variables that capture those arguments in a descriptive name:</p> |
| 5112 | <pre>int my_heuristic = scores[x] * y + bases[x]; |
| 5113 | bool result = DoSomething(my_heuristic, x, y, z); |
| 5114 | </pre> |
| 5115 | |
| 5116 | <p>Or put the confusing argument on its own line with |
| 5117 | an explanatory comment:</p> |
| 5118 | <pre>bool result = DoSomething(scores[x] * y + bases[x], // Score heuristic. |
| 5119 | x, y, z); |
| 5120 | </pre> |
| 5121 | |
| 5122 | <p>If there is still a case where one argument is |
| 5123 | significantly more readable on its own line, then put it on |
| 5124 | its own line. The decision should be specific to the argument |
| 5125 | which is made more readable rather than a general policy.</p> |
| 5126 | |
| 5127 | <p>Sometimes arguments form a structure that is important |
| 5128 | for readability. In those cases, feel free to format the |
| 5129 | arguments according to that structure:</p> |
| 5130 | <pre>// Transform the widget by a 3x3 matrix. |
| 5131 | my_widget.Transform(x1, x2, x3, |
| 5132 | y1, y2, y3, |
| 5133 | z1, z2, z3); |
| 5134 | </pre> |
| 5135 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5136 | <h3 id="Braced_Initializer_List_Format">Braced Initializer List Format</h3> |
| 5137 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5138 | <p>Format a <a href="#Braced_Initializer_List">braced initializer list</a> |
| 5139 | exactly like you would format a function call in its place.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5140 | |
| 5141 | <p>If the braced list follows a name (e.g. a type or |
| 5142 | variable name), format as if the <code>{}</code> were the |
| 5143 | parentheses of a function call with that name. If there |
| 5144 | is no name, assume a zero-length name.</p> |
| 5145 | |
| 5146 | <pre>// Examples of braced init list on a single line. |
| 5147 | return {foo, bar}; |
| 5148 | functioncall({foo, bar}); |
| 5149 | std::pair<int, int> p{foo, bar}; |
| 5150 | |
| 5151 | // When you have to wrap. |
| 5152 | SomeFunction( |
| 5153 | {"assume a zero-length name before {"}, |
| 5154 | some_other_function_parameter); |
| 5155 | SomeType variable{ |
| 5156 | some, other, values, |
| 5157 | {"assume a zero-length name before {"}, |
| 5158 | SomeOtherType{ |
| 5159 | "Very long string requiring the surrounding breaks.", |
| 5160 | some, other values}, |
| 5161 | SomeOtherType{"Slightly shorter string", |
| 5162 | some, other, values}}; |
| 5163 | SomeType variable{ |
| 5164 | "This is too long to fit all in one line"}; |
| 5165 | MyType m = { // Here, you could also break before {. |
| 5166 | superlongvariablename1, |
| 5167 | superlongvariablename2, |
| 5168 | {short, interior, list}, |
| 5169 | {interiorwrappinglist, |
| 5170 | interiorwrappinglist2}}; |
| 5171 | </pre> |
| 5172 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5173 | <h3 id="Conditionals">Conditionals</h3> |
| 5174 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5175 | <p>Prefer no spaces inside parentheses. The <code>if</code> |
| 5176 | and <code>else</code> keywords belong on separate lines.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5177 | |
| 5178 | <p>There are two acceptable formats for a basic |
| 5179 | conditional statement. One includes spaces between the |
| 5180 | parentheses and the condition, and one does not.</p> |
| 5181 | |
| 5182 | <p>The most common form is without spaces. Either is |
| 5183 | fine, but <em>be consistent</em>. If you are modifying a |
| 5184 | file, use the format that is already present. If you are |
| 5185 | writing new code, use the format that the other files in |
| 5186 | that directory or project use. If in doubt and you have |
| 5187 | no personal preference, do not add the spaces.</p> |
| 5188 | |
| 5189 | <pre>if (condition) { // no spaces inside parentheses |
| 5190 | ... // 2 space indent. |
| 5191 | } else if (...) { // The else goes on the same line as the closing brace. |
| 5192 | ... |
| 5193 | } else { |
| 5194 | ... |
| 5195 | } |
| 5196 | </pre> |
| 5197 | |
| 5198 | <p>If you prefer you may add spaces inside the |
| 5199 | parentheses:</p> |
| 5200 | |
| 5201 | <pre>if ( condition ) { // spaces inside parentheses - rare |
| 5202 | ... // 2 space indent. |
| 5203 | } else { // The else goes on the same line as the closing brace. |
| 5204 | ... |
| 5205 | } |
| 5206 | </pre> |
| 5207 | |
| 5208 | <p>Note that in all cases you must have a space between |
| 5209 | the <code>if</code> and the open parenthesis. You must |
| 5210 | also have a space between the close parenthesis and the |
| 5211 | curly brace, if you're using one.</p> |
| 5212 | |
| 5213 | <pre class="badcode">if(condition) { // Bad - space missing after IF. |
| 5214 | if (condition){ // Bad - space missing before {. |
| 5215 | if(condition){ // Doubly bad. |
| 5216 | </pre> |
| 5217 | |
| 5218 | <pre>if (condition) { // Good - proper space after IF and before {. |
| 5219 | </pre> |
| 5220 | |
| 5221 | <p>Short conditional statements may be written on one |
| 5222 | line if this enhances readability. You may use this only |
| 5223 | when the line is brief and the statement does not use the |
| 5224 | <code>else</code> clause.</p> |
| 5225 | |
| 5226 | <pre>if (x == kFoo) return new Foo(); |
| 5227 | if (x == kBar) return new Bar(); |
| 5228 | </pre> |
| 5229 | |
| 5230 | <p>This is not allowed when the if statement has an |
| 5231 | <code>else</code>:</p> |
| 5232 | |
| 5233 | <pre class="badcode">// Not allowed - IF statement on one line when there is an ELSE clause |
| 5234 | if (x) DoThis(); |
| 5235 | else DoThat(); |
| 5236 | </pre> |
| 5237 | |
| 5238 | <p>In general, curly braces are not required for |
| 5239 | single-line statements, but they are allowed if you like |
| 5240 | them; conditional or loop statements with complex |
| 5241 | conditions or statements may be more readable with curly |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5242 | braces. Some |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5243 | projects require that an |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5244 | <code>if</code> must always have an accompanying |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5245 | brace.</p> |
| 5246 | |
| 5247 | <pre>if (condition) |
| 5248 | DoSomething(); // 2 space indent. |
| 5249 | |
| 5250 | if (condition) { |
| 5251 | DoSomething(); // 2 space indent. |
| 5252 | } |
| 5253 | </pre> |
| 5254 | |
| 5255 | <p>However, if one part of an |
| 5256 | <code>if</code>-<code>else</code> statement uses curly |
| 5257 | braces, the other part must too:</p> |
| 5258 | |
| 5259 | <pre class="badcode">// Not allowed - curly on IF but not ELSE |
| 5260 | if (condition) { |
| 5261 | foo; |
| 5262 | } else |
| 5263 | bar; |
| 5264 | |
| 5265 | // Not allowed - curly on ELSE but not IF |
| 5266 | if (condition) |
| 5267 | foo; |
| 5268 | else { |
| 5269 | bar; |
| 5270 | } |
| 5271 | </pre> |
| 5272 | |
| 5273 | <pre>// Curly braces around both IF and ELSE required because |
| 5274 | // one of the clauses used braces. |
| 5275 | if (condition) { |
| 5276 | foo; |
| 5277 | } else { |
| 5278 | bar; |
| 5279 | } |
| 5280 | </pre> |
| 5281 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5282 | <h3 id="Loops_and_Switch_Statements">Loops and Switch Statements</h3> |
| 5283 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5284 | <p>Switch statements may use braces for blocks. Annotate |
| 5285 | non-trivial fall-through between cases. |
| 5286 | Braces are optional for single-statement loops. |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5287 | 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] | 5288 | |
| 5289 | <p><code>case</code> blocks in <code>switch</code> |
| 5290 | statements can have curly braces or not, depending on |
| 5291 | your preference. If you do include curly braces they |
| 5292 | should be placed as shown below.</p> |
| 5293 | |
| 5294 | <p>If not conditional on an enumerated value, switch |
| 5295 | statements should always have a <code>default</code> case |
| 5296 | (in the case of an enumerated value, the compiler will |
| 5297 | warn you if any values are not handled). If the default |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5298 | case should never execute, treat this as an error. For example: |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5299 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5300 | </p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5301 | |
| 5302 | <div> |
| 5303 | <pre>switch (var) { |
| 5304 | case 0: { // 2 space indent |
| 5305 | ... // 4 space indent |
| 5306 | break; |
| 5307 | } |
| 5308 | case 1: { |
| 5309 | ... |
| 5310 | break; |
| 5311 | } |
| 5312 | default: { |
| 5313 | assert(false); |
| 5314 | } |
| 5315 | } |
| 5316 | </pre> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5317 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5318 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 5319 | <p>Fall-through from one case label to |
| 5320 | another must be annotated using the |
| 5321 | <code>ABSL_FALLTHROUGH_INTENDED;</code> macro (defined in |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5322 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 5323 | <code>absl/base/macros.h</code>). |
| 5324 | <code>ABSL_FALLTHROUGH_INTENDED;</code> should be placed at a |
| 5325 | point of execution where a fall-through to the next case |
| 5326 | label occurs. A common exception is consecutive case |
| 5327 | labels without intervening code, in which case no |
| 5328 | annotation is needed.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5329 | |
Victor Costan | 4b9c0c0 | 2018-02-20 14:58:48 -0800 | [diff] [blame] | 5330 | <pre>switch (x) { |
| 5331 | case 41: // No annotation needed here. |
| 5332 | case 43: |
| 5333 | if (dont_be_picky) { |
| 5334 | // Use this instead of or along with annotations in comments. |
| 5335 | ABSL_FALLTHROUGH_INTENDED; |
| 5336 | } else { |
| 5337 | CloseButNoCigar(); |
| 5338 | break; |
| 5339 | } |
| 5340 | case 42: |
| 5341 | DoSomethingSpecial(); |
| 5342 | ABSL_FALLTHROUGH_INTENDED; |
| 5343 | default: |
| 5344 | DoSomethingGeneric(); |
| 5345 | break; |
| 5346 | } |
| 5347 | </pre> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5348 | |
| 5349 | <p> Braces are optional for single-statement loops.</p> |
| 5350 | |
| 5351 | <pre>for (int i = 0; i < kSomeNumber; ++i) |
| 5352 | printf("I love you\n"); |
| 5353 | |
| 5354 | for (int i = 0; i < kSomeNumber; ++i) { |
| 5355 | printf("I take it back\n"); |
| 5356 | } |
| 5357 | </pre> |
| 5358 | |
| 5359 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5360 | <p>Empty loop bodies should use either an empty pair of braces or |
| 5361 | <code>continue</code> with no braces, rather than a single semicolon.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5362 | |
| 5363 | <pre>while (condition) { |
| 5364 | // Repeat test until it returns false. |
| 5365 | } |
| 5366 | for (int i = 0; i < kSomeNumber; ++i) {} // Good - one newline is also OK. |
| 5367 | while (condition) continue; // Good - continue indicates no logic. |
| 5368 | </pre> |
| 5369 | |
| 5370 | <pre class="badcode">while (condition); // Bad - looks like part of do/while loop. |
| 5371 | </pre> |
| 5372 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5373 | <h3 id="Pointer_and_Reference_Expressions">Pointer and Reference Expressions</h3> |
| 5374 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5375 | <p>No spaces around period or arrow. Pointer operators do not |
| 5376 | have trailing spaces.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5377 | |
| 5378 | <p>The following are examples of correctly-formatted |
| 5379 | pointer and reference expressions:</p> |
| 5380 | |
| 5381 | <pre>x = *p; |
| 5382 | p = &x; |
| 5383 | x = r.y; |
| 5384 | x = r->y; |
| 5385 | </pre> |
| 5386 | |
| 5387 | <p>Note that:</p> |
| 5388 | |
| 5389 | <ul> |
| 5390 | <li>There are no spaces around the period or arrow when |
| 5391 | accessing a member.</li> |
| 5392 | |
| 5393 | <li>Pointer operators have no space after the |
| 5394 | <code>*</code> or <code>&</code>.</li> |
| 5395 | </ul> |
| 5396 | |
| 5397 | <p>When declaring a pointer variable or argument, you may |
| 5398 | place the asterisk adjacent to either the type or to the |
| 5399 | variable name:</p> |
| 5400 | |
| 5401 | <pre>// These are fine, space preceding. |
| 5402 | char *c; |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5403 | const std::string &str; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5404 | |
| 5405 | // These are fine, space following. |
| 5406 | char* c; |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5407 | const std::string& str; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5408 | </pre> |
| 5409 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5410 | <p>You should do this consistently within a single |
| 5411 | file, |
| 5412 | so, when modifying an existing file, use the style in |
| 5413 | that file.</p> |
| 5414 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5415 | It is allowed (if unusual) to declare multiple variables in the same |
| 5416 | declaration, but it is disallowed if any of those have pointer or |
| 5417 | reference decorations. Such declarations are easily misread. |
| 5418 | <pre>// Fine if helpful for readability. |
| 5419 | int x, y; |
| 5420 | </pre> |
| 5421 | <pre class="badcode">int x, *y; // Disallowed - no & or * in multiple declaration |
| 5422 | char * c; // Bad - spaces on both sides of * |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5423 | const std::string & str; // Bad - spaces on both sides of & |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5424 | </pre> |
| 5425 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5426 | <h3 id="Boolean_Expressions">Boolean Expressions</h3> |
| 5427 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5428 | <p>When you have a boolean expression that is longer than the |
| 5429 | <a href="#Line_Length">standard line length</a>, be |
| 5430 | consistent in how you break up the lines.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5431 | |
| 5432 | <p>In this example, the logical AND operator is always at |
| 5433 | the end of the lines:</p> |
| 5434 | |
| 5435 | <pre>if (this_one_thing > this_other_thing && |
| 5436 | a_third_thing == a_fourth_thing && |
| 5437 | yet_another && last_one) { |
| 5438 | ... |
| 5439 | } |
| 5440 | </pre> |
| 5441 | |
| 5442 | <p>Note that when the code wraps in this example, both of |
| 5443 | the <code>&&</code> logical AND operators are at |
| 5444 | the end of the line. This is more common in Google code, |
| 5445 | though wrapping all operators at the beginning of the |
| 5446 | line is also allowed. Feel free to insert extra |
| 5447 | parentheses judiciously because they can be very helpful |
| 5448 | in increasing readability when used |
| 5449 | appropriately. Also note that you should always use |
| 5450 | the punctuation operators, such as |
| 5451 | <code>&&</code> and <code>~</code>, rather than |
| 5452 | the word operators, such as <code>and</code> and |
| 5453 | <code>compl</code>.</p> |
| 5454 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5455 | <h3 id="Return_Values">Return Values</h3> |
| 5456 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5457 | <p>Do not needlessly surround the <code>return</code> |
| 5458 | expression with parentheses.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5459 | |
| 5460 | <p>Use parentheses in <code>return expr;</code> only |
| 5461 | where you would use them in <code>x = expr;</code>.</p> |
| 5462 | |
| 5463 | <pre>return result; // No parentheses in the simple case. |
| 5464 | // Parentheses OK to make a complex expression more readable. |
| 5465 | return (some_long_condition && |
| 5466 | another_condition); |
| 5467 | </pre> |
| 5468 | |
| 5469 | <pre class="badcode">return (value); // You wouldn't write var = (value); |
| 5470 | return(result); // return is not a function! |
| 5471 | </pre> |
| 5472 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5473 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5474 | |
| 5475 | <h3 id="Variable_and_Array_Initialization">Variable and Array Initialization</h3> |
| 5476 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5477 | <p>Your choice of <code>=</code>, <code>()</code>, or |
| 5478 | <code>{}</code>.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5479 | |
| 5480 | <p>You may choose between <code>=</code>, |
| 5481 | <code>()</code>, and <code>{}</code>; the following are |
| 5482 | all correct:</p> |
| 5483 | |
| 5484 | <pre>int x = 3; |
| 5485 | int x(3); |
| 5486 | int x{3}; |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5487 | std::string name = "Some Name"; |
| 5488 | std::string name("Some Name"); |
| 5489 | std::string name{"Some Name"}; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5490 | </pre> |
| 5491 | |
| 5492 | <p>Be careful when using a braced initialization list <code>{...}</code> |
| 5493 | on a type with an <code>std::initializer_list</code> constructor. |
| 5494 | A nonempty <i>braced-init-list</i> prefers the |
| 5495 | <code>std::initializer_list</code> constructor whenever |
| 5496 | possible. Note that empty braces <code>{}</code> are special, and |
| 5497 | will call a default constructor if available. To force the |
| 5498 | non-<code>std::initializer_list</code> constructor, use parentheses |
| 5499 | instead of braces.</p> |
| 5500 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5501 | <pre>std::vector<int> v(100, 1); // A vector containing 100 items: All 1s. |
| 5502 | 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] | 5503 | </pre> |
| 5504 | |
| 5505 | <p>Also, the brace form prevents narrowing of integral |
| 5506 | types. This can prevent some types of programming |
| 5507 | errors.</p> |
| 5508 | |
| 5509 | <pre>int pi(3.14); // OK -- pi == 3. |
| 5510 | int pi{3.14}; // Compile error: narrowing conversion. |
| 5511 | </pre> |
| 5512 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5513 | <h3 id="Preprocessor_Directives">Preprocessor Directives</h3> |
| 5514 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5515 | <p>The hash mark that starts a preprocessor directive should |
| 5516 | always be at the beginning of the line.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5517 | |
| 5518 | <p>Even when preprocessor directives are within the body |
| 5519 | of indented code, the directives should start at the |
| 5520 | beginning of the line.</p> |
| 5521 | |
| 5522 | <pre>// Good - directives at beginning of line |
| 5523 | if (lopsided_score) { |
| 5524 | #if DISASTER_PENDING // Correct -- Starts at beginning of line |
| 5525 | DropEverything(); |
| 5526 | # if NOTIFY // OK but not required -- Spaces after # |
| 5527 | NotifyClient(); |
| 5528 | # endif |
| 5529 | #endif |
| 5530 | BackToNormal(); |
| 5531 | } |
| 5532 | </pre> |
| 5533 | |
| 5534 | <pre class="badcode">// Bad - indented directives |
| 5535 | if (lopsided_score) { |
| 5536 | #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line |
| 5537 | DropEverything(); |
| 5538 | #endif // Wrong! Do not indent "#endif" |
| 5539 | BackToNormal(); |
| 5540 | } |
| 5541 | </pre> |
| 5542 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5543 | <h3 id="Class_Format">Class Format</h3> |
| 5544 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5545 | <p>Sections in <code>public</code>, <code>protected</code> and |
| 5546 | <code>private</code> order, each indented one space.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5547 | |
| 5548 | <p>The basic format for a class definition (lacking the |
| 5549 | comments, see <a href="#Class_Comments">Class |
| 5550 | Comments</a> for a discussion of what comments are |
| 5551 | needed) is:</p> |
| 5552 | |
| 5553 | <pre>class MyClass : public OtherClass { |
| 5554 | public: // Note the 1 space indent! |
| 5555 | MyClass(); // Regular 2 space indent. |
| 5556 | explicit MyClass(int var); |
| 5557 | ~MyClass() {} |
| 5558 | |
| 5559 | void SomeFunction(); |
| 5560 | void SomeFunctionThatDoesNothing() { |
| 5561 | } |
| 5562 | |
| 5563 | void set_some_var(int var) { some_var_ = var; } |
| 5564 | int some_var() const { return some_var_; } |
| 5565 | |
| 5566 | private: |
| 5567 | bool SomeInternalFunction(); |
| 5568 | |
| 5569 | int some_var_; |
| 5570 | int some_other_var_; |
| 5571 | }; |
| 5572 | </pre> |
| 5573 | |
| 5574 | <p>Things to note:</p> |
| 5575 | |
| 5576 | <ul> |
| 5577 | <li>Any base class name should be on the same line as |
| 5578 | the subclass name, subject to the 80-column limit.</li> |
| 5579 | |
| 5580 | <li>The <code>public:</code>, <code>protected:</code>, |
| 5581 | and <code>private:</code> keywords should be indented |
| 5582 | one space.</li> |
| 5583 | |
| 5584 | <li>Except for the first instance, these keywords |
| 5585 | should be preceded by a blank line. This rule is |
| 5586 | optional in small classes.</li> |
| 5587 | |
| 5588 | <li>Do not leave a blank line after these |
| 5589 | keywords.</li> |
| 5590 | |
| 5591 | <li>The <code>public</code> section should be first, |
| 5592 | followed by the <code>protected</code> and finally the |
| 5593 | <code>private</code> section.</li> |
| 5594 | |
| 5595 | <li>See <a href="#Declaration_Order">Declaration |
| 5596 | Order</a> for rules on ordering declarations within |
| 5597 | each of these sections.</li> |
| 5598 | </ul> |
| 5599 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5600 | <h3 id="Constructor_Initializer_Lists">Constructor Initializer Lists</h3> |
| 5601 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5602 | <p>Constructor initializer lists can be all on one line or |
| 5603 | with subsequent lines indented four spaces.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5604 | |
| 5605 | <p>The acceptable formats for initializer lists are:</p> |
| 5606 | |
| 5607 | <pre>// When everything fits on one line: |
| 5608 | MyClass::MyClass(int var) : some_var_(var) { |
| 5609 | DoSomething(); |
| 5610 | } |
| 5611 | |
| 5612 | // If the signature and initializer list are not all on one line, |
| 5613 | // you must wrap before the colon and indent 4 spaces: |
| 5614 | MyClass::MyClass(int var) |
| 5615 | : some_var_(var), some_other_var_(var + 1) { |
| 5616 | DoSomething(); |
| 5617 | } |
| 5618 | |
| 5619 | // When the list spans multiple lines, put each member on its own line |
| 5620 | // and align them: |
| 5621 | MyClass::MyClass(int var) |
| 5622 | : some_var_(var), // 4 space indent |
| 5623 | some_other_var_(var + 1) { // lined up |
| 5624 | DoSomething(); |
| 5625 | } |
| 5626 | |
| 5627 | // As with any other code block, the close curly can be on the same |
| 5628 | // line as the open curly, if it fits. |
| 5629 | MyClass::MyClass(int var) |
| 5630 | : some_var_(var) {} |
| 5631 | </pre> |
| 5632 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5633 | <h3 id="Namespace_Formatting">Namespace Formatting</h3> |
| 5634 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5635 | <p>The contents of namespaces are not indented.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5636 | |
| 5637 | <p><a href="#Namespaces">Namespaces</a> do not add an |
| 5638 | extra level of indentation. For example, use:</p> |
| 5639 | |
| 5640 | <pre>namespace { |
| 5641 | |
| 5642 | void foo() { // Correct. No extra indentation within namespace. |
| 5643 | ... |
| 5644 | } |
| 5645 | |
| 5646 | } // namespace |
| 5647 | </pre> |
| 5648 | |
| 5649 | <p>Do not indent within a namespace:</p> |
| 5650 | |
| 5651 | <pre class="badcode">namespace { |
| 5652 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5653 | // Wrong! Indented when it should not be. |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5654 | void foo() { |
| 5655 | ... |
| 5656 | } |
| 5657 | |
| 5658 | } // namespace |
| 5659 | </pre> |
| 5660 | |
| 5661 | <p>When declaring nested namespaces, put each namespace |
| 5662 | on its own line.</p> |
| 5663 | |
| 5664 | <pre>namespace foo { |
| 5665 | namespace bar { |
| 5666 | </pre> |
| 5667 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5668 | <h3 id="Horizontal_Whitespace">Horizontal Whitespace</h3> |
| 5669 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5670 | <p>Use of horizontal whitespace depends on location. Never put |
| 5671 | trailing whitespace at the end of a line.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5672 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5673 | <h4>General</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5674 | |
| 5675 | <pre>void f(bool b) { // Open braces should always have a space before them. |
| 5676 | ... |
| 5677 | int i = 0; // Semicolons usually have no space before them. |
| 5678 | // Spaces inside braces for braced-init-list are optional. If you use them, |
| 5679 | // put them on both sides! |
| 5680 | int x[] = { 0 }; |
| 5681 | int x[] = {0}; |
| 5682 | |
| 5683 | // Spaces around the colon in inheritance and initializer lists. |
| 5684 | class Foo : public Bar { |
| 5685 | public: |
| 5686 | // For inline function implementations, put spaces between the braces |
| 5687 | // and the implementation itself. |
| 5688 | Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces. |
| 5689 | void Reset() { baz_ = 0; } // Spaces separating braces from implementation. |
| 5690 | ... |
| 5691 | </pre> |
| 5692 | |
| 5693 | <p>Adding trailing whitespace can cause extra work for |
| 5694 | others editing the same file, when they merge, as can |
| 5695 | removing existing trailing whitespace. So: Don't |
| 5696 | introduce trailing whitespace. Remove it if you're |
| 5697 | already changing that line, or do it in a separate |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5698 | clean-up |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5699 | operation (preferably when no-one |
| 5700 | else is working on the file).</p> |
| 5701 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5702 | <h4>Loops and Conditionals</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5703 | |
| 5704 | <pre>if (b) { // Space after the keyword in conditions and loops. |
| 5705 | } else { // Spaces around else. |
| 5706 | } |
| 5707 | while (test) {} // There is usually no space inside parentheses. |
| 5708 | switch (i) { |
| 5709 | for (int i = 0; i < 5; ++i) { |
| 5710 | // Loops and conditions may have spaces inside parentheses, but this |
| 5711 | // is rare. Be consistent. |
| 5712 | switch ( i ) { |
| 5713 | if ( test ) { |
| 5714 | for ( int i = 0; i < 5; ++i ) { |
| 5715 | // For loops always have a space after the semicolon. They may have a space |
| 5716 | // before the semicolon, but this is rare. |
| 5717 | for ( ; i < 5 ; ++i) { |
| 5718 | ... |
| 5719 | |
| 5720 | // Range-based for loops always have a space before and after the colon. |
| 5721 | for (auto x : counts) { |
| 5722 | ... |
| 5723 | } |
| 5724 | switch (i) { |
| 5725 | case 1: // No space before colon in a switch case. |
| 5726 | ... |
| 5727 | case 2: break; // Use a space after a colon if there's code after it. |
| 5728 | </pre> |
| 5729 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5730 | <h4>Operators</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5731 | |
| 5732 | <pre>// Assignment operators always have spaces around them. |
| 5733 | x = 0; |
| 5734 | |
| 5735 | // Other binary operators usually have spaces around them, but it's |
| 5736 | // OK to remove spaces around factors. Parentheses should have no |
| 5737 | // internal padding. |
| 5738 | v = w * x + y / z; |
| 5739 | v = w*x + y/z; |
| 5740 | v = w * (x + z); |
| 5741 | |
| 5742 | // No spaces separating unary operators and their arguments. |
| 5743 | x = -5; |
| 5744 | ++x; |
| 5745 | if (x && !y) |
| 5746 | ... |
| 5747 | </pre> |
| 5748 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5749 | <h4>Templates and Casts</h4> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5750 | |
| 5751 | <pre>// No spaces inside the angle brackets (< and >), before |
| 5752 | // <, or between >( in a cast |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5753 | std::vector<std::string> x; |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5754 | y = static_cast<char*>(x); |
| 5755 | |
| 5756 | // Spaces between type and pointer are OK, but be consistent. |
| 5757 | std::vector<char *> x; |
| 5758 | </pre> |
| 5759 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5760 | <h3 id="Vertical_Whitespace">Vertical Whitespace</h3> |
| 5761 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5762 | <p>Minimize use of vertical whitespace.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5763 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5764 | <p>This is more a principle than a rule: don't use blank lines when |
| 5765 | you don't have to. In particular, don't put more than one or two blank |
| 5766 | lines between functions, resist starting functions with a blank line, |
| 5767 | don't end functions with a blank line, and be sparing with your use of |
| 5768 | blank lines. A blank line within a block of code serves like a |
| 5769 | paragraph break in prose: visually separating two thoughts.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5770 | |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5771 | <p>The basic principle is: The more code that fits on one screen, the |
| 5772 | easier it is to follow and understand the control flow of the |
| 5773 | program. Use whitespace purposefully to provide separation in that |
| 5774 | flow.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5775 | |
| 5776 | <p>Some rules of thumb to help when blank lines may be |
| 5777 | useful:</p> |
| 5778 | |
| 5779 | <ul> |
| 5780 | <li>Blank lines at the beginning or end of a function |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5781 | do not help readability.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5782 | |
| 5783 | <li>Blank lines inside a chain of if-else blocks may |
| 5784 | well help readability.</li> |
Victor Costan | b89a775 | 2018-07-31 10:17:48 -0700 | [diff] [blame] | 5785 | |
| 5786 | <li>A blank line before a comment line usually helps |
| 5787 | readability — the introduction of a new comment suggests |
| 5788 | the start of a new thought, and the blank line makes it clear |
| 5789 | that the comment goes with the following thing instead of the |
| 5790 | preceding.</li> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5791 | </ul> |
| 5792 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5793 | <h2 id="Exceptions_to_the_Rules">Exceptions to the Rules</h2> |
| 5794 | |
| 5795 | <p>The coding conventions described above are mandatory. |
| 5796 | However, like all good rules, these sometimes have exceptions, |
| 5797 | which we discuss here.</p> |
| 5798 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5799 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5800 | |
| 5801 | <div> |
| 5802 | <h3 id="Existing_Non-conformant_Code">Existing Non-conformant Code</h3> |
| 5803 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5804 | <p>You may diverge from the rules when dealing with code that |
| 5805 | does not conform to this style guide.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5806 | |
| 5807 | <p>If you find yourself modifying code that was written |
| 5808 | to specifications other than those presented by this |
| 5809 | guide, you may have to diverge from these rules in order |
| 5810 | to stay consistent with the local conventions in that |
| 5811 | code. If you are in doubt about how to do this, ask the |
| 5812 | original author or the person currently responsible for |
| 5813 | the code. Remember that <em>consistency</em> includes |
| 5814 | local consistency, too.</p> |
| 5815 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5816 | </div> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5817 | |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5818 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5819 | |
| 5820 | <h3 id="Windows_Code">Windows Code</h3> |
| 5821 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5822 | <p> Windows |
| 5823 | programmers have developed their own set of coding |
| 5824 | conventions, mainly derived from the conventions in Windows |
| 5825 | headers and other Microsoft code. We want to make it easy |
| 5826 | for anyone to understand your code, so we have a single set |
| 5827 | of guidelines for everyone writing C++ on any platform.</p> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5828 | |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5829 | <p>It is worth reiterating a few of the guidelines that |
| 5830 | you might forget if you are used to the prevalent Windows |
| 5831 | style:</p> |
| 5832 | |
| 5833 | <ul> |
| 5834 | <li>Do not use Hungarian notation (for example, naming |
| 5835 | an integer <code>iNum</code>). Use the Google naming |
| 5836 | conventions, including the <code>.cc</code> extension |
| 5837 | for source files.</li> |
| 5838 | |
| 5839 | <li>Windows defines many of its own synonyms for |
| 5840 | primitive types, such as <code>DWORD</code>, |
| 5841 | <code>HANDLE</code>, etc. It is perfectly acceptable, |
| 5842 | and encouraged, that you use these types when calling |
| 5843 | Windows API functions. Even so, keep as close as you |
| 5844 | can to the underlying C++ types. For example, use |
| 5845 | <code>const TCHAR *</code> instead of |
| 5846 | <code>LPCTSTR</code>.</li> |
| 5847 | |
| 5848 | <li>When compiling with Microsoft Visual C++, set the |
| 5849 | compiler to warning level 3 or higher, and treat all |
| 5850 | warnings as errors.</li> |
| 5851 | |
| 5852 | <li>Do not use <code>#pragma once</code>; instead use |
| 5853 | the standard Google include guards. The path in the |
| 5854 | include guards should be relative to the top of your |
| 5855 | project tree.</li> |
| 5856 | |
| 5857 | <li>In fact, do not use any nonstandard extensions, |
| 5858 | like <code>#pragma</code> and <code>__declspec</code>, |
| 5859 | unless you absolutely must. Using |
| 5860 | <code>__declspec(dllimport)</code> and |
| 5861 | <code>__declspec(dllexport)</code> is allowed; however, |
| 5862 | you must use them through macros such as |
| 5863 | <code>DLLIMPORT</code> and <code>DLLEXPORT</code>, so |
| 5864 | that someone can easily disable the extensions if they |
| 5865 | share the code.</li> |
| 5866 | </ul> |
| 5867 | |
| 5868 | <p>However, there are just a few rules that we |
| 5869 | occasionally need to break on Windows:</p> |
| 5870 | |
| 5871 | <ul> |
Victor Costan | f0314ea | 2019-09-01 20:42:44 -0700 | [diff] [blame] | 5872 | <li>Normally we <a href="#Multiple_Inheritance">strongly discourage |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5873 | the use of multiple implementation inheritance</a>; |
| 5874 | however, it is required when using COM and some ATL/WTL |
| 5875 | classes. You may use multiple implementation |
| 5876 | inheritance to implement COM or ATL/WTL classes and |
| 5877 | interfaces.</li> |
| 5878 | |
| 5879 | <li>Although you should not use exceptions in your own |
| 5880 | code, they are used extensively in the ATL and some |
| 5881 | STLs, including the one that comes with Visual C++. |
| 5882 | When using the ATL, you should define |
| 5883 | <code>_ATL_NO_EXCEPTIONS</code> to disable exceptions. |
| 5884 | You should investigate whether you can also disable |
| 5885 | exceptions in your STL, but if not, it is OK to turn on |
| 5886 | exceptions in the compiler. (Note that this is only to |
| 5887 | get the STL to compile. You should still not write |
| 5888 | exception handling code yourself.)</li> |
| 5889 | |
| 5890 | <li>The usual way of working with precompiled headers |
| 5891 | is to include a header file at the top of each source |
| 5892 | file, typically with a name like <code>StdAfx.h</code> |
| 5893 | or <code>precompile.h</code>. To make your code easier |
| 5894 | to share with other projects, avoid including this file |
| 5895 | explicitly (except in <code>precompile.cc</code>), and |
| 5896 | use the <code>/FI</code> compiler option to include the |
| 5897 | file automatically.</li> |
| 5898 | |
| 5899 | <li>Resource headers, which are usually named |
| 5900 | <code>resource.h</code> and contain only macros, do not |
| 5901 | need to conform to these style guidelines.</li> |
| 5902 | </ul> |
| 5903 | |
Victor Costan | 6dfd9d9 | 2018-02-05 18:30:35 -0800 | [diff] [blame] | 5904 | <h2 id="Parting_Words">Parting Words</h2> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5905 | |
| 5906 | <p>Use common sense and <em>BE CONSISTENT</em>.</p> |
| 5907 | |
| 5908 | <p>If you are editing code, take a few minutes to look at the |
| 5909 | code around you and determine its style. If they use spaces |
| 5910 | around their <code>if</code> clauses, you should, too. If their |
| 5911 | comments have little boxes of stars around them, make your |
| 5912 | comments have little boxes of stars around them too.</p> |
| 5913 | |
| 5914 | <p>The point of having style guidelines is to have a common |
| 5915 | vocabulary of coding so people can concentrate on what you are |
| 5916 | saying, rather than on how you are saying it. We present global |
| 5917 | style rules here so people know the vocabulary. But local style |
| 5918 | is also important. If code you add to a file looks drastically |
| 5919 | different from the existing code around it, the discontinuity |
| 5920 | throws readers out of their rhythm when they go to read it. Try |
| 5921 | to avoid this.</p> |
| 5922 | |
| 5923 | |
| 5924 | |
| 5925 | <p>OK, enough writing about writing code; the code itself is much |
| 5926 | more interesting. Have fun!</p> |
| 5927 | |
| 5928 | <hr> |
Ted Osborne | 505ba68 | 2018-01-30 12:36:50 -0500 | [diff] [blame] | 5929 | </div> |
| 5930 | </body> |
| 5931 | </html> |