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