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