fix missing forward for function object parameter (#2092)
[CppCoreGuidelines.git] / CppCoreGuidelines.md
blob9ab5e60b1595568e4a81b31372755baafeb08214
1 # <a name="main"></a>C++ Core Guidelines
3 October 12, 2023
5 Editors:
7 * [Bjarne Stroustrup](http://www.stroustrup.com)
8 * [Herb Sutter](http://herbsutter.com/)
10 This is a living document under continuous improvement.
11 Had it been an open-source (code) project, this would have been release 0.8.
12 Copying, use, modification, and creation of derivative works from this project is licensed under an MIT-style license.
13 Contributing to this project requires agreeing to a Contributor License. See the accompanying [LICENSE](LICENSE) file for details.
14 We make this project available to "friendly users" to use, copy, modify, and derive from, hoping for constructive input.
16 Comments and suggestions for improvements are most welcome.
17 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
18 When commenting, please note [the introduction](#S-introduction) that outlines our aims and general approach.
19 The list of contributors is [here](#SS-ack).
21 Problems:
23 * The sets of rules have not been completely checked for completeness, consistency, or enforceability.
24 * Triple question marks (???) mark known missing information
25 * Update reference sections; many pre-C++11 sources are too old.
26 * For a more-or-less up-to-date to-do list see: [To-do: Unclassified proto-rules](#S-unclassified)
28 You can [read an explanation of the scope and structure of this Guide](#S-abstract) or just jump straight in:
30 * [In: Introduction](#S-introduction)
31 * [P: Philosophy](#S-philosophy)
32 * [I: Interfaces](#S-interfaces)
33 * [F: Functions](#S-functions)
34 * [C: Classes and class hierarchies](#S-class)
35 * [Enum: Enumerations](#S-enum)
36 * [R: Resource management](#S-resource)
37 * [ES: Expressions and statements](#S-expr)
38 * [Per: Performance](#S-performance)
39 * [CP: Concurrency and parallelism](#S-concurrency)
40 * [E: Error handling](#S-errors)
41 * [Con: Constants and immutability](#S-const)
42 * [T: Templates and generic programming](#S-templates)
43 * [CPL: C-style programming](#S-cpl)
44 * [SF: Source files](#S-source)
45 * [SL: The Standard Library](#sl-the-standard-library)
47 Supporting sections:
49 * [A: Architectural ideas](#S-A)
50 * [NR: Non-Rules and myths](#S-not)
51 * [RF: References](#S-references)
52 * [Pro: Profiles](#S-profile)
53 * [GSL: Guidelines support library](#gsl-guidelines-support-library)
54 * [NL: Naming and layout suggestions](#S-naming)
55 * [FAQ: Answers to frequently asked questions](#S-faq)
56 * [Appendix A: Libraries](#S-libraries)
57 * [Appendix B: Modernizing code](#S-modernizing)
58 * [Appendix C: Discussion](#S-discussion)
59 * [Appendix D: Supporting tools](#S-tools)
60 * [Glossary](#S-glossary)
61 * [To-do: Unclassified proto-rules](#S-unclassified)
63 You can sample rules for specific language features:
65 * assignment:
66 [regular types](#Rc-regular) --
67 [prefer initialization](#Rc-initialize) --
68 [copy](#Rc-copy-semantic) --
69 [move](#Rc-move-semantic) --
70 [other operations](#Rc-matched) --
71 [default](#Rc-eqdefault)
72 * `class`:
73 [data](#Rc-org) --
74 [invariant](#Rc-struct) --
75 [members](#Rc-member) --
76 [helpers](#Rc-helper) --
77 [concrete types](#SS-concrete) --
78 [ctors, =, and dtors](#S-ctor) --
79 [hierarchy](#SS-hier) --
80 [operators](#SS-overload)
81 * `concept`:
82 [rules](#SS-concepts) --
83 [in generic programming](#Rt-raise) --
84 [template arguments](#Rt-concepts) --
85 [semantics](#Rt-low)
86 * constructor:
87 [invariant](#Rc-struct) --
88 [establish invariant](#Rc-ctor) --
89 [`throw`](#Rc-throw) --
90 [default](#Rc-default0) --
91 [not needed](#Rc-default) --
92 [`explicit`](#Rc-explicit) --
93 [delegating](#Rc-delegating) --
94 [`virtual`](#Rc-ctor-virtual)
95 * derived `class`:
96 [when to use](#Rh-domain) --
97 [as interface](#Rh-abstract) --
98 [destructors](#Rh-dtor) --
99 [copy](#Rh-copy) --
100 [getters and setters](#Rh-get) --
101 [multiple inheritance](#Rh-mi-interface) --
102 [overloading](#Rh-using) --
103 [slicing](#Rc-copy-virtual) --
104 [`dynamic_cast`](#Rh-dynamic_cast)
105 * destructor:
106 [and constructors](#Rc-matched) --
107 [when needed?](#Rc-dtor) --
108 [must not fail](#Rc-dtor-fail)
109 * exception:
110 [errors](#S-errors) --
111 [`throw`](#Re-throw) --
112 [for errors only](#Re-errors) --
113 [`noexcept`](#Re-noexcept) --
114 [minimize `try`](#Re-catch) --
115 [what if no exceptions?](#Re-no-throw-codes)
116 * `for`:
117 [range-for and for](#Res-for-range) --
118 [for and while](#Res-for-while) --
119 [for-initializer](#Res-for-init) --
120 [empty body](#Res-empty) --
121 [loop variable](#Res-loop-counter) --
122 [loop variable type ???](#Res-???)
123 * function:
124 [naming](#Rf-package) --
125 [single operation](#Rf-logical) --
126 [no throw](#Rf-noexcept) --
127 [arguments](#Rf-smart) --
128 [argument passing](#Rf-conventional) --
129 [multiple return values](#Rf-out-multi) --
130 [pointers](#Rf-return-ptr) --
131 [lambdas](#Rf-capture-vs-overload)
132 * `inline`:
133 [small functions](#Rf-inline) --
134 [in headers](#Rs-inline)
135 * initialization:
136 [always](#Res-always) --
137 [prefer `{}`](#Res-list) --
138 [lambdas](#Res-lambda-init) --
139 [default member initializers](#Rc-in-class-initializer) --
140 [class members](#Rc-initialize) --
141 [factory functions](#Rc-factory)
142 * lambda expression:
143 [when to use](#SS-lambdas)
144 * operator:
145 [conventional](#Ro-conventional) --
146 [avoid conversion operators](#Ro-conversion) --
147 [and lambdas](#Ro-lambda)
148 * `public`, `private`, and `protected`:
149 [information hiding](#Rc-private) --
150 [consistency](#Rh-public) --
151 [`protected`](#Rh-protected)
152 * `static_assert`:
153 [compile-time checking](#Rp-compile-time) --
154 [and concepts](#Rt-check-class)
155 * `struct`:
156 [for organizing data](#Rc-org) --
157 [use if no invariant](#Rc-struct) --
158 [no private members](#Rc-class)
159 * `template`:
160 [abstraction](#Rt-raise) --
161 [containers](#Rt-cont) --
162 [concepts](#Rt-concepts)
163 * `unsigned`:
164 [and signed](#Res-mix) --
165 [bit manipulation](#Res-unsigned)
166 * `virtual`:
167 [interfaces](#Ri-abstract) --
168 [not `virtual`](#Rc-concrete) --
169 [destructor](#Rc-dtor-virtual) --
170 [never fail](#Rc-dtor-fail)
172 You can look at design concepts used to express the rules:
174 * assertion: ???
175 * error: ???
176 * exception: exception guarantee (???)
177 * failure: ???
178 * invariant: ???
179 * leak: ???
180 * library: ???
181 * precondition: ???
182 * postcondition: ???
183 * resource: ???
185 # <a name="S-abstract"></a>Abstract
187 This document is a set of guidelines for using C++ well.
188 The aim of this document is to help people to use modern C++ effectively.
189 By "modern C++" we mean effective use of the ISO C++ standard (currently C++20, but almost all of our recommendations also apply to C++17, C++14 and C++11).
190 In other words, what would you like your code to look like in 5 years' time, given that you can start now? In 10 years' time?
192 The guidelines are focused on relatively high-level issues, such as interfaces, resource management, memory management, and concurrency.
193 Such rules affect application architecture and library design.
194 Following the rules will lead to code that is statically type safe, has no resource leaks, and catches many more programming logic errors than is common in code today.
195 And it will run fast -- you can afford to do things right.
197 We are less concerned with low-level issues, such as naming conventions and indentation style.
198 However, no topic that can help a programmer is out of bounds.
200 Our initial set of rules emphasizes safety (of various forms) and simplicity.
201 They might very well be too strict.
202 We expect to have to introduce more exceptions to better accommodate real-world needs.
203 We also need more rules.
205 You will find some of the rules contrary to your expectations or even contrary to your experience.
206 If we haven't suggested you change your coding style in any way, we have failed!
207 Please try to verify or disprove rules!
208 In particular, we'd really like to have some of our rules backed up with measurements or better examples.
210 You will find some of the rules obvious or even trivial.
211 Please remember that one purpose of a guideline is to help someone who is less experienced or coming from a different background or language to get up to speed.
213 Many of the rules are designed to be supported by an analysis tool.
214 Violations of rules will be flagged with references (or links) to the relevant rule.
215 We do not expect you to memorize all the rules before trying to write code.
216 One way of thinking about these guidelines is as a specification for tools that happens to be readable by humans.
218 The rules are meant for gradual introduction into a code base.
219 We plan to build tools for that and hope others will too.
221 Comments and suggestions for improvements are most welcome.
222 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
224 # <a name="S-introduction"></a>In: Introduction
226 This is a set of core guidelines for modern C++ (currently C++20 and C++17) taking likely future enhancements and ISO Technical Specifications (TSs) into account.
227 The aim is to help C++ programmers to write simpler, more efficient, more maintainable code.
229 Introduction summary:
231 * [In.target: Target readership](#SS-readers)
232 * [In.aims: Aims](#SS-aims)
233 * [In.not: Non-aims](#SS-non)
234 * [In.force: Enforcement](#SS-force)
235 * [In.struct: The structure of this document](#SS-struct)
236 * [In.sec: Major sections](#SS-sec)
238 ## <a name="SS-readers"></a>In.target: Target readership
240 All C++ programmers. This includes [programmers who might consider C](#S-cpl).
242 ## <a name="SS-aims"></a>In.aims: Aims
244 The purpose of this document is to help developers to adopt modern C++ (currently C++20 and C++17) and to achieve a more uniform style across code bases.
246 We do not suffer the delusion that every one of these rules can be effectively applied to every code base. Upgrading old systems is hard. However, we do believe that a program that uses a rule is less error-prone and more maintainable than one that does not. Often, rules also lead to faster/easier initial development.
247 As far as we can tell, these rules lead to code that performs as well or better than older, more conventional techniques; they are meant to follow the zero-overhead principle ("what you don't use, you don't pay for" or "when you use an abstraction mechanism appropriately, you get at least as good performance as if you had handcoded using lower-level language constructs").
248 Consider these rules ideals for new code, opportunities to exploit when working on older code, and try to approximate these ideals as closely as feasible.
249 Remember:
251 ### <a name="R0"></a>In.0: Don't panic!
253 Take the time to understand the implications of a guideline rule on your program.
255 These guidelines are designed according to the "subset of superset" principle ([Stroustrup05](#Stroustrup05)).
256 They do not simply define a subset of C++ to be used (for reliability, safety, performance, or whatever).
257 Instead, they strongly recommend the use of a few simple "extensions" ([library components](#gsl-guidelines-support-library))
258 that make the use of the most error-prone features of C++ redundant, so that they can be banned (in our set of rules).
260 The rules emphasize static type safety and resource safety.
261 For that reason, they emphasize possibilities for range checking, for avoiding dereferencing `nullptr`, for avoiding dangling pointers, and the systematic use of exceptions (via RAII).
262 Partly to achieve that and partly to minimize obscure code as a source of errors, the rules also emphasize simplicity and the hiding of necessary complexity behind well-specified interfaces.
264 Many of the rules are prescriptive.
265 We are uncomfortable with rules that simply state "don't do that!" without offering an alternative.
266 One consequence of that is that some rules can be supported only by heuristics, rather than precise and mechanically verifiable checks.
267 Other rules articulate general principles. For these more general rules, more detailed and specific rules provide partial checking.
269 These guidelines address the core of C++ and its use.
270 We expect that most large organizations, specific application areas, and even large projects will need further rules, possibly further restrictions, and further library support.
271 For example, hard-real-time programmers typically can't use free store (dynamic memory) freely and will be restricted in their choice of libraries.
272 We encourage the development of such more specific rules as addenda to these core guidelines.
273 Build your ideal small foundation library and use that, rather than lowering your level of programming to glorified assembly code.
275 The rules are designed to allow [gradual adoption](#S-modernizing).
277 Some rules aim to increase various forms of safety while others aim to reduce the likelihood of accidents, many do both.
278 The guidelines aimed at preventing accidents often ban perfectly legal C++.
279 However, when there are two ways of expressing an idea and one has shown itself a common source of errors and the other has not, we try to guide programmers towards the latter.
281 ## <a name="SS-non"></a>In.not: Non-aims
283 The rules are not intended to be minimal or orthogonal.
284 In particular, general rules can be simple, but unenforceable.
285 Also, it is often hard to understand the implications of a general rule.
286 More specialized rules are often easier to understand and to enforce, but without general rules, they would just be a long list of special cases.
287 We provide rules aimed at helping novices as well as rules supporting expert use.
288 Some rules can be completely enforced, but others are based on heuristics.
290 These rules are not meant to be read serially, like a book.
291 You can browse through them using the links.
292 However, their main intended use is to be targets for tools.
293 That is, a tool looks for violations and the tool returns links to violated rules.
294 The rules then provide reasons, examples of potential consequences of the violation, and suggested remedies.
296 These guidelines are not intended to be a substitute for a tutorial treatment of C++.
297 If you need a tutorial for some given level of experience, see [the references](#S-references).
299 This is not a guide on how to convert old C++ code to more modern code.
300 It is meant to articulate ideas for new code in a concrete fashion.
301 However, see [the modernization section](#S-modernizing) for some possible approaches to modernizing/rejuvenating/upgrading.
302 Importantly, the rules support gradual adoption: It is typically infeasible to completely convert a large code base all at once.
304 These guidelines are not meant to be complete or exact in every language-technical detail.
305 For the final word on language definition issues, including every exception to general rules and every feature, see the ISO C++ standard.
307 The rules are not intended to force you to write in an impoverished subset of C++.
308 They are *emphatically* not meant to define a, say, Java-like subset of C++.
309 They are not meant to define a single "one true C++" language.
310 We value expressiveness and uncompromised performance.
312 The rules are not value-neutral.
313 They are meant to make code simpler and more correct/safer than most existing C++ code, without loss of performance.
314 They are meant to inhibit perfectly valid C++ code that correlates with errors, spurious complexity, and poor performance.
316 The rules are not precise to the point where a person (or machine) can follow them without thinking.
317 The enforcement parts try to be that, but we would rather leave a rule or a definition a bit vague
318 and open to interpretation than specify something precisely and wrong.
319 Sometimes, precision comes only with time and experience.
320 Design is not (yet) a form of Math.
322 The rules are not perfect.
323 A rule can do harm by prohibiting something that is useful in a given situation.
324 A rule can do harm by failing to prohibit something that enables a serious error in a given situation.
325 A rule can do a lot of harm by being vague, ambiguous, unenforceable, or by enabling every solution to a problem.
326 It is impossible to completely meet the "do no harm" criteria.
327 Instead, our aim is the less ambitious: "Do the most good for most programmers";
328 if you cannot live with a rule, object to it, ignore it, but don't water it down until it becomes meaningless.
329 Also, suggest an improvement.
331 ## <a name="SS-force"></a>In.force: Enforcement
333 Rules with no enforcement are unmanageable for large code bases.
334 Enforcement of all rules is possible only for a small weak set of rules or for a specific user community.
336 * But we want lots of rules, and we want rules that everybody can use.
337 * But different people have different needs.
338 * But people don't like to read lots of rules.
339 * But people can't remember many rules.
341 So, we need subsetting to meet a variety of needs.
343 * But arbitrary subsetting leads to chaos.
345 We want guidelines that help a lot of people, make code more uniform, and strongly encourage people to modernize their code.
346 We want to encourage best practices, rather than leave all to individual choices and management pressures.
347 The ideal is to use all rules; that gives the greatest benefits.
349 This adds up to quite a few dilemmas.
350 We try to resolve those using tools.
351 Each rule has an **Enforcement** section listing ideas for enforcement.
352 Enforcement might be done by code review, by static analysis, by compiler, or by run-time checks.
353 Wherever possible, we prefer "mechanical" checking (humans are slow, inaccurate, and bore easily) and static checking.
354 Run-time checks are suggested only rarely where no alternative exists; we do not want to introduce "distributed bloat".
355 Where appropriate, we label a rule (in the **Enforcement** sections) with the name of groups of related rules (called "profiles").
356 A rule can be part of several profiles, or none.
357 For a start, we have a few profiles corresponding to common needs (desires, ideals):
359 * **type**: No type violations (reinterpreting a `T` as a `U` through casts, unions, or varargs)
360 * **bounds**: No bounds violations (accessing beyond the range of an array)
361 * **lifetime**: No leaks (failing to `delete` or multiple `delete`) and no access to invalid objects (dereferencing `nullptr`, using a dangling reference).
363 The profiles are intended to be used by tools, but also serve as an aid to the human reader.
364 We do not limit our comment in the **Enforcement** sections to things we know how to enforce; some comments are mere wishes that might inspire some tool builder.
366 Tools that implement these rules shall respect the following syntax to explicitly suppress a rule:
368     [[gsl::suppress(tag)]]
370 and optionally with a message (following usual C++11 standard attribute syntax):
372     [[gsl::suppress(tag, justification: "message")]]
374 where
376 * `tag` is the anchor name of the item where the Enforcement rule appears (e.g., for [C.134](#Rh-public) it is "Rh-public"), the
377 name of a profile group-of-rules ("type", "bounds", or "lifetime"),
378 or a specific rule in a profile ([type.4](#Pro-type-cstylecast), or [bounds.2](#Pro-bounds-arrayindex))
380 * `"message"` is a string literal
382 ## <a name="SS-struct"></a>In.struct: The structure of this document
384 Each rule (guideline, suggestion) can have several parts:
386 * The rule itself -- e.g., **no naked `new`**
387 * A rule reference number -- e.g., **C.7** (the 7th rule related to classes).
388   Since the major sections are not inherently ordered, we use letters as the first part of a rule reference "number".
389   We leave gaps in the numbering to minimize "disruption" when we add or remove rules.
390 * **Reason**s (rationales) -- because programmers find it hard to follow rules they don't understand
391 * **Example**s -- because rules are hard to understand in the abstract; can be positive or negative
392 * **Alternative**s -- for "don't do this" rules
393 * **Exception**s -- we prefer simple general rules. However, many rules apply widely, but not universally, so exceptions must be listed
394 * **Enforcement** -- ideas about how the rule might be checked "mechanically"
395 * **See also**s -- references to related rules and/or further discussion (in this document or elsewhere)
396 * **Note**s (comments) -- something that needs saying that doesn't fit the other classifications
397 * **Discussion** -- references to more extensive rationale and/or examples placed outside the main lists of rules
399 Some rules are hard to check mechanically, but they all meet the minimal criteria that an expert programmer can spot many violations without too much trouble.
400 We hope that "mechanical" tools will improve with time to approximate what such an expert programmer notices.
401 Also, we assume that the rules will be refined over time to make them more precise and checkable.
403 A rule is aimed at being simple, rather than carefully phrased to mention every alternative and special case.
404 Such information is found in the **Alternative** paragraphs and the [Discussion](#S-discussion) sections.
405 If you don't understand a rule or disagree with it, please visit its **Discussion**.
406 If you feel that a discussion is missing or incomplete, enter an [Issue](https://github.com/isocpp/CppCoreGuidelines/issues)
407 explaining your concerns and possibly a corresponding PR.
409 Examples are written to illustrate rules.
411 * Examples are not intended to be production quality or to cover all tutorial dimensions.
412 For example, many examples are language-technical and use names like `f`, `base`, and `x`.
413 * We try to ensure that "good" examples follow the Core Guidelines.
414 * Comments are often illustrating rules where they would be unnecessary and/or distracting in "real code."
415 * We assume knowledge of the standard library. For example, we use plain `vector` rather than `std::vector`.
417 This is not a language manual.
418 It is meant to be helpful, rather than complete, fully accurate on technical details, or a guide to existing code.
419 Recommended information sources can be found in [the references](#S-references).
421 ## <a name="SS-sec"></a>In.sec: Major sections
423 * [In: Introduction](#S-introduction)
424 * [P: Philosophy](#S-philosophy)
425 * [I: Interfaces](#S-interfaces)
426 * [F: Functions](#S-functions)
427 * [C: Classes and class hierarchies](#S-class)
428 * [Enum: Enumerations](#S-enum)
429 * [R: Resource management](#S-resource)
430 * [ES: Expressions and statements](#S-expr)
431 * [Per: Performance](#S-performance)
432 * [CP: Concurrency and parallelism](#S-concurrency)
433 * [E: Error handling](#S-errors)
434 * [Con: Constants and immutability](#S-const)
435 * [T: Templates and generic programming](#S-templates)
436 * [CPL: C-style programming](#S-cpl)
437 * [SF: Source files](#S-source)
438 * [SL: The Standard Library](#sl-the-standard-library)
440 Supporting sections:
442 * [A: Architectural ideas](#S-A)
443 * [NR: Non-Rules and myths](#S-not)
444 * [RF: References](#S-references)
445 * [Pro: Profiles](#S-profile)
446 * [GSL: Guidelines support library](#gsl-guidelines-support-library)
447 * [NL: Naming and layout suggestions](#S-naming)
448 * [FAQ: Answers to frequently asked questions](#S-faq)
449 * [Appendix A: Libraries](#S-libraries)
450 * [Appendix B: Modernizing code](#S-modernizing)
451 * [Appendix C: Discussion](#S-discussion)
452 * [Appendix D: Supporting tools](#S-tools)
453 * [Glossary](#S-glossary)
454 * [To-do: Unclassified proto-rules](#S-unclassified)
456 These sections are not orthogonal.
458 Each section (e.g., "P" for "Philosophy") and each subsection (e.g., "C.hier" for "Class Hierarchies (OOP)") have an abbreviation for ease of searching and reference.
459 The main section abbreviations are also used in rule numbers (e.g., "C.11" for "Make concrete types regular").
461 # <a name="S-philosophy"></a>P: Philosophy
463 The rules in this section are very general.
465 Philosophy rules summary:
467 * [P.1: Express ideas directly in code](#Rp-direct)
468 * [P.2: Write in ISO Standard C++](#Rp-Cplusplus)
469 * [P.3: Express intent](#Rp-what)
470 * [P.4: Ideally, a program should be statically type safe](#Rp-typesafe)
471 * [P.5: Prefer compile-time checking to run-time checking](#Rp-compile-time)
472 * [P.6: What cannot be checked at compile time should be checkable at run time](#Rp-run-time)
473 * [P.7: Catch run-time errors early](#Rp-early)
474 * [P.8: Don't leak any resources](#Rp-leak)
475 * [P.9: Don't waste time or space](#Rp-waste)
476 * [P.10: Prefer immutable data to mutable data](#Rp-mutable)
477 * [P.11: Encapsulate messy constructs, rather than spreading through the code](#Rp-library)
478 * [P.12: Use supporting tools as appropriate](#Rp-tools)
479 * [P.13: Use support libraries as appropriate](#Rp-lib)
481 Philosophical rules are generally not mechanically checkable.
482 However, individual rules reflecting these philosophical themes are.
483 Without a philosophical basis, the more concrete/specific/checkable rules lack rationale.
485 ### <a name="Rp-direct"></a>P.1: Express ideas directly in code
487 ##### Reason
489 Compilers don't read comments (or design documents) and neither do many programmers (consistently).
490 What is expressed in code has defined semantics and can (in principle) be checked by compilers and other tools.
492 ##### Example
494     class Date {
495     public:
496         Month month() const;  // do
497         int month();          // don't
498         // ...
499     };
501 The first declaration of `month` is explicit about returning a `Month` and about not modifying the state of the `Date` object.
502 The second version leaves the reader guessing and opens more possibilities for uncaught bugs.
504 ##### Example, bad
506 This loop is a restricted form of `std::find`:
508     void f(vector<string>& v)
509     {
510         string val;
511         cin >> val;
512         // ...
513         int index = -1;                    // bad, plus should use gsl::index
514         for (int i = 0; i < v.size(); ++i) {
515             if (v[i] == val) {
516                 index = i;
517                 break;
518             }
519         }
520         // ...
521     }
523 ##### Example, good
525 A much clearer expression of intent would be:
527     void f(vector<string>& v)
528     {
529         string val;
530         cin >> val;
531         // ...
532         auto p = find(begin(v), end(v), val);  // better
533         // ...
534     }
536 A well-designed library expresses intent (what is to be done, rather than just how something is being done) far better than direct use of language features.
538 A C++ programmer should know the basics of the standard library, and use it where appropriate.
539 Any programmer should know the basics of the foundation libraries of the project being worked on, and use them appropriately.
540 Any programmer using these guidelines should know the [guidelines support library](#gsl-guidelines-support-library), and use it appropriately.
542 ##### Example
544     change_speed(double s);   // bad: what does s signify?
545     // ...
546     change_speed(2.3);
548 A better approach is to be explicit about the meaning of the double (new speed or delta on old speed?) and the unit used:
550     change_speed(Speed s);    // better: the meaning of s is specified
551     // ...
552     change_speed(2.3);        // error: no unit
553     change_speed(23_m / 10s);  // meters per second
555 We could have accepted a plain (unit-less) `double` as a delta, but that would have been error-prone.
556 If we wanted both absolute speed and deltas, we would have defined a `Delta` type.
558 ##### Enforcement
560 Very hard in general.
562 * use `const` consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference)
563 * flag uses of casts (casts neuter the type system)
564 * detect code that mimics the standard library (hard)
566 ### <a name="Rp-Cplusplus"></a>P.2: Write in ISO Standard C++
568 ##### Reason
570 This is a set of guidelines for writing ISO Standard C++.
572 ##### Note
574 There are environments where extensions are necessary, e.g., to access system resources.
575 In such cases, localize the use of necessary extensions and control their use with non-core Coding Guidelines.  If possible, build interfaces that encapsulate the extensions so they can be turned off or compiled away on systems that do not support those extensions.
577 Extensions often do not have rigorously defined semantics.  Even extensions that
578 are common and implemented by multiple compilers might have slightly different
579 behaviors and edge case behavior as a direct result of *not* having a rigorous
580 standard definition.  With sufficient use of any such extension, expected
581 portability will be impacted.
583 ##### Note
585 Using valid ISO C++ does not guarantee portability (let alone correctness).
586 Avoid dependence on undefined behavior (e.g., [undefined order of evaluation](#Res-order))
587 and be aware of constructs with implementation defined meaning (e.g., `sizeof(int)`).
589 ##### Note
591 There are environments where restrictions on use of standard C++ language or library features are necessary, e.g., to avoid dynamic memory allocation as required by aircraft control software standards.
592 In such cases, control their (dis)use with an extension of these Coding Guidelines customized to the specific environment.
594 ##### Enforcement
596 Use an up-to-date C++ compiler (currently C++20 or C++17) with a set of options that do not accept extensions.
598 ### <a name="Rp-what"></a>P.3: Express intent
600 ##### Reason
602 Unless the intent of some code is stated (e.g., in names or comments), it is impossible to tell whether the code does what it is supposed to do.
604 ##### Example
606     gsl::index i = 0;
607     while (i < v.size()) {
608         // ... do something with v[i] ...
609     }
611 The intent of "just" looping over the elements of `v` is not expressed here. The implementation detail of an index is exposed (so that it might be misused), and `i` outlives the scope of the loop, which might or might not be intended. The reader cannot know from just this section of code.
613 Better:
615     for (const auto& x : v) { /* do something with the value of x */ }
617 Now, there is no explicit mention of the iteration mechanism, and the loop operates on a reference to `const` elements so that accidental modification cannot happen. If modification is desired, say so:
619     for (auto& x : v) { /* modify x */ }
621 For more details about for-statements, see [ES.71](#Res-for-range).
622 Sometimes better still, use a named algorithm. This example uses the `for_each` from the Ranges TS because it directly expresses the intent:
624     for_each(v, [](int x) { /* do something with the value of x */ });
625     for_each(par, v, [](int x) { /* do something with the value of x */ });
627 The last variant makes it clear that we are not interested in the order in which the elements of `v` are handled.
629 A programmer should be familiar with
631 * [The guidelines support library](#gsl-guidelines-support-library)
632 * [The ISO C++ Standard Library](#sl-the-standard-library)
633 * Whatever foundation libraries are used for the current project(s)
635 ##### Note
637 Alternative formulation: Say what should be done, rather than just how it should be done.
639 ##### Note
641 Some language constructs express intent better than others.
643 ##### Example
645 If two `int`s are meant to be the coordinates of a 2D point, say so:
647     draw_line(int, int, int, int);  // obscure: (x1,y1,x2,y2)? (x,y,h,w)? ...?
648                                     // need to look up documentation to know
650     draw_line(Point, Point);        // clearer
652 ##### Enforcement
654 Look for common patterns for which there are better alternatives
656 * simple `for` loops vs. range-`for` loops
657 * `f(T*, int)` interfaces vs. `f(span<T>)` interfaces
658 * loop variables in too large a scope
659 * naked `new` and `delete`
660 * functions with many parameters of built-in types
662 There is a huge scope for cleverness and semi-automated program transformation.
664 ### <a name="Rp-typesafe"></a>P.4: Ideally, a program should be statically type safe
666 ##### Reason
668 Ideally, a program would be completely statically (compile-time) type safe.
669 Unfortunately, that is not possible. Problem areas:
671 * unions
672 * casts
673 * array decay
674 * range errors
675 * narrowing conversions
677 ##### Note
679 These areas are sources of serious problems (e.g., crashes and security violations).
680 We try to provide alternative techniques.
682 ##### Enforcement
684 We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs.
685 Always suggest an alternative.
686 For example:
688 * unions -- use `variant` (in C++17)
689 * casts -- minimize their use; templates can help
690 * array decay -- use `span` (from the GSL)
691 * range errors -- use `span`
692 * narrowing conversions -- minimize their use and use `narrow` or `narrow_cast` (from the GSL) where they are necessary
694 ### <a name="Rp-compile-time"></a>P.5: Prefer compile-time checking to run-time checking
696 ##### Reason
698 Code clarity and performance.
699 You don't need to write error handlers for errors caught at compile time.
701 ##### Example
703     // Int is an alias used for integers
704     int bits = 0;         // don't: avoidable code
705     for (Int i = 1; i; i <<= 1)
706         ++bits;
707     if (bits < 32)
708         cerr << "Int too small\n";
710 This example fails to achieve what it is trying to achieve (because overflow is undefined) and should be replaced with a simple `static_assert`:
712     // Int is an alias used for integers
713     static_assert(sizeof(Int) >= 4);    // do: compile-time check
715 Or better still just use the type system and replace `Int` with `int32_t`.
717 ##### Example
719     void read(int* p, int n);   // read max n integers into *p
721     int a[100];
722     read(a, 1000);    // bad, off the end
724 better
726     void read(span<int> r); // read into the range of integers r
728     int a[100];
729     read(a);        // better: let the compiler figure out the number of elements
731 **Alternative formulation**: Don't postpone to run time what can be done well at compile time.
733 ##### Enforcement
735 * Look for pointer arguments.
736 * Look for run-time checks for range violations.
738 ### <a name="Rp-run-time"></a>P.6: What cannot be checked at compile time should be checkable at run time
740 ##### Reason
742 Leaving hard-to-detect errors in a program is asking for crashes and bad results.
744 ##### Note
746 Ideally, we catch all errors (that are not errors in the programmer's logic) at either compile time or run time. It is impossible to catch all errors at compile time and often not affordable to catch all remaining errors at run time. However, we should endeavor to write programs that in principle can be checked, given sufficient resources (analysis programs, run-time checks, machine resources, time).
748 ##### Example, bad
750     // separately compiled, possibly dynamically loaded
751     extern void f(int* p);
753     void g(int n)
754     {
755         // bad: the number of elements is not passed to f()
756         f(new int[n]);
757     }
759 Here, a crucial bit of information (the number of elements) has been so thoroughly "obscured" that static analysis is probably rendered infeasible and dynamic checking can be very difficult when `f()` is part of an ABI so that we cannot "instrument" that pointer. We could embed helpful information into the free store, but that requires global changes to a system and maybe to the compiler. What we have here is a design that makes error detection very hard.
761 ##### Example, bad
763 We can of course pass the number of elements along with the pointer:
765     // separately compiled, possibly dynamically loaded
766     extern void f2(int* p, int n);
768     void g2(int n)
769     {
770         f2(new int[n], m);  // bad: a wrong number of elements can be passed to f()
771     }
773 Passing the number of elements as an argument is better (and far more common) than just passing the pointer and relying on some (unstated) convention for knowing or discovering the number of elements. However (as shown), a simple typo can introduce a serious error. The connection between the two arguments of `f2()` is conventional, rather than explicit.
775 Also, it is implicit that `f2()` is supposed to `delete` its argument (or did the caller make a second mistake?).
777 ##### Example, bad
779 The standard library resource management pointers fail to pass the size when they point to an object:
781     // separately compiled, possibly dynamically loaded
782     // NB: this assumes the calling code is ABI-compatible, using a
783     // compatible C++ compiler and the same stdlib implementation
784     extern void f3(unique_ptr<int[]>, int n);
786     void g3(int n)
787     {
788         f3(make_unique<int[]>(n), m);    // bad: pass ownership and size separately
789     }
791 ##### Example
793 We need to pass the pointer and the number of elements as an integral object:
795     extern void f4(vector<int>&);   // separately compiled, possibly dynamically loaded
796     extern void f4(span<int>);      // separately compiled, possibly dynamically loaded
797                                     // NB: this assumes the calling code is ABI-compatible, using a
798                                     // compatible C++ compiler and the same stdlib implementation
800     void g3(int n)
801     {
802         vector<int> v(n);
803         f4(v);                     // pass a reference, retain ownership
804         f4(span<int>{v});          // pass a view, retain ownership
805     }
807 This design carries the number of elements along as an integral part of an object, so that errors are unlikely and dynamic (run-time) checking is always feasible, if not always affordable.
809 ##### Example
811 How do we transfer both ownership and all information needed for validating use?
813     vector<int> f5(int n)    // OK: move
814     {
815         vector<int> v(n);
816         // ... initialize v ...
817         return v;
818     }
820     unique_ptr<int[]> f6(int n)    // bad: loses n
821     {
822         auto p = make_unique<int[]>(n);
823         // ... initialize *p ...
824         return p;
825     }
827     owner<int*> f7(int n)    // bad: loses n and we might forget to delete
828     {
829         owner<int*> p = new int[n];
830         // ... initialize *p ...
831         return p;
832     }
834 ##### Example
836 * ???
837 * show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
838   Or strings as "free-style" options
840 ##### Enforcement
842 * Flag (pointer, count)-style interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons)
843 * ???
845 ### <a name="Rp-early"></a>P.7: Catch run-time errors early
847 ##### Reason
849 Avoid "mysterious" crashes.
850 Avoid errors leading to (possibly unrecognized) wrong results.
852 ##### Example
854     void increment1(int* p, int n)    // bad: error-prone
855     {
856         for (int i = 0; i < n; ++i) ++p[i];
857     }
859     void use1(int m)
860     {
861         const int n = 10;
862         int a[n] = {};
863         // ...
864         increment1(a, m);   // maybe typo, maybe m <= n is supposed
865                             // but assume that m == 20
866         // ...
867     }
869 Here we made a small error in `use1` that will lead to corrupted data or a crash.
870 The (pointer, count)-style interface leaves `increment1()` with no realistic way of defending itself against out-of-range errors.
871 If we could check subscripts for out of range access, then the error would not be discovered until `p[10]` was accessed.
872 We could check earlier and improve the code:
874     void increment2(span<int> p)
875     {
876         for (int& x : p) ++x;
877     }
879     void use2(int m)
880     {
881         const int n = 10;
882         int a[n] = {};
883         // ...
884         increment2({a, m});    // maybe typo, maybe m <= n is supposed
885         // ...
886     }
888 Now, `m <= n` can be checked at the point of call (early) rather than later.
889 If all we had was a typo so that we meant to use `n` as the bound, the code could be further simplified (eliminating the possibility of an error):
891     void use3(int m)
892     {
893         const int n = 10;
894         int a[n] = {};
895         // ...
896         increment2(a);   // the number of elements of a need not be repeated
897         // ...
898     }
900 ##### Example, bad
902 Don't repeatedly check the same value. Don't pass structured data as strings:
904     Date read_date(istream& is);    // read date from istream
906     Date extract_date(const string& s);    // extract date from string
908     void user1(const string& date)    // manipulate date
909     {
910         auto d = extract_date(date);
911         // ...
912     }
914     void user2()
915     {
916         Date d = read_date(cin);
917         // ...
918         user1(d.to_string());
919         // ...
920     }
922 The date is validated twice (by the `Date` constructor) and passed as a character string (unstructured data).
924 ##### Example
926 Excess checking can be costly.
927 There are cases where checking early is inefficient because you might never need the value, or might only need part of the value that is more easily checked than the whole.  Similarly, don't add validity checks that change the asymptotic behavior of your interface (e.g., don't add a `O(n)` check to an interface with an average complexity of `O(1)`).
929     class Jet {    // Physics says: e * e < x * x + y * y + z * z
930         float x;
931         float y;
932         float z;
933         float e;
934     public:
935         Jet(float x, float y, float z, float e)
936             :x(x), y(y), z(z), e(e)
937         {
938             // Should I check here that the values are physically meaningful?
939         }
941         float m() const
942         {
943             // Should I handle the degenerate case here?
944             return sqrt(x * x + y * y + z * z - e * e);
945         }
947         ???
948     };
950 The physical law for a jet (`e * e < x * x + y * y + z * z`) is not an invariant because of the possibility for measurement errors.
954 ##### Enforcement
956 * Look at pointers and arrays: Do range-checking early and not repeatedly
957 * Look at conversions: Eliminate or mark narrowing conversions
958 * Look for unchecked values coming from input
959 * Look for structured data (objects of classes with invariants) being converted into strings
960 * ???
962 ### <a name="Rp-leak"></a>P.8: Don't leak any resources
964 ##### Reason
966 Even a slow growth in resources will, over time, exhaust the availability of those resources.
967 This is particularly important for long-running programs, but is an essential piece of responsible programming behavior.
969 ##### Example, bad
971     void f(char* name)
972     {
973         FILE* input = fopen(name, "r");
974         // ...
975         if (something) return;   // bad: if something == true, a file handle is leaked
976         // ...
977         fclose(input);
978     }
980 Prefer [RAII](#Rr-raii):
982     void f(char* name)
983     {
984         ifstream input {name};
985         // ...
986         if (something) return;   // OK: no leak
987         // ...
988     }
990 **See also**: [The resource management section](#S-resource)
992 ##### Note
994 A leak is colloquially "anything that isn't cleaned up."
995 The more important classification is "anything that can no longer be cleaned up."
996 For example, allocating an object on the heap and then losing the last pointer that points to that allocation.
997 This rule should not be taken as requiring that allocations within long-lived objects must be returned during program shutdown.
998 For example, relying on system guaranteed cleanup such as file closing and memory deallocation upon process shutdown can simplify code.
999 However, relying on abstractions that implicitly clean up can be as simple, and often safer.
1001 ##### Note
1003 Enforcing [the lifetime safety profile](#SS-lifetime) eliminates leaks.
1004 When combined with resource safety provided by [RAII](#Rr-raii), it eliminates the need for "garbage collection" (by generating no garbage).
1005 Combine this with enforcement of [the type and bounds profiles](#SS-force) and you get complete type- and resource-safety, guaranteed by tools.
1007 ##### Enforcement
1009 * Look at pointers: Classify them into non-owners (the default) and owners.
1010   Where feasible, replace owners with standard-library resource handles (as in the example above).
1011   Alternatively, mark an owner as such using `owner` from [the GSL](#gsl-guidelines-support-library).
1012 * Look for naked `new` and `delete`
1013 * Look for known resource allocating functions returning raw pointers (such as `fopen`, `malloc`, and `strdup`)
1015 ### <a name="Rp-waste"></a>P.9: Don't waste time or space
1017 ##### Reason
1019 This is C++.
1021 ##### Note
1023 Time and space that you spend well to achieve a goal (e.g., speed of development, resource safety, or simplification of testing) is not wasted.
1024 "Another benefit of striving for efficiency is that the process forces you to understand the problem in more depth." - Alex Stepanov
1026 ##### Example, bad
1028     struct X {
1029         char ch;
1030         int i;
1031         string s;
1032         char ch2;
1034         X& operator=(const X& a);
1035         X(const X&);
1036     };
1038     X waste(const char* p)
1039     {
1040         if (!p) throw Nullptr_error{};
1041         int n = strlen(p);
1042         auto buf = new char[n];
1043         if (!buf) throw Allocation_error{};
1044         for (int i = 0; i < n; ++i) buf[i] = p[i];
1045         // ... manipulate buffer ...
1046         X x;
1047         x.ch = 'a';
1048         x.s = string(n);    // give x.s space for *p
1049         for (gsl::index i = 0; i < x.s.size(); ++i) x.s[i] = buf[i];  // copy buf into x.s
1050         delete[] buf;
1051         return x;
1052     }
1054     void driver()
1055     {
1056         X x = waste("Typical argument");
1057         // ...
1058     }
1060 Yes, this is a caricature, but we have seen every individual mistake in production code, and worse.
1061 Note that the layout of `X` guarantees that at least 6 bytes (and most likely more) are wasted.
1062 The spurious definition of copy operations disables move semantics so that the return operation is slow
1063 (please note that the Return Value Optimization, RVO, is not guaranteed here).
1064 The use of `new` and `delete` for `buf` is redundant; if we really needed a local string, we should use a local `string`.
1065 There are several more performance bugs and gratuitous complication.
1067 ##### Example, bad
1069     void lower(zstring s)
1070     {
1071         for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
1072     }
1074 This is actually an example from production code.
1075 We can see that in our condition we have `i < strlen(s)`. This expression will be evaluated on every iteration of the loop, which means that `strlen` must walk through string every loop to discover its length. While the string contents are changing, it's assumed that `tolower` will not affect the length of the string, so it's better to cache the length outside the loop and not incur that cost each iteration.
1077 ##### Note
1079 An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert.
1080 However, waste spread liberally across a code base can easily be significant and experts are not always as available as we would like.
1081 The aim of this rule (and the more specific rules that support it) is to eliminate most waste related to the use of C++ before it happens.
1082 After that, we can look at waste related to algorithms and requirements, but that is beyond the scope of these guidelines.
1084 ##### Enforcement
1086 Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste.
1088 * Flag an unused return value from a user-defined non-defaulted postfix `operator++` or `operator--` function. Prefer using the prefix form instead. (Note: "User-defined non-defaulted" is intended to reduce noise. Review this enforcement if it's still too noisy in practice.)
1091 ### <a name="Rp-mutable"></a>P.10: Prefer immutable data to mutable data
1093 ##### Reason
1095 It is easier to reason about constants than about variables.
1096 Something immutable cannot change unexpectedly.
1097 Sometimes immutability enables better optimization.
1098 You can't have a data race on a constant.
1100 See [Con: Constants and immutability](#S-const)
1102 ### <a name="Rp-library"></a>P.11: Encapsulate messy constructs, rather than spreading through the code
1104 ##### Reason
1106 Messy code is more likely to hide bugs and harder to write.
1107 A good interface is easier and safer to use.
1108 Messy, low-level code breeds more such code.
1110 ##### Example
1112     int sz = 100;
1113     int* p = (int*) malloc(sizeof(int) * sz);
1114     int count = 0;
1115     // ...
1116     for (;;) {
1117         // ... read an int into x, exit loop if end of file is reached ...
1118         // ... check that x is valid ...
1119         if (count == sz)
1120             p = (int*) realloc(p, sizeof(int) * sz * 2);
1121         p[count++] = x;
1122         // ...
1123     }
1125 This is low-level, verbose, and error-prone.
1126 For example, we "forgot" to test for memory exhaustion.
1127 Instead, we could use `vector`:
1129     vector<int> v;
1130     v.reserve(100);
1131     // ...
1132     for (int x; cin >> x; ) {
1133         // ... check that x is valid ...
1134         v.push_back(x);
1135     }
1137 ##### Note
1139 The standards library and the GSL are examples of this philosophy.
1140 For example, instead of messing with the arrays, unions, cast, tricky lifetime issues, `gsl::owner`, etc.,
1141 that are needed to implement key abstractions, such as `vector`, `span`, `lock_guard`, and `future`, we use the libraries
1142 designed and implemented by people with more time and expertise than we usually have.
1143 Similarly, we can and should design and implement more specialized libraries, rather than leaving the users (often ourselves)
1144 with the challenge of repeatedly getting low-level code well.
1145 This is a variant of the [subset of superset principle](#R0) that underlies these guidelines.
1147 ##### Enforcement
1149 * Look for "messy code" such as complex pointer manipulation and casting outside the implementation of abstractions.
1152 ### <a name="Rp-tools"></a>P.12: Use supporting tools as appropriate
1154 ##### Reason
1156 There are many things that are done better "by machine".
1157 Computers don't tire or get bored by repetitive tasks.
1158 We typically have better things to do than repeatedly do routine tasks.
1160 ##### Example
1162 Run a static analyzer to verify that your code follows the guidelines you want it to follow.
1164 ##### Note
1168 * [Static analysis tools](???)
1169 * [Concurrency tools](#Rconc-tools)
1170 * [Testing tools](???)
1172 There are many other kinds of tools, such as source code repositories, build tools, etc.,
1173 but those are beyond the scope of these guidelines.
1175 ##### Note
1177 Be careful not to become dependent on over-elaborate or over-specialized tool chains.
1178 Those can make your otherwise portable code non-portable.
1181 ### <a name="Rp-lib"></a>P.13: Use support libraries as appropriate
1183 ##### Reason
1185 Using a well-designed, well-documented, and well-supported library saves time and effort;
1186 its quality and documentation are likely to be greater than what you could do
1187 if the majority of your time must be spent on an implementation.
1188 The cost (time, effort, money, etc.) of a library can be shared over many users.
1189 A widely used library is more likely to be kept up-to-date and ported to new systems than an individual application.
1190 Knowledge of a widely-used library can save time on other/future projects.
1191 So, if a suitable library exists for your application domain, use it.
1193 ##### Example
1195     std::sort(begin(v), end(v), std::greater<>());
1197 Unless you are an expert in sorting algorithms and have plenty of time,
1198 this is more likely to be correct and to run faster than anything you write for a specific application.
1199 You need a reason not to use the standard library (or whatever foundational libraries your application uses) rather than a reason to use it.
1201 ##### Note
1203 By default use
1205 * The [ISO C++ Standard Library](#sl-the-standard-library)
1206 * The [Guidelines Support Library](#gsl-guidelines-support-library)
1208 ##### Note
1210 If no well-designed, well-documented, and well-supported library exists for an important domain,
1211 maybe you should design and implement it, and then use it.
1214 # <a name="S-interfaces"></a>I: Interfaces
1216 An interface is a contract between two parts of a program. Precisely stating what is expected of a supplier of a service and a user of that service is essential.
1217 Having good (easy-to-understand, encouraging efficient use, not error-prone, supporting testing, etc.) interfaces is probably the most important single aspect of code organization.
1219 Interface rule summary:
1221 * [I.1: Make interfaces explicit](#Ri-explicit)
1222 * [I.2: Avoid non-`const` global variables](#Ri-global)
1223 * [I.3: Avoid singletons](#Ri-singleton)
1224 * [I.4: Make interfaces precisely and strongly typed](#Ri-typed)
1225 * [I.5: State preconditions (if any)](#Ri-pre)
1226 * [I.6: Prefer `Expects()` for expressing preconditions](#Ri-expects)
1227 * [I.7: State postconditions](#Ri-post)
1228 * [I.8: Prefer `Ensures()` for expressing postconditions](#Ri-ensures)
1229 * [I.9: If an interface is a template, document its parameters using concepts](#Ri-concepts)
1230 * [I.10: Use exceptions to signal a failure to perform a required task](#Ri-except)
1231 * [I.11: Never transfer ownership by a raw pointer (`T*`) or reference (`T&`)](#Ri-raw)
1232 * [I.12: Declare a pointer that must not be null as `not_null`](#Ri-nullptr)
1233 * [I.13: Do not pass an array as a single pointer](#Ri-array)
1234 * [I.22: Avoid complex initialization of global objects](#Ri-global-init)
1235 * [I.23: Keep the number of function arguments low](#Ri-nargs)
1236 * [I.24: Avoid adjacent parameters that can be invoked by the same arguments in either order with different meaning](#Ri-unrelated)
1237 * [I.25: Prefer empty abstract classes as interfaces to class hierarchies](#Ri-abstract)
1238 * [I.26: If you want a cross-compiler ABI, use a C-style subset](#Ri-abi)
1239 * [I.27: For stable library ABI, consider the Pimpl idiom](#Ri-pimpl)
1240 * [I.30: Encapsulate rule violations](#Ri-encapsulate)
1242 **See also**:
1244 * [F: Functions](#S-functions)
1245 * [C.concrete: Concrete types](#SS-concrete)
1246 * [C.hier: Class hierarchies](#SS-hier)
1247 * [C.over: Overloading and overloaded operators](#SS-overload)
1248 * [C.con: Containers and other resource handles](#SS-containers)
1249 * [E: Error handling](#S-errors)
1250 * [T: Templates and generic programming](#S-templates)
1252 ### <a name="Ri-explicit"></a>I.1: Make interfaces explicit
1254 ##### Reason
1256 Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.
1258 ##### Example, bad
1260 Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:
1262     int round(double d)
1263     {
1264         return (round_up) ? ceil(d) : d;    // don't: "invisible" dependency
1265     }
1267 It will not be obvious to a caller that the meaning of two calls of `round(7.2)` might give different results.
1269 ##### Exception
1271 Sometimes we control the details of a set of operations by an environment variable, e.g., normal vs. verbose output or debug vs. optimized.
1272 The use of a non-local control is potentially confusing, but controls only implementation details of otherwise fixed semantics.
1274 ##### Example, bad
1276 Reporting through non-local variables (e.g., `errno`) is easily ignored. For example:
1278     // don't: no test of fprintf's return value
1279     fprintf(connection, "logging: %d %d %d\n", x, y, s);
1281 What if the connection goes down so that no logging output is produced? See I.???.
1283 **Alternative**: Throw an exception. An exception cannot be ignored.
1285 **Alternative formulation**: Avoid passing information across an interface through non-local or implicit state.
1286 Note that non-`const` member functions pass information to other member functions through their object's state.
1288 **Alternative formulation**: An interface should be a function or a set of functions.
1289 Functions can be function templates and sets of functions can be classes or class templates.
1291 ##### Enforcement
1293 * (Simple) A function should not make control-flow decisions based on the values of variables declared at namespace scope.
1294 * (Simple) A function should not write to variables declared at namespace scope.
1296 ### <a name="Ri-global"></a>I.2: Avoid non-`const` global variables
1298 ##### Reason
1300 Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes.
1302 ##### Example
1304     struct Data {
1305         // ... lots of stuff ...
1306     } data;            // non-const data
1308     void compute()     // don't
1309     {
1310         // ... use data ...
1311     }
1313     void output()     // don't
1314     {
1315         // ... use data ...
1316     }
1318 Who else might modify `data`?
1320 **Warning**: The initialization of global objects is not totally ordered.
1321 If you use a global object initialize it with a constant.
1322 Note that it is possible to get undefined initialization order even for `const` objects.
1324 ##### Exception
1326 A global object is often better than a singleton.
1328 ##### Note
1330 Global constants are useful.
1332 ##### Note
1334 The rule against global variables applies to namespace scope variables as well.
1336 **Alternative**: If you use global (more generally namespace scope) data to avoid copying, consider passing the data as an object by reference to `const`.
1337 Another solution is to define the data as the state of some object and the operations as member functions.
1339 **Warning**: Beware of data races: If one thread can access non-local data (or data passed by reference) while another thread executes the callee, we can have a data race.
1340 Every pointer or reference to mutable data is a potential data race.
1342 Using global pointers or references to access and change non-const, and otherwise non-global,
1343 data isn't a better alternative to non-const global variables since that doesn't solve the issues of hidden dependencies or potential race conditions.
1345 ##### Note
1347 You cannot have a race condition on immutable data.
1349 **References**: See the [rules for calling functions](#SS-call).
1351 ##### Note
1353 The rule is "avoid", not "don't use." Of course there will be (rare) exceptions, such as `cin`, `cout`, and `cerr`.
1355 ##### Enforcement
1357 (Simple) Report all non-`const` variables declared at namespace scope and global pointers/references to non-const data.
1360 ### <a name="Ri-singleton"></a>I.3: Avoid singletons
1362 ##### Reason
1364 Singletons are basically complicated global objects in disguise.
1366 ##### Example
1368     class Singleton {
1369         // ... lots of stuff to ensure that only one Singleton object is created,
1370         // that it is initialized properly, etc.
1371     };
1373 There are many variants of the singleton idea.
1374 That's part of the problem.
1376 ##### Note
1378 If you don't want a global object to change, declare it `const` or `constexpr`.
1380 ##### Exception
1382 You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any:
1384     X& myX()
1385     {
1386         static X my_x {3};
1387         return my_x;
1388     }
1390 This is one of the most effective solutions to problems related to initialization order.
1391 In a multi-threaded environment, the initialization of the static object does not introduce a race condition
1392 (unless you carelessly access a shared object from within its constructor).
1394 Note that the initialization of a local `static` does not imply a race condition.
1395 However, if the destruction of `X` involves an operation that needs to be synchronized we must use a less simple solution.
1396 For example:
1398     X& myX()
1399     {
1400         static auto p = new X {3};
1401         return *p;  // potential leak
1402     }
1404 Now someone must `delete` that object in some suitably thread-safe way.
1405 That's error-prone, so we don't use that technique unless
1407 * `myX` is in multi-threaded code,
1408 * that `X` object needs to be destroyed (e.g., because it releases a resource), and
1409 * `X`'s destructor's code needs to be synchronized.
1411 If you, as many do, define a singleton as a class for which only one object is created, functions like `myX` are not singletons, and this useful technique is not an exception to the no-singleton rule.
1413 ##### Enforcement
1415 Very hard in general.
1417 * Look for classes with names that include `singleton`.
1418 * Look for classes for which only a single object is created (by counting objects or by examining constructors).
1419 * If a class X has a public static function that contains a function-local static of the class' type X and returns a pointer or reference to it, ban that.
1421 ### <a name="Ri-typed"></a>I.4: Make interfaces precisely and strongly typed
1423 ##### Reason
1425 Types are the simplest and best documentation, improve legibility due to their well-defined meaning, and are checked at compile time.
1426 Also, precisely typed code is often optimized better.
1428 ##### Example, don't
1430 Consider:
1432     void pass(void* data);    // weak and under qualified type void* is suspicious
1434 Callers are unsure what types are allowed and if the data may
1435 be mutated as `const` is not specified. Note all pointer types
1436 implicitly convert to `void*`, so it is easy for callers to provide this value.
1438 The callee must `static_cast` data to an unverified type to use it.
1439 That is error-prone and verbose.
1441 Only use `const void*` for passing in data in designs that are indescribable in C++. Consider using a `variant` or a pointer to base instead.
1443 **Alternative**: Often, a template parameter can eliminate the `void*` turning it into a `T*` or `T&`.
1444 For generic code these `T`s can be general or concept constrained template parameters.
1446 ##### Example, bad
1448 Consider:
1450     draw_rect(100, 200, 100, 500); // what do the numbers specify?
1452     draw_rect(p.x, p.y, 10, 20); // what units are 10 and 20 in?
1454 It is clear that the caller is describing a rectangle, but it is unclear what parts they relate to. Also, an `int` can carry arbitrary forms of information, including values of many units, so we must guess about the meaning of the four `int`s. Most likely, the first two are an `x`,`y` coordinate pair, but what are the last two?
1456 Comments and parameter names can help, but we could be explicit:
1458     void draw_rectangle(Point top_left, Point bottom_right);
1459     void draw_rectangle(Point top_left, Size height_width);
1461     draw_rectangle(p, Point{10, 20});  // two corners
1462     draw_rectangle(p, Size{10, 20});   // one corner and a (height, width) pair
1464 Obviously, we cannot catch all errors through the static type system
1465 (e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)).
1467 ##### Example, bad
1469 Consider:
1471     set_settings(true, false, 42); // what do the numbers specify?
1473 The parameter types and their values do not communicate what settings are being specified or what those values mean.
1475 This design is more explicit, safe and legible:
1477     alarm_settings s{};
1478     s.enabled = true;
1479     s.displayMode = alarm_settings::mode::spinning_light;
1480     s.frequency = alarm_settings::every_10_seconds;
1481     set_settings(s);
1483 For the case of a set of boolean values consider using a flags `enum`; a pattern that expresses a set of boolean values.
1485     enable_lamp_options(lamp_option::on | lamp_option::animate_state_transitions);
1487 ##### Example, bad
1489 In the following example, it is not clear from the interface what `time_to_blink` means: Seconds? Milliseconds?
1491     void blink_led(int time_to_blink) // bad -- the unit is ambiguous
1492     {
1493         // ...
1494         // do something with time_to_blink
1495         // ...
1496     }
1498     void use()
1499     {
1500         blink_led(2);
1501     }
1503 ##### Example, good
1505 `std::chrono::duration` types helps making the unit of time duration explicit.
1507     void blink_led(milliseconds time_to_blink) // good -- the unit is explicit
1508     {
1509         // ...
1510         // do something with time_to_blink
1511         // ...
1512     }
1514     void use()
1515     {
1516         blink_led(1500ms);
1517     }
1519 The function can also be written in such a way that it will accept any time duration unit.
1521     template<class rep, class period>
1522     void blink_led(duration<rep, period> time_to_blink) // good -- accepts any unit
1523     {
1524         // assuming that millisecond is the smallest relevant unit
1525         auto milliseconds_to_blink = duration_cast<milliseconds>(time_to_blink);
1526         // ...
1527         // do something with milliseconds_to_blink
1528         // ...
1529     }
1531     void use()
1532     {
1533         blink_led(2s);
1534         blink_led(1500ms);
1535     }
1537 ##### Enforcement
1539 * (Simple) Report the use of `void*` as a parameter or return type.
1540 * (Simple) Report the use of more than one `bool` parameter.
1541 * (Hard to do well) Look for functions that use too many primitive type arguments.
1543 ### <a name="Ri-pre"></a>I.5: State preconditions (if any)
1545 ##### Reason
1547 Arguments have meaning that might constrain their proper use in the callee.
1549 ##### Example
1551 Consider:
1553     double sqrt(double x);
1555 Here `x` must be non-negative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
1557     double sqrt(double x); // x must be non-negative
1559 Some preconditions can be expressed as assertions. For example:
1561     double sqrt(double x) { Expects(x >= 0); /* ... */ }
1563 Ideally, that `Expects(x >= 0)` should be part of the interface of `sqrt()` but that's not easily done. For now, we place it in the definition (function body).
1565 **References**: `Expects()` is described in [GSL](#gsl-guidelines-support-library).
1567 ##### Note
1569 Prefer a formal specification of requirements, such as `Expects(p);`.
1570 If that is infeasible, use English text in comments, such as `// the sequence [p:q) is ordered using <`.
1572 ##### Note
1574 Most member functions have as a precondition that some class invariant holds.
1575 That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class.
1576 We don't need to mention it for each member function.
1578 ##### Enforcement
1580 (Not enforceable)
1582 **See also**: The rules for passing pointers. ???
1584 ### <a name="Ri-expects"></a>I.6: Prefer `Expects()` for expressing preconditions
1586 ##### Reason
1588 To make it clear that the condition is a precondition and to enable tool use.
1590 ##### Example
1592     int area(int height, int width)
1593     {
1594         Expects(height > 0 && width > 0);            // good
1595         if (height <= 0 || width <= 0) my_error();   // obscure
1596         // ...
1597     }
1599 ##### Note
1601 Preconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
1602 This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and might have the wrong semantics (do you always want to abort in debug mode and check nothing in productions runs?).
1604 ##### Note
1606 Preconditions should be part of the interface rather than part of the implementation,
1607 but we don't yet have the language facilities to do that.
1608 Once language support becomes available (e.g., see the [contract proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf)) we will adopt the standard version of preconditions, postconditions, and assertions.
1610 ##### Note
1612 `Expects()` can also be used to check a condition in the middle of an algorithm.
1614 ##### Note
1616 No, using `unsigned` is not a good way to sidestep the problem of [ensuring that a value is non-negative](#Res-nonnegative).
1618 ##### Enforcement
1620 (Not enforceable) Finding the variety of ways preconditions can be asserted is not feasible. Warning about those that can be easily identified (`assert()`) has questionable value in the absence of a language facility.
1622 ### <a name="Ri-post"></a>I.7: State postconditions
1624 ##### Reason
1626 To detect misunderstandings about the result and possibly catch erroneous implementations.
1628 ##### Example, bad
1630 Consider:
1632     int area(int height, int width) { return height * width; }  // bad
1634 Here, we (incautiously) left out the precondition specification, so it is not explicit that height and width must be positive.
1635 We also left out the postcondition specification, so it is not obvious that the algorithm (`height * width`) is wrong for areas larger than the largest integer.
1636 Overflow can happen.
1637 Consider using:
1639     int area(int height, int width)
1640     {
1641         auto res = height * width;
1642         Ensures(res > 0);
1643         return res;
1644     }
1646 ##### Example, bad
1648 Consider a famous security bug:
1650     void f()    // problematic
1651     {
1652         char buffer[MAX];
1653         // ...
1654         memset(buffer, 0, sizeof(buffer));
1655     }
1657 There was no postcondition stating that the buffer should be cleared and the optimizer eliminated the apparently redundant `memset()` call:
1659     void f()    // better
1660     {
1661         char buffer[MAX];
1662         // ...
1663         memset(buffer, 0, sizeof(buffer));
1664         Ensures(buffer[0] == 0);
1665     }
1667 ##### Note
1669 Postconditions are often informally stated in a comment that states the purpose of a function; `Ensures()` can be used to make this more systematic, visible, and checkable.
1671 ##### Note
1673 Postconditions are especially important when they relate to something that is not directly reflected in a returned result, such as a state of a data structure used.
1675 ##### Example
1677 Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions:
1679     mutex m;
1681     void manipulate(Record& r)    // don't
1682     {
1683         m.lock();
1684         // ... no m.unlock() ...
1685     }
1687 Here, we "forgot" to state that the `mutex` should be released, so we don't know if the failure to ensure release of the `mutex` was a bug or a feature.
1688 Stating the postcondition would have made it clear:
1690     void manipulate(Record& r)    // postcondition: m is unlocked upon exit
1691     {
1692         m.lock();
1693         // ... no m.unlock() ...
1694     }
1696 The bug is now obvious (but only to a human reading comments).
1698 Better still, use [RAII](#Rr-raii) to ensure that the postcondition ("the lock must be released") is enforced in code:
1700     void manipulate(Record& r)    // best
1701     {
1702         lock_guard<mutex> _ {m};
1703         // ...
1704     }
1706 ##### Note
1708 Ideally, postconditions are stated in the interface/declaration so that users can easily see them.
1709 Only postconditions related to the users can be stated in the interface.
1710 Postconditions related only to internal state belongs in the definition/implementation.
1712 ##### Enforcement
1714 (Not enforceable) This is a philosophical guideline that is infeasible to check
1715 directly in the general case. Domain specific checkers (like lock-holding
1716 checkers) exist for many toolchains.
1718 ### <a name="Ri-ensures"></a>I.8: Prefer `Ensures()` for expressing postconditions
1720 ##### Reason
1722 To make it clear that the condition is a postcondition and to enable tool use.
1724 ##### Example
1726     void f()
1727     {
1728         char buffer[MAX];
1729         // ...
1730         memset(buffer, 0, MAX);
1731         Ensures(buffer[0] == 0);
1732     }
1734 ##### Note
1736 Postconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
1737 This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and might have the wrong semantics.
1739 **Alternative**: Postconditions of the form "this resource must be released" are best expressed by [RAII](#Rr-raii).
1741 ##### Note
1743 Ideally, that `Ensures` should be part of the interface, but that's not easily done.
1744 For now, we place it in the definition (function body).
1745 Once language support becomes available (e.g., see the [contract proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf)) we will adopt the standard version of preconditions, postconditions, and assertions.
1747 ##### Enforcement
1749 (Not enforceable) Finding the variety of ways postconditions can be asserted is not feasible. Warning about those that can be easily identified (`assert()`) has questionable value in the absence of a language facility.
1751 ### <a name="Ri-concepts"></a>I.9: If an interface is a template, document its parameters using concepts
1753 ##### Reason
1755 Make the interface precisely specified and compile-time checkable in the (not so distant) future.
1757 ##### Example
1759 Use the C++20 style of requirements specification. For example:
1761     template<typename Iter, typename Val>
1762       requires input_iterator<Iter> && equality_comparable_with<iter_value_t<Iter>, Val>
1763     Iter find(Iter first, Iter last, Val v)
1764     {
1765         // ...
1766     }
1768 **See also**: [Generic programming](#SS-GP) and [concepts](#SS-concepts).
1770 ##### Enforcement
1772 Warn if any non-variadic template parameter is not constrained by a concept (in its declaration or mentioned in a `requires` clause).
1774 ### <a name="Ri-except"></a>I.10: Use exceptions to signal a failure to perform a required task
1776 ##### Reason
1778 It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state.
1779 This is a major source of errors.
1781 ##### Example
1783     int printf(const char* ...);    // bad: return negative number if output fails
1785     template<class F, class ...Args>
1786     // good: throw system_error if unable to start the new thread
1787     explicit thread(F&& f, Args&&... args);
1789 ##### Note
1791 What is an error?
1793 An error means that the function cannot achieve its advertised purpose (including establishing postconditions).
1794 Calling code that ignores an error could lead to wrong results or undefined systems state.
1795 For example, not being able to connect to a remote server is not by itself an error:
1796 the server can refuse a connection for all kinds of reasons, so the natural thing is to return a result that the caller should always check.
1797 However, if failing to make a connection is considered an error, then a failure should throw an exception.
1799 ##### Exception
1801 Many traditional interface functions (e.g., UNIX signal handlers) use error codes (e.g., `errno`) to report what are really status codes, rather than errors. You don't have a good alternative to using such, so calling these does not violate the rule.
1803 ##### Alternative
1805 If you can't use exceptions (e.g., because your code is full of old-style raw-pointer use or because there are hard-real-time constraints), consider using a style that returns a pair of values:
1807     int val;
1808     int error_code;
1809     tie(val, error_code) = do_something();
1810     if (error_code) {
1811         // ... handle the error or exit ...
1812     }
1813     // ... use val ...
1815 This style unfortunately leads to uninitialized variables.
1816 Since C++17 the "structured bindings" feature can be used to initialize variables directly from the return value:
1818     auto [val, error_code] = do_something();
1819     if (error_code) {
1820         // ... handle the error or exit ...
1821     }
1822     // ... use val ...
1824 ##### Note
1826 We don't consider "performance" a valid reason not to use exceptions.
1828 * Often, explicit error checking and handling consume as much time and space as exception handling.
1829 * Often, cleaner code yields better performance with exceptions (simplifying the tracing of paths through the program and their optimization).
1830 * A good rule for performance critical code is to move checking outside the [critical](#Rper-critical) part of the code.
1831 * In the longer term, more regular code gets better optimized.
1832 * Always carefully [measure](#Rper-measure) before making performance claims.
1834 **See also**: [I.5](#Ri-pre) and [I.7](#Ri-post) for reporting precondition and postcondition violations.
1836 ##### Enforcement
1838 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
1839 * Look for `errno`.
1841 ### <a name="Ri-raw"></a>I.11: Never transfer ownership by a raw pointer (`T*`) or reference (`T&`)
1843 ##### Reason
1845 If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.
1847 ##### Example
1849 Consider:
1851     X* compute(args)    // don't
1852     {
1853         X* res = new X{};
1854         // ...
1855         return res;
1856     }
1858 Who deletes the returned `X`? The problem would be harder to spot if `compute` returned a reference.
1859 Consider returning the result by value (use move semantics if the result is large):
1861     vector<double> compute(args)  // good
1862     {
1863         vector<double> res(10000);
1864         // ...
1865         return res;
1866     }
1868 **Alternative**: [Pass ownership](#Rr-smartptrparam) using a "smart pointer", such as `unique_ptr` (for exclusive ownership) and `shared_ptr` (for shared ownership).
1869 However, that is less elegant and often less efficient than returning the object itself,
1870 so use smart pointers only if reference semantics are needed.
1872 **Alternative**: Sometimes older code can't be modified because of ABI compatibility requirements or lack of resources.
1873 In that case, mark owning pointers using `owner` from the [guidelines support library](#gsl-guidelines-support-library):
1875     owner<X*> compute(args)    // It is now clear that ownership is transferred
1876     {
1877         owner<X*> res = new X{};
1878         // ...
1879         return res;
1880     }
1882 This tells analysis tools that `res` is an owner.
1883 That is, its value must be `delete`d or transferred to another owner, as is done here by the `return`.
1885 `owner` is used similarly in the implementation of resource handles.
1887 ##### Note
1889 Every object passed as a raw pointer (or iterator) is assumed to be owned by the
1890 caller, so that its lifetime is handled by the caller. Viewed another way:
1891 ownership transferring APIs are relatively rare compared to pointer-passing APIs,
1892 so the default is "no ownership transfer."
1894 **See also**: [Argument passing](#Rf-conventional), [use of smart pointer arguments](#Rr-smartptrparam), and [value return](#Rf-value-return).
1896 ##### Enforcement
1898 * (Simple) Warn on `delete` of a raw pointer that is not an `owner<T>`. Suggest use of standard-library resource handle or use of `owner<T>`.
1899 * (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path.
1900 * (Simple) Warn if the return value of `new` or a function call with an `owner` return value is assigned to a raw pointer or non-`owner` reference.
1902 ### <a name="Ri-nullptr"></a>I.12: Declare a pointer that must not be null as `not_null`
1904 ##### Reason
1906 To help avoid dereferencing `nullptr` errors.
1907 To improve performance by avoiding redundant checks for `nullptr`.
1909 ##### Example
1911     int length(const char* p);            // it is not clear whether length(nullptr) is valid
1913     length(nullptr);                      // OK?
1915     int length(not_null<const char*> p);  // better: we can assume that p cannot be nullptr
1917     int length(const char* p);            // we must assume that p can be nullptr
1919 By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.
1921 ##### Note
1923 `not_null` is defined in the [guidelines support library](#gsl-guidelines-support-library).
1925 ##### Note
1927 The assumption that the pointer to `char` pointed to a C-style string (a zero-terminated string of characters) was still implicit, and a potential source of confusion and errors. Use `czstring` in preference to `const char*`.
1929     // we can assume that p cannot be nullptr
1930     // we can assume that p points to a zero-terminated array of characters
1931     int length(not_null<czstring> p);
1933 Note: `length()` is, of course, `std::strlen()` in disguise.
1935 ##### Enforcement
1937 * (Simple) ((Foundation)) If a function checks a pointer parameter against `nullptr` before access, on all control-flow paths, then warn it should be declared `not_null`.
1938 * (Complex) If a function with pointer return value ensures it is not `nullptr` on all return paths, then warn the return type should be declared `not_null`.
1940 ### <a name="Ri-array"></a>I.13: Do not pass an array as a single pointer
1942 ##### Reason
1944  (pointer, size)-style interfaces are error-prone. Also, a plain pointer (to array) must rely on some convention to allow the callee to determine the size.
1946 ##### Example
1948 Consider:
1950     void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
1952 What if there are fewer than `n` elements in the array pointed to by `q`? Then, we overwrite some probably unrelated memory.
1953 What if there are fewer than `n` elements in the array pointed to by `p`? Then, we read some probably unrelated memory.
1954 Either is undefined behavior and a potentially very nasty bug.
1956 ##### Alternative
1958 Consider using explicit spans:
1960     void copy(span<const T> r, span<T> r2); // copy r to r2
1962 ##### Example, bad
1964 Consider:
1966     void draw(Shape* p, int n);  // poor interface; poor code
1967     Circle arr[10];
1968     // ...
1969     draw(arr, 10);
1971 Passing `10` as the `n` argument might be a mistake: the most common convention is to assume `[0:n)` but that is nowhere stated. Worse is that the call of `draw()` compiled at all: there was an implicit conversion from array to pointer (array decay) and then another implicit conversion from `Circle` to `Shape`. There is no way that `draw()` can safely iterate through that array: it has no way of knowing the size of the elements.
1973 **Alternative**: Use a support class that ensures that the number of elements is correct and prevents dangerous implicit conversions. For example:
1975     void draw2(span<Circle>);
1976     Circle arr[10];
1977     // ...
1978     draw2(span<Circle>(arr));  // deduce the number of elements
1979     draw2(arr);    // deduce the element type and array size
1981     void draw3(span<Shape>);
1982     draw3(arr);    // error: cannot convert Circle[10] to span<Shape>
1984 This `draw2()` passes the same amount of information to `draw()`, but makes the fact that it is supposed to be a range of `Circle`s explicit. See ???.
1986 ##### Exception
1988 Use `zstring` and `czstring` to represent C-style, zero-terminated strings.
1989 But when doing so, use `std::string_view` or `span<char>` from the [GSL](#gsl-guidelines-support-library) to prevent range errors.
1991 ##### Enforcement
1993 * (Simple) ((Bounds)) Warn for any expression that would rely on implicit conversion of an array type to a pointer type. Allow exception for zstring/czstring pointer types.
1994 * (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type. Allow exception for zstring/czstring pointer types.
1996 ### <a name="Ri-global-init"></a>I.22: Avoid complex initialization of global objects
1998 ##### Reason
2000 Complex initialization can lead to undefined order of execution.
2002 ##### Example
2004     // file1.c
2006     extern const X x;
2008     const Y y = f(x);   // read x; write y
2010     // file2.c
2012     extern const Y y;
2014     const X x = g(y);   // read y; write x
2016 Since `x` and `y` are in different translation units the order of calls to `f()` and `g()` is undefined;
2017 one will access an uninitialized `const`.
2018 This shows that the order-of-initialization problem for global (namespace scope) objects is not limited to global *variables*.
2020 ##### Note
2022 Order of initialization problems become particularly difficult to handle in concurrent code.
2023 It is usually best to avoid global (namespace scope) objects altogether.
2025 ##### Enforcement
2027 * Flag initializers of globals that call non-`constexpr` functions
2028 * Flag initializers of globals that access `extern` objects
2030 ### <a name="Ri-nargs"></a>I.23: Keep the number of function arguments low
2032 ##### Reason
2034 Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.
2036 ##### Discussion
2038 The two most common reasons why functions have too many parameters are:
2040 1. *Missing an abstraction.*
2041    There is an abstraction missing, so that a compound value is being
2042    passed as individual elements instead of as a single object that enforces an invariant.
2043    This not only expands the parameter list, but it leads to errors because the component values
2044    are no longer protected by an enforced invariant.
2046 2. *Violating "one function, one responsibility."*
2047    The function is trying to do more than one job and should probably be refactored.
2049 ##### Example
2051 The standard-library `merge()` is at the limit of what we can comfortably handle:
2053     template<class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
2054     OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
2055                          InputIterator2 first2, InputIterator2 last2,
2056                          OutputIterator result, Compare comp);
2058 Note that this is because of problem 1 above -- missing abstraction. Instead of passing a range (abstraction), STL passed iterator pairs (unencapsulated component values).
2060 Here, we have four template arguments and six function arguments.
2061 To simplify the most frequent and simplest uses, the comparison argument can be defaulted to `<`:
2063     template<class InputIterator1, class InputIterator2, class OutputIterator>
2064     OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
2065                          InputIterator2 first2, InputIterator2 last2,
2066                          OutputIterator result);
2068 This doesn't reduce the total complexity, but it reduces the surface complexity presented to many users.
2069 To really reduce the number of arguments, we need to bundle the arguments into higher-level abstractions:
2071     template<class InputRange1, class InputRange2, class OutputIterator>
2072     OutputIterator merge(InputRange1 r1, InputRange2 r2, OutputIterator result);
2074 Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking.
2076 Alternatively, we could use a standard library concept to define the notion of three types that must be usable for merging:
2078     template<class In1, class In2, class Out>
2079       requires mergeable<In1, In2, Out>
2080     Out merge(In1 r1, In2 r2, Out result);
2082 ##### Example
2084 The safety Profiles recommend replacing
2086     void f(int* some_ints, int some_ints_length);  // BAD: C style, unsafe
2088 with
2090     void f(gsl::span<int> some_ints);              // GOOD: safe, bounds-checked
2092 Here, using an abstraction has safety and robustness benefits, and naturally also reduces the number of parameters.
2094 ##### Note
2096 How many parameters are too many? Try to use fewer than four (4) parameters.
2097 There are functions that are best expressed with four individual parameters, but not many.
2099 **Alternative**: Use better abstraction: Group arguments into meaningful objects and pass the objects (by value or by reference).
2101 **Alternative**: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments.
2103 ##### Enforcement
2105 * Warn when a function declares two iterators (including pointers) of the same type instead of a range or a view.
2106 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
2108 ### <a name="Ri-unrelated"></a>I.24: Avoid adjacent parameters that can be invoked by the same arguments in either order with different meaning
2110 ##### Reason
2112 Adjacent arguments of the same type are easily swapped by mistake.
2114 ##### Example, bad
2116 Consider:
2118     void copy_n(T* p, T* q, int n);  // copy from [p:p + n) to [q:q + n)
2120 This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.
2122 Use `const` for the "from" argument:
2124     void copy_n(const T* p, T* q, int n);  // copy from [p:p + n) to [q:q + n)
2126 ##### Exception
2128 If the order of the parameters is not important, there is no problem:
2130     int max(int a, int b);
2132 ##### Alternative
2134 Don't pass arrays as pointers, pass an object representing a range (e.g., a `span`):
2136     void copy_n(span<const T> p, span<T> q);  // copy from p to q
2138 ##### Alternative
2140 Define a `struct` as the parameter type and name the fields for those parameters accordingly:
2142     struct SystemParams {
2143         string config_file;
2144         string output_path;
2145         seconds timeout;
2146     };
2147     void initialize(SystemParams p);
2149 This tends to make invocations of this clear to future readers, as the parameters
2150 are often filled in by name at the call site.
2152 ##### Note
2154 Only the interface's designer can adequately address the source of violations of this guideline.
2156 ##### Enforcement strategy
2158 (Simple) Warn if two consecutive parameters share the same type
2160 We are still looking for a less-simple enforcement.
2162 ### <a name="Ri-abstract"></a>I.25: Prefer empty abstract classes as interfaces to class hierarchies
2164 ##### Reason
2166 Abstract classes that are empty (have no non-static member data) are more likely to be stable than base classes with state.
2168 ##### Example, bad
2170 You just knew that `Shape` would turn up somewhere :-)
2172     class Shape {  // bad: interface class loaded with data
2173     public:
2174         Point center() const { return c; }
2175         virtual void draw() const;
2176         virtual void rotate(int);
2177         // ...
2178     private:
2179         Point c;
2180         vector<Point> outline;
2181         Color col;
2182     };
2184 This will force every derived class to compute a center -- even if that's non-trivial and the center is never used. Similarly, not every `Shape` has a `Color`, and many `Shape`s are best represented without an outline defined as a sequence of `Point`s. Using an abstract class is better:
2186     class Shape {    // better: Shape is a pure interface
2187     public:
2188         virtual Point center() const = 0;   // pure virtual functions
2189         virtual void draw() const = 0;
2190         virtual void rotate(int) = 0;
2191         // ...
2192         // ... no data members ...
2193         // ...
2194         virtual ~Shape() = default;
2195     };
2197 ##### Enforcement
2199 (Simple) Warn if a pointer/reference to a class `C` is assigned to a pointer/reference to a base of `C` and the base class contains data members.
2201 ### <a name="Ri-abi"></a>I.26: If you want a cross-compiler ABI, use a C-style subset
2203 ##### Reason
2205 Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.
2207 ##### Exception
2209 Common ABIs are emerging on some platforms freeing you from the more draconian restrictions.
2211 ##### Note
2213 If you use a single compiler, you can use full C++ in interfaces. That might require recompilation after an upgrade to a new compiler version.
2215 ##### Enforcement
2217 (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
2219 ### <a name="Ri-pimpl"></a>I.27: For stable library ABI, consider the Pimpl idiom
2221 ##### Reason
2223 Because private data members participate in class layout and private member functions participate in overload resolution, changes to those
2224 implementation details require recompilation of all users of a class that uses them. A non-polymorphic interface class holding a pointer to
2225 implementation (Pimpl) can isolate the users of a class from changes in its implementation at the cost of an indirection.
2227 ##### Example
2229 interface (widget.h)
2231     class widget {
2232         class impl;
2233         std::unique_ptr<impl> pimpl;
2234     public:
2235         void draw(); // public API that will be forwarded to the implementation
2236         widget(int); // defined in the implementation file
2237         ~widget();   // defined in the implementation file, where impl is a complete type
2238         widget(widget&&) noexcept; // defined in the implementation file
2239         widget(const widget&) = delete;
2240         widget& operator=(widget&&) noexcept; // defined in the implementation file
2241         widget& operator=(const widget&) = delete;
2242     };
2245 implementation (widget.cpp)
2247     class widget::impl {
2248         int n; // private data
2249     public:
2250         void draw(const widget& w) { /* ... */ }
2251         impl(int n) : n(n) {}
2252     };
2253     void widget::draw() { pimpl->draw(*this); }
2254     widget::widget(int n) : pimpl{std::make_unique<impl>(n)} {}
2255     widget::widget(widget&&) noexcept = default;
2256     widget::~widget() = default;
2257     widget& widget::operator=(widget&&) noexcept = default;
2259 ##### Notes
2261 See [GOTW #100](https://herbsutter.com/gotw/_100/) and [cppreference](http://en.cppreference.com/w/cpp/language/pimpl) for the trade-offs and additional implementation details associated with this idiom.
2263 ##### Enforcement
2265 (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
2267 ### <a name="Ri-encapsulate"></a>I.30: Encapsulate rule violations
2269 ##### Reason
2271 To keep code simple and safe.
2272 Sometimes, ugly, unsafe, or error-prone techniques are necessary for logical or performance reasons.
2273 If so, keep them local, rather than "infecting" interfaces so that larger groups of programmers have to be aware of the
2274 subtleties.
2275 Implementation complexity should, if at all possible, not leak through interfaces into user code.
2277 ##### Example
2279 Consider a program that, depending on some form of input (e.g., arguments to `main`), should consume input
2280 from a file, from the command line, or from standard input.
2281 We might write
2283     bool owned;
2284     owner<istream*> inp;
2285     switch (source) {
2286     case std_in:        owned = false; inp = &cin;                       break;
2287     case command_line:  owned = true;  inp = new istringstream{argv[2]}; break;
2288     case file:          owned = true;  inp = new ifstream{argv[2]};      break;
2289     }
2290     istream& in = *inp;
2292 This violated the rule [against uninitialized variables](#Res-always),
2293 the rule against [ignoring ownership](#Ri-raw),
2294 and the rule [against magic constants](#Res-magic).
2295 In particular, someone has to remember to somewhere write
2297     if (owned) delete inp;
2299 We could handle this particular example by using `unique_ptr` with a special deleter that does nothing for `cin`,
2300 but that's complicated for novices (who can easily encounter this problem) and the example is an example of a more general
2301 problem where a property that we would like to consider static (here, ownership) needs infrequently be addressed
2302 at run time.
2303 The common, most frequent, and safest examples can be handled statically, so we don't want to add cost and complexity to those.
2304 But we must also cope with the uncommon, less-safe, and necessarily more expensive cases.
2305 Such examples are discussed in [[Str15]](http://www.stroustrup.com/resource-model.pdf).
2307 So, we write a class
2309     class Istream { [[gsl::suppress(lifetime)]]
2310     public:
2311         enum Opt { from_line = 1 };
2312         Istream() { }
2313         Istream(czstring p) : owned{true}, inp{new ifstream{p}} {}            // read from file
2314         Istream(czstring p, Opt) : owned{true}, inp{new istringstream{p}} {}  // read from command line
2315         ~Istream() { if (owned) delete inp; }
2316         operator istream&() { return *inp; }
2317     private:
2318         bool owned = false;
2319         istream* inp = &cin;
2320     };
2322 Now, the dynamic nature of `istream` ownership has been encapsulated.
2323 Presumably, a bit of checking for potential errors would be added in real code.
2325 ##### Enforcement
2327 * Hard, it is hard to decide what rule-breaking code is essential
2328 * Flag rule suppression that enable rule-violations to cross interfaces
2330 # <a name="S-functions"></a>F: Functions
2332 A function specifies an action or a computation that takes the system from one consistent state to the next. It is the fundamental building block of programs.
2334 It should be possible to name a function meaningfully, to specify the requirements of its argument, and clearly state the relationship between the arguments and the result. An implementation is not a specification. Try to think about what a function does as well as about how it does it.
2335 Functions are the most critical part in most interfaces, so see the interface rules.
2337 Function rule summary:
2339 Function definition rules:
2341 * [F.1: "Package" meaningful operations as carefully named functions](#Rf-package)
2342 * [F.2: A function should perform a single logical operation](#Rf-logical)
2343 * [F.3: Keep functions short and simple](#Rf-single)
2344 * [F.4: If a function might have to be evaluated at compile time, declare it `constexpr`](#Rf-constexpr)
2345 * [F.5: If a function is very small and time-critical, declare it inline](#Rf-inline)
2346 * [F.6: If your function must not throw, declare it `noexcept`](#Rf-noexcept)
2347 * [F.7: For general use, take `T*` or `T&` arguments rather than smart pointers](#Rf-smart)
2348 * [F.8: Prefer pure functions](#Rf-pure)
2349 * [F.9: Unused parameters should be unnamed](#Rf-unused)
2350 * [F.10: If an operation can be reused, give it a name](#Rf-name)
2351 * [F.11: Use an unnamed lambda if you need a simple function object in one place only](#Rf-lambda)
2353 Parameter passing expression rules:
2355 * [F.15: Prefer simple and conventional ways of passing information](#Rf-conventional)
2356 * [F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`](#Rf-in)
2357 * [F.17: For "in-out" parameters, pass by reference to non-`const`](#Rf-inout)
2358 * [F.18: For "will-move-from" parameters, pass by `X&&` and `std::move` the parameter](#Rf-consume)
2359 * [F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter](#Rf-forward)
2360 * [F.20: For "out" output values, prefer return values to output parameters](#Rf-out)
2361 * [F.21: To return multiple "out" values, prefer returning a struct or tuple](#Rf-out-multi)
2362 * [F.60: Prefer `T*` over `T&` when "no argument" is a valid option](#Rf-ptr-ref)
2364 Parameter passing semantic rules:
2366 * [F.22: Use `T*` or `owner<T*>` to designate a single object](#Rf-ptr)
2367 * [F.23: Use a `not_null<T>` to indicate that "null" is not a valid value](#Rf-nullptr)
2368 * [F.24: Use a `span<T>` or a `span_p<T>` to designate a half-open sequence](#Rf-range)
2369 * [F.25: Use a `zstring` or a `not_null<zstring>` to designate a C-style string](#Rf-zstring)
2370 * [F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed](#Rf-unique_ptr)
2371 * [F.27: Use a `shared_ptr<T>` to share ownership](#Rf-shared_ptr)
2373 <a name="Rf-value-return"></a>Value return semantic rules:
2375 * [F.42: Return a `T*` to indicate a position (only)](#Rf-return-ptr)
2376 * [F.43: Never (directly or indirectly) return a pointer or a reference to a local object](#Rf-dangle)
2377 * [F.44: Return a `T&` when copy is undesirable and "returning no object" isn't needed](#Rf-return-ref)
2378 * [F.45: Don't return a `T&&`](#Rf-return-ref-ref)
2379 * [F.46: `int` is the return type for `main()`](#Rf-main)
2380 * [F.47: Return `T&` from assignment operators](#Rf-assignment-op)
2381 * [F.48: Don't return `std::move(local)`](#Rf-return-move-local)
2382 * [F.49: Don't return `const T`](#Rf-return-const)
2384 Other function rules:
2386 * [F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)](#Rf-capture-vs-overload)
2387 * [F.51: Where there is a choice, prefer default arguments over overloading](#Rf-default-args)
2388 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
2389 * [F.53: Avoid capturing by reference in lambdas that will be used non-locally, including returned, stored on the heap, or passed to another thread](#Rf-value-capture)
2390 * [F.54: When writing a lambda that captures `this` or any class data member, don't use `[=]` default capture](#Rf-this-capture)
2391 * [F.55: Don't use `va_arg` arguments](#F-varargs)
2392 * [F.56: Avoid unnecessary condition nesting](#F-nesting)
2394 Functions have strong similarities to lambdas and function objects.
2396 **See also**: [C.lambdas: Function objects and lambdas](#SS-lambdas)
2398 ## <a name="SS-fct-def"></a>F.def: Function definitions
2400 A function definition is a function declaration that also specifies the function's implementation, the function body.
2402 ### <a name="Rf-package"></a>F.1: "Package" meaningful operations as carefully named functions
2404 ##### Reason
2406 Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code.
2407 If something is a well-specified action, separate it out from its surrounding code and give it a name.
2409 ##### Example, don't
2411     void read_and_print(istream& is)    // read and print an int
2412     {
2413         int x;
2414         if (is >> x)
2415             cout << "the int is " << x << '\n';
2416         else
2417             cerr << "no int on input\n";
2418     }
2420 Almost everything is wrong with `read_and_print`.
2421 It reads, it writes (to a fixed `ostream`), it writes error messages (to a fixed `ostream`), it handles only `int`s.
2422 There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use.
2423 For a tiny example, this looks OK, but if the input operation, the output operation, and the error handling had been more complicated the tangled
2424 mess could become hard to understand.
2426 ##### Note
2428 If you write a non-trivial lambda that potentially can be used in more than one place, give it a name by assigning it to a (usually non-local) variable.
2430 ##### Example
2432     sort(a, b, [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); });
2434 Naming that lambda breaks up the expression into its logical parts and provides a strong hint to the meaning of the lambda.
2436     auto lessT = [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); };
2438     sort(a, b, lessT);
2440 The shortest code is not always the best for performance or maintainability.
2442 ##### Exception
2444 Loop bodies, including lambdas used as loop bodies, rarely need to be named.
2445 However, large loop bodies (e.g., dozens of lines or dozens of pages) can be a problem.
2446 The rule [Keep functions short and simple](#Rf-single) implies "Keep loop bodies short."
2447 Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unlikely to be reusable.
2449 ##### Enforcement
2451 * See [Keep functions short and simple](#Rf-single)
2452 * Flag identical and very similar lambdas used in different places.
2454 ### <a name="Rf-logical"></a>F.2: A function should perform a single logical operation
2456 ##### Reason
2458 A function that performs a single operation is simpler to understand, test, and reuse.
2460 ##### Example
2462 Consider:
2464     void read_and_print()    // bad
2465     {
2466         int x;
2467         cin >> x;
2468         // check for errors
2469         cout << x << "\n";
2470     }
2472 This is a monolith that is tied to a specific input and will never find another (different) use. Instead, break functions up into suitable logical parts and parameterize:
2474     int read(istream& is)    // better
2475     {
2476         int x;
2477         is >> x;
2478         // check for errors
2479         return x;
2480     }
2482     void print(ostream& os, int x)
2483     {
2484         os << x << "\n";
2485     }
2487 These can now be combined where needed:
2489     void read_and_print()
2490     {
2491         auto x = read(cin);
2492         print(cout, x);
2493     }
2495 If there was a need, we could further templatize `read()` and `print()` on the data type, the I/O mechanism, the response to errors, etc. Example:
2497     auto read = [](auto& input, auto& value)    // better
2498     {
2499         input >> value;
2500         // check for errors
2501     };
2503     void print(auto& output, const auto& value)
2504     {
2505         output << value << "\n";
2506     }
2508 ##### Enforcement
2510 * Consider functions with more than one "out" parameter suspicious. Use return values instead, including `tuple` for multiple return values.
2511 * Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
2512 * Consider functions with 7 or more parameters suspicious.
2514 ### <a name="Rf-single"></a>F.3: Keep functions short and simple
2516 ##### Reason
2518 Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes.
2519 Functions with complex control structures are more likely to be long and more likely to hide logical errors
2521 ##### Example
2523 Consider:
2525     double simple_func(double val, int flag1, int flag2)
2526         // simple_func: takes a value and calculates the expected ASIC output,
2527         // given the two mode flags.
2528     {
2529         double intermediate;
2530         if (flag1 > 0) {
2531             intermediate = func1(val);
2532             if (flag2 % 2)
2533                  intermediate = sqrt(intermediate);
2534         }
2535         else if (flag1 == -1) {
2536             intermediate = func1(-val);
2537             if (flag2 % 2)
2538                  intermediate = sqrt(-intermediate);
2539             flag1 = -flag1;
2540         }
2541         if (abs(flag2) > 10) {
2542             intermediate = func2(intermediate);
2543         }
2544         switch (flag2 / 10) {
2545         case 1: if (flag1 == -1) return finalize(intermediate, 1.171);
2546                 break;
2547         case 2: return finalize(intermediate, 13.1);
2548         default: break;
2549         }
2550         return finalize(intermediate, 0.);
2551     }
2553 This is too complex.
2554 How would you know if all possible alternatives have been correctly handled?
2555 Yes, it breaks other rules also.
2557 We can refactor:
2559     double func1_muon(double val, int flag)
2560     {
2561         // ???
2562     }
2564     double func1_tau(double val, int flag1, int flag2)
2565     {
2566         // ???
2567     }
2569     double simple_func(double val, int flag1, int flag2)
2570         // simple_func: takes a value and calculates the expected ASIC output,
2571         // given the two mode flags.
2572     {
2573         if (flag1 > 0)
2574             return func1_muon(val, flag2);
2575         if (flag1 == -1)
2576             // handled by func1_tau: flag1 = -flag1;
2577             return func1_tau(-val, flag1, flag2);
2578         return 0.;
2579     }
2581 ##### Note
2583 "It doesn't fit on a screen" is often a good practical definition of "far too large."
2584 One-to-five-line functions should be considered normal.
2586 ##### Note
2588 Break large functions up into smaller cohesive and named functions.
2589 Small simple functions are easily inlined where the cost of a function call is significant.
2591 ##### Enforcement
2593 * Flag functions that do not "fit on a screen."
2594   How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
2595 * Flag functions that are too complex. How complex is too complex?
2596   You could use cyclomatic complexity. Try "more than 10 logical paths through." Count a simple switch as one path.
2598 ### <a name="Rf-constexpr"></a>F.4: If a function might have to be evaluated at compile time, declare it `constexpr`
2600 ##### Reason
2602  `constexpr` is needed to tell the compiler to allow compile-time evaluation.
2604 ##### Example
2606 The (in)famous factorial:
2608     constexpr int fac(int n)
2609     {
2610         constexpr int max_exp = 17;      // constexpr enables max_exp to be used in Expects
2611         Expects(0 <= n && n < max_exp);  // prevent silliness and overflow
2612         int x = 1;
2613         for (int i = 2; i <= n; ++i) x *= i;
2614         return x;
2615     }
2617 This is C++14.
2618 For C++11, use a recursive formulation of `fac()`.
2620 ##### Note
2622 `constexpr` does not guarantee compile-time evaluation;
2623 it just guarantees that the function can be evaluated at compile time for constant expression arguments if the programmer requires it or the compiler decides to do so to optimize.
2625     constexpr int min(int x, int y) { return x < y ? x : y; }
2627     void test(int v)
2628     {
2629         int m1 = min(-1, 2);            // probably compile-time evaluation
2630         constexpr int m2 = min(-1, 2);  // compile-time evaluation
2631         int m3 = min(-1, v);            // run-time evaluation
2632         constexpr int m4 = min(-1, v);  // error: cannot evaluate at compile time
2633     }
2635 ##### Note
2637 Don't try to make all functions `constexpr`.
2638 Most computation is best done at run time.
2640 ##### Note
2642 Any API that might eventually depend on high-level run-time configuration or
2643 business logic should not be made `constexpr`. Such customization can not be
2644 evaluated by the compiler, and any `constexpr` functions that depended upon
2645 that API would have to be refactored or drop `constexpr`.
2647 ##### Enforcement
2649 Impossible and unnecessary.
2650 The compiler gives an error if a non-`constexpr` function is called where a constant is required.
2652 ### <a name="Rf-inline"></a>F.5: If a function is very small and time-critical, declare it `inline`
2654 ##### Reason
2656 Some optimizers are good at inlining without hints from the programmer, but don't rely on it.
2657 Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans.
2658 We are still waiting.
2659 Specifying inline (explicitly, or implicitly when writing member functions inside a class definition) encourages the compiler to do a better job.
2661 ##### Example
2663     inline string cat(const string& s, const string& s2) { return s + s2; }
2665 ##### Exception
2667 Do not put an `inline` function in what is meant to be a stable interface unless you are certain that it will not change.
2668 An inline function is part of the ABI.
2670 ##### Note
2672 `constexpr` implies `inline`.
2674 ##### Note
2676 Member functions defined in-class are `inline` by default.
2678 ##### Exception
2680 Function templates (including member functions of class templates `A<T>::function()` and member function templates `A::function<T>()`) are normally defined in headers and therefore inline.
2682 ##### Enforcement
2684 Flag `inline` functions that are more than three statements and could have been declared out of line (such as class member functions).
2686 ### <a name="Rf-noexcept"></a>F.6: If your function must not throw, declare it `noexcept`
2688 ##### Reason
2690 If an exception is not supposed to be thrown, the program cannot be assumed to cope with the error and should be terminated as soon as possible. Declaring a function `noexcept` helps optimizers by reducing the number of alternative execution paths. It also speeds up the exit after failure.
2692 ##### Example
2694 Put `noexcept` on every function written completely in C or in any other language without exceptions.
2695 The C++ Standard Library does that implicitly for all functions in the C Standard Library.
2697 ##### Note
2699 `constexpr` functions can throw when evaluated at run time, so you might need conditional `noexcept` for some of those.
2701 ##### Example
2703 You can use `noexcept` even on functions that can throw:
2705     vector<string> collect(istream& is) noexcept
2706     {
2707         vector<string> res;
2708         for (string s; is >> s;)
2709             res.push_back(s);
2710         return res;
2711     }
2713 If `collect()` runs out of memory, the program crashes.
2714 Unless the program is crafted to survive memory exhaustion, that might be just the right thing to do;
2715 `terminate()` might generate suitable error log information (but after memory runs out it is hard to do anything clever).
2717 ##### Note
2719 You must be aware of the execution environment that your code is running when
2720 deciding whether to tag a function `noexcept`, especially because of the issue
2721 of throwing and allocation.  Code that is intended to be perfectly general (like
2722 the standard library and other utility code of that sort) needs to support
2723 environments where a `bad_alloc` exception could be handled meaningfully.
2724 However, most programs and execution environments cannot meaningfully
2725 handle a failure to allocate, and aborting the program is the cleanest and
2726 simplest response to an allocation failure in those cases.  If you know that
2727 your application code cannot respond to an allocation failure, it could be
2728 appropriate to add `noexcept` even on functions that allocate.
2730 Put another way: In most programs, most functions can throw (e.g., because they
2731 use `new`, call functions that do, or use library functions that reports failure
2732 by throwing), so don't just sprinkle `noexcept` all over the place without
2733 considering whether the possible exceptions can be handled.
2735 `noexcept` is most useful (and most clearly correct) for frequently used,
2736 low-level functions.
2738 ##### Note
2740 Destructors, `swap` functions, move operations, and default constructors should never throw.
2741 See also [C.44](#Rc-default00).
2743 ##### Enforcement
2745 * Flag functions that are not `noexcept`, yet cannot throw.
2746 * Flag throwing `swap`, `move`, destructors, and default constructors.
2748 ### <a name="Rf-smart"></a>F.7: For general use, take `T*` or `T&` arguments rather than smart pointers
2750 ##### Reason
2752 Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended.
2753 A function that does not manipulate lifetime should take raw pointers or references instead.
2755 Passing by smart pointer restricts the use of a function to callers that use smart pointers.
2756 A function that needs a `widget` should be able to accept any `widget` object, not just ones whose lifetimes are managed by a particular kind of smart pointer.
2758 Passing a shared smart pointer (e.g., `std::shared_ptr`) implies a run-time cost.
2760 ##### Example
2762     // accepts any int*
2763     void f(int*);
2765     // can only accept ints for which you want to transfer ownership
2766     void g(unique_ptr<int>);
2768     // can only accept ints for which you are willing to share ownership
2769     void g(shared_ptr<int>);
2771     // doesn't change ownership, but requires a particular ownership of the caller
2772     void h(const unique_ptr<int>&);
2774     // accepts any int
2775     void h(int&);
2777 ##### Example, bad
2779     // callee
2780     void f(shared_ptr<widget>& w)
2781     {
2782         // ...
2783         use(*w); // only use of w -- the lifetime is not used at all
2784         // ...
2785     };
2787     // caller
2788     shared_ptr<widget> my_widget = /* ... */;
2789     f(my_widget);
2791     widget stack_widget;
2792     f(stack_widget); // error
2794 ##### Example, good
2796     // callee
2797     void f(widget& w)
2798     {
2799         // ...
2800         use(w);
2801         // ...
2802     };
2804     // caller
2805     shared_ptr<widget> my_widget = /* ... */;
2806     f(*my_widget);
2808     widget stack_widget;
2809     f(stack_widget); // ok -- now this works
2811 ##### Note
2813 We can catch many common cases of dangling pointers statically (see [lifetime safety profile](#SS-lifetime)). Function arguments naturally live for the lifetime of the function call, and so have fewer lifetime problems.
2815 ##### Enforcement
2817 * (Simple) Warn if a function takes a parameter of a smart pointer type (that overloads `operator->` or `operator*`) that is copyable but the function only calls any of: `operator*`, `operator->` or `get()`.
2818   Suggest using a `T*` or `T&` instead.
2819 * Flag a parameter of a smart pointer type (a type that overloads `operator->` or `operator*`) that is copyable/movable but never copied/moved from in the function body, and that is never modified, and that is not passed along to another function that could do so. That means the ownership semantics are not used.
2820   Suggest using a `T*` or `T&` instead.
2822 **See also**:
2824 * [Prefer `T*` over `T&` when "no argument" is a valid option](#Rf-ptr-ref)
2825 * [Smart pointer rule summary](#Rr-summary-smartptrs)
2827 ### <a name="Rf-pure"></a>F.8: Prefer pure functions
2829 ##### Reason
2831 Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.
2833 ##### Example
2835     template<class T>
2836     auto square(T t) { return t * t; }
2838 ##### Enforcement
2840 Not possible.
2842 ### <a name="Rf-unused"></a>F.9: Unused parameters should be unnamed
2844 ##### Reason
2846 Readability.
2847 Suppression of unused parameter warnings.
2849 ##### Example
2851     widget* find(const set<widget>& s, const widget& w, Hint);   // once upon a time, a hint was used
2853 ##### Note
2855 Allowing parameters to be unnamed was introduced in the early 1980s to address this problem.
2857 If parameters are conditionally unused, declare them with the `[[maybe_unused]]` attribute.
2858 For example:
2860     template <typename Value>
2861     Value* find(const set<Value>& s, const Value& v, [[maybe_unused]] Hint h)
2862     {
2863         if constexpr (sizeof(Value) > CacheSize)
2864         {
2865             // a hint is used only if Value is of a certain size
2866         }
2867     }
2869 ##### Enforcement
2871 Flag named unused parameters.
2873 ### <a name="Rf-name"></a>F.10: If an operation can be reused, give it a name
2875 ##### Reason
2877 Documentation, readability, opportunity for reuse.
2879 ##### Example
2881     struct Rec {
2882         string name;
2883         string addr;
2884         int id;         // unique identifier
2885     };
2887     bool same(const Rec& a, const Rec& b)
2888     {
2889         return a.id == b.id;
2890     }
2892     vector<Rec*> find_id(const string& name);    // find all records for "name"
2894     auto x = find_if(vr.begin(), vr.end(),
2895         [&](Rec& r) {
2896             if (r.name.size() != n.size()) return false; // name to compare to is in n
2897             for (int i = 0; i < r.name.size(); ++i)
2898                 if (tolower(r.name[i]) != tolower(n[i])) return false;
2899             return true;
2900         }
2901     );
2903 There is a useful function lurking here (case insensitive string comparison), as there often is when lambda arguments get large.
2905     bool compare_insensitive(const string& a, const string& b)
2906     {
2907         if (a.size() != b.size()) return false;
2908         for (int i = 0; i < a.size(); ++i) if (tolower(a[i]) != tolower(b[i])) return false;
2909         return true;
2910     }
2912     auto x = find_if(vr.begin(), vr.end(),
2913         [&](Rec& r) { return compare_insensitive(r.name, n); }
2914     );
2916 Or maybe (if you prefer to avoid the implicit name binding to n):
2918     auto cmp_to_n = [&n](const string& a) { return compare_insensitive(a, n); };
2920     auto x = find_if(vr.begin(), vr.end(),
2921         [](const Rec& r) { return cmp_to_n(r.name); }
2922     );
2924 ##### Note
2926 whether functions, lambdas, or operators.
2928 ##### Exception
2930 * Lambdas logically used only locally, such as an argument to `for_each` and similar control flow algorithms.
2931 * Lambdas as [initializers](#???)
2933 ##### Enforcement
2935 * (hard) flag similar lambdas
2936 * ???
2938 ### <a name="Rf-lambda"></a>F.11: Use an unnamed lambda if you need a simple function object in one place only
2940 ##### Reason
2942 That makes the code concise and gives better locality than alternatives.
2944 ##### Example
2946     auto earlyUsersEnd = std::remove_if(users.begin(), users.end(),
2947                                         [](const User &a) { return a.id > 100; });
2950 ##### Exception
2952 Naming a lambda can be useful for clarity even if it is used only once.
2954 ##### Enforcement
2956 * Look for identical and near identical lambdas (to be replaced with named functions or named lambdas).
2958 ## <a name="SS-call"></a>F.call: Parameter passing
2960 There are a variety of ways to pass parameters to a function and to return values.
2962 ### <a name="Rf-conventional"></a>F.15: Prefer simple and conventional ways of passing information
2964 ##### Reason
2966 Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs.
2967 If you really feel the need for an optimization beyond the common techniques, measure to ensure that it really is an improvement, and document/comment because the improvement might not be portable.
2969 The following tables summarize the advice in the following Guidelines, F.16-21.
2971 Normal parameter passing:
2973 ![Normal parameter passing table](./param-passing-normal.png "Normal parameter passing")
2975 Advanced parameter passing:
2977 ![Advanced parameter passing table](./param-passing-advanced.png "Advanced parameter passing")
2979 Use the advanced techniques only after demonstrating need, and document that need in a comment.
2981 For passing sequences of characters see [String](#SS-string).
2983 ##### Exception
2985 To express shared ownership using `shared_ptr` types, rather than following guidelines F.16-21,
2986 follow [R.34](#Rr-sharedptrparam-owner), [R.35](#Rr-sharedptrparam), and [R.36](#Rr-sharedptrparam-const).
2988 ### <a name="Rf-in"></a>F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`
2990 ##### Reason
2992 Both let the caller know that a function will not modify the argument, and both allow initialization by rvalues.
2994 What is "cheap to copy" depends on the machine architecture, but two or three words (doubles, pointers, references) are usually best passed by value.
2995 When copying is cheap, nothing beats the simplicity and safety of copying, and for small objects (up to two or three words) it is also faster than passing by reference because it does not require an extra indirection to access from the function.
2997 ##### Example
2999     void f1(const string& s);  // OK: pass by reference to const; always cheap
3001     void f2(string s);         // bad: potentially expensive
3003     void f3(int x);            // OK: Unbeatable
3005     void f4(const int& x);     // bad: overhead on access in f4()
3007 For advanced uses (only), where you really need to optimize for rvalues passed to "input-only" parameters:
3009 * If the function is going to unconditionally move from the argument, take it by `&&`. See [F.18](#Rf-consume).
3010 * If the function is going to keep a copy of the argument, in addition to passing by `const&` (for lvalues),
3011   add an overload that passes the parameter by `&&` (for rvalues) and in the body `std::move`s it to its destination. Essentially this overloads a "will-move-from"; see [F.18](#Rf-consume).
3012 * In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. See [F.19](#Rf-forward).
3014 ##### Example
3016     int multiply(int, int); // just input ints, pass by value
3018     // suffix is input-only but not as cheap as an int, pass by const&
3019     string& concatenate(string&, const string& suffix);
3021     void sink(unique_ptr<widget>);  // input only, and moves ownership of the widget
3023 Avoid "esoteric techniques" such as passing arguments as `T&&` "for efficiency".
3024 Most rumors about performance advantages from passing by `&&` are false or brittle (but see [F.18](#Rf-consume) and [F.19](#Rf-forward)).
3026 ##### Notes
3028 A reference can be assumed to refer to a valid object (language rule).
3029 There is no (legitimate) "null reference."
3030 If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value."
3032 ##### Enforcement
3034 * (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than `2 * sizeof(void*)`.
3035   Suggest using a reference to `const` instead.
3036 * (Simple) ((Foundation)) Warn when a parameter passed by reference to `const` has a size less or equal than `2 * sizeof(void*)`. Suggest passing by value instead.
3037 * (Simple) ((Foundation)) Warn when a parameter passed by reference to `const` is `move`d.
3039 ##### Exception
3041 To express shared ownership using `shared_ptr` types, follow [R.34](#Rr-sharedptrparam-owner) or [R.36](#Rr-sharedptrparam-const),
3042 depending on whether or not the function unconditionally takes a reference to the argument.
3044 ### <a name="Rf-inout"></a>F.17: For "in-out" parameters, pass by reference to non-`const`
3046 ##### Reason
3048 This makes it clear to callers that the object is assumed to be modified.
3050 ##### Example
3052     void update(Record& r);  // assume that update writes to r
3054 ##### Note
3056 Some user-defined and standard library types, such as `span<T>` or the iterators
3057 are [cheap to copy](#Rf-in) and may be passed by value, while doing so has
3058 mutable (in-out) reference semantics:
3060     void increment_all(span<int> a)
3061     {
3062       for (auto&& e : a)
3063         ++e;
3064     }
3066 ##### Note
3068 A `T&` argument can pass information into a function as well as out of it.
3069 Thus `T&` could be an in-out-parameter. That can in itself be a problem and a source of errors:
3071     void f(string& s)
3072     {
3073         s = "New York";  // non-obvious error
3074     }
3076     void g()
3077     {
3078         string buffer = ".................................";
3079         f(buffer);
3080         // ...
3081     }
3083 Here, the writer of `g()` is supplying a buffer for `f()` to fill, but `f()` simply replaces it (at a somewhat higher cost than a simple copy of the characters).
3084 A bad logic error can happen if the writer of `g()` incorrectly assumes the size of the `buffer`.
3086 ##### Enforcement
3088 * (Moderate) ((Foundation)) Warn about functions regarding reference to non-`const` parameters that do *not* write to them.
3089 * (Simple) ((Foundation)) Warn when a non-`const` parameter being passed by reference is `move`d.
3091 ### <a name="Rf-consume"></a>F.18: For "will-move-from" parameters, pass by `X&&` and `std::move` the parameter
3093 ##### Reason
3095 It's efficient and eliminates bugs at the call site: `X&&` binds to rvalues, which requires an explicit `std::move` at the call site if passing an lvalue.
3097 ##### Example
3099     void sink(vector<int>&& v)  // sink takes ownership of whatever the argument owned
3100     {
3101         // usually there might be const accesses of v here
3102         store_somewhere(std::move(v));
3103         // usually no more use of v here; it is moved-from
3104     }
3106 Note that the `std::move(v)` makes it possible for `store_somewhere()` to leave `v` in a moved-from state.
3107 [That could be dangerous](#Rc-move-semantic).
3110 ##### Exception
3112 Unique owner types that are move-only and cheap-to-move, such as `unique_ptr`, can also be passed by value which is simpler to write and achieves the same effect. Passing by value does generate one extra (cheap) move operation, but prefer simplicity and clarity first.
3114 For example:
3116     template<class T>
3117     void sink(std::unique_ptr<T> p)
3118     {
3119         // use p ... possibly std::move(p) onward somewhere else
3120     }   // p gets destroyed
3122 ##### Exception
3124 If the "will-move-from" parameter is a `shared_ptr` follow [R.34](#Rr-sharedptrparam-owner) and pass the `shared_ptr` by value.
3126 ##### Enforcement
3128 * Flag all `X&&` parameters (where `X` is not a template type parameter name) where the function body uses them without `std::move`.
3129 * Flag access to moved-from objects.
3130 * Don't conditionally move from objects
3132 ### <a name="Rf-forward"></a>F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter
3134 ##### Reason
3136 If the object is to be passed onward to other code and not directly used by this function, we want to make this function agnostic to the argument `const`-ness and rvalue-ness.
3138 In that case, and only that case, make the parameter `TP&&` where `TP` is a template type parameter -- it both *ignores* and *preserves* `const`-ness and rvalue-ness. Therefore any code that uses a `TP&&` is implicitly declaring that it itself doesn't care about the variable's `const`-ness and rvalue-ness (because it is ignored), but that intends to pass the value onward to other code that does care about `const`-ness and rvalue-ness (because it is preserved). When used as a parameter `TP&&` is safe because any temporary objects passed from the caller will live for the duration of the function call. A parameter of type `TP&&` should essentially always be passed onward via `std::forward` in the body of the function.
3140 ##### Example
3142 Usually you forward the entire parameter (or parameter pack, using `...`) exactly once on every static control flow path:
3144     template<class F, class... Args>
3145     inline decltype(auto) invoke(F&& f, Args&&... args)
3146     {
3147         return forward<F>(f)(forward<Args>(args)...);
3148     }
3150 ##### Example
3152 Sometimes you may forward a composite parameter piecewise, each subobject once on every static control flow path:
3154     template<class PairLike>
3155     inline auto test(PairLike&& pairlike)
3156     {
3157         // ...
3158         f1(some, args, and, forward<PairLike>(pairlike).first);           // forward .first
3159         f2(and, forward<PairLike>(pairlike).second, in, another, call);   // forward .second
3160     }
3162 ##### Enforcement
3164 * Flag a function that takes a `TP&&` parameter (where `TP` is a template type parameter name) and does anything with it other than `std::forward`ing it exactly once on every static path, or `std::forward`ing it more than once but qualified with a different data member exactly once on every static path.
3166 ### <a name="Rf-out"></a>F.20: For "out" output values, prefer return values to output parameters
3168 ##### Reason
3170 A return value is self-documenting, whereas a `&` could be either in-out or out-only and is liable to be misused.
3172 This includes large objects like standard containers that use implicit move operations for performance and to avoid explicit memory management.
3174 If you have multiple values to return, [use a tuple](#Rf-out-multi) or similar multi-member type.
3176 ##### Example
3178     // OK: return pointers to elements with the value x
3179     vector<const int*> find_all(const vector<int>&, int x);
3181     // Bad: place pointers to elements with value x in-out
3182     void find_all(const vector<int>&, vector<const int*>& out, int x);
3184 ##### Note
3186 A `struct` of many (individually cheap-to-move) elements might be in aggregate expensive to move.
3188 ##### Exceptions
3190 * For non-concrete types, such as types in an inheritance hierarchy, return the object by `unique_ptr` or `shared_ptr`.
3191 * If a type is expensive to move (e.g., `array<BigTrivial>`), consider allocating it on the free store and return a handle (e.g., `unique_ptr`), or passing it in a reference to non-`const` target object to fill (to be used as an out-parameter).
3192 * To reuse an object that carries capacity (e.g., `std::string`, `std::vector`) across multiple calls to the function in an inner loop: [treat it as an in/out parameter and pass by reference](#Rf-out-multi).
3194 ##### Example
3196 Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`):
3198     Matrix operator+(const Matrix& a, const Matrix& b)
3199     {
3200         Matrix res;
3201         // ... fill res with the sum ...
3202         return res;
3203     }
3205     Matrix x = m1 + m2;  // move constructor
3207     y = m3 + m3;         // move assignment
3210 ##### Note
3212 The return value optimization doesn't handle the assignment case, but the move assignment does.
3214 ##### Example
3216     struct Package {      // exceptional case: expensive-to-move object
3217         char header[16];
3218         char load[2024 - 16];
3219     };
3221     Package fill();       // Bad: large return value
3222     void fill(Package&);  // OK
3224     int val();            // OK
3225     void val(int&);       // Bad: Is val reading its argument
3227 ##### Enforcement
3229 * Flag reference to non-`const` parameters that are not read before being written to and are a type that could be cheaply returned; they should be "out" return values.
3231 ### <a name="Rf-out-multi"></a>F.21: To return multiple "out" values, prefer returning a struct or tuple
3233 ##### Reason
3235 A return value is self-documenting as an "output-only" value.
3236 Note that C++ does have multiple return values, by convention of using a `tuple` (including `pair`), possibly with the extra convenience of `tie` or structured bindings (C++17) at the call site.
3237 Prefer using a named struct where there are semantics to the returned value. Otherwise, a nameless `tuple` is useful in generic code.
3239 ##### Example
3241     // BAD: output-only parameter documented in a comment
3242     int f(const string& input, /*output only*/ string& output_data)
3243     {
3244         // ...
3245         output_data = something();
3246         return status;
3247     }
3249     // GOOD: self-documenting
3250     tuple<int, string> f(const string& input)
3251     {
3252         // ...
3253         return {status, something()};
3254     }
3256 C++98's standard library already used this style, because a `pair` is like a two-element `tuple`.
3257 For example, given a `set<string> my_set`, consider:
3259     // C++98
3260     result = my_set.insert("Hello");
3261     if (result.second) do_something_with(result.first);    // workaround
3263 With C++11 we can write this, putting the results directly in existing local variables:
3265     Sometype iter;                                // default initialize if we haven't already
3266     Someothertype success;                        // used these variables for some other purpose
3268     tie(iter, success) = my_set.insert("Hello");   // normal return value
3269     if (success) do_something_with(iter);
3271 With C++17 we are able to use "structured bindings" to declare and initialize the multiple variables:
3273     if (auto [ iter, success ] = my_set.insert("Hello"); success) do_something_with(iter);
3275 ##### Exception
3277 Sometimes, we need to pass an object to a function to manipulate its state.
3278 In such cases, passing the object by reference [`T&`](#Rf-inout) is usually the right technique.
3279 Explicitly passing an in-out parameter back out again as a return value is often not necessary.
3280 For example:
3282     istream& operator>>(istream& in, string& s);    // much like std::operator>>()
3284     for (string s; in >> s; ) {
3285         // do something with line
3286     }
3288 Here, both `s` and `in` are used as in-out parameters.
3289 We pass `in` by (non-`const`) reference to be able to manipulate its state.
3290 We pass `s` to avoid repeated allocations.
3291 By reusing `s` (passed by reference), we allocate new memory only when we need to expand `s`'s capacity.
3292 This technique is sometimes called the "caller-allocated out" pattern and is particularly useful for types,
3293 such as `string` and `vector`, that needs to do free store allocations.
3295 To compare, if we passed out all values as return values, we would something like this:
3297     pair<istream&, string> get_string(istream& in)  // not recommended
3298     {
3299         string s;
3300         in >> s;
3301         return {in, move(s)};
3302     }
3304     for (auto p = get_string(cin); p.first; p.second = get_string(p.first).second) {
3305         // do something with p.second
3306     }
3308 We consider that significantly less elegant with significantly less performance.
3310 For a truly strict reading of this rule (F.21), the exception isn't really an exception because it relies on in-out parameters,
3311 rather than the plain out parameters mentioned in the rule.
3312 However, we prefer to be explicit, rather than subtle.
3314 ##### Note
3316 In many cases, it can be useful to return a specific, user-defined type.
3317 For example:
3319     struct Distance {
3320         int value;
3321         int unit = 1;   // 1 means meters
3322     };
3324     Distance d1 = measure(obj1);        // access d1.value and d1.unit
3325     auto d2 = measure(obj2);            // access d2.value and d2.unit
3326     auto [value, unit] = measure(obj3); // access value and unit; somewhat redundant
3327                                         // to people who know measure()
3328     auto [x, y] = measure(obj4);        // don't; it's likely to be confusing
3330 The overly-generic `pair` and `tuple` should be used only when the value returned represents independent entities rather than an abstraction.
3332 Another example, use a specific type along the lines of `variant<T, error_code>`, rather than using the generic `tuple`.
3334 ##### Note
3336 When the tuple to be returned is initialized from local variables that are expensive to copy,
3337 explicit `move` may be helpful to avoid copying:
3339     pair<LargeObject, LargeObject> f(const string& input)
3340     {
3341         LargeObject large1 = g(input);
3342         LargeObject large2 = h(input);
3343         // ...
3344         return { move(large1), move(large2) }; // no copies
3345     }
3347 Alternatively,
3349     pair<LargeObject, LargeObject> f(const string& input)
3350     {
3351         // ...
3352         return { g(input), h(input) }; // no copies, no moves
3353     }
3355 Note this is different from the `return move(...)` anti-pattern from [ES.56](#Res-move)
3357 ##### Enforcement
3359 * Output parameters should be replaced by return values.
3360   An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`.
3362 ### <a name="Rf-ptr-ref"></a>F.60: Prefer `T*` over `T&` when "no argument" is a valid option
3364 ##### Reason
3366 A pointer (`T*`) can be a `nullptr` and a reference (`T&`) cannot, there is no valid "null reference".
3367 Sometimes having `nullptr` as an alternative to indicated "no object" is useful, but if it is not, a reference is notationally simpler and might yield better code.
3369 ##### Example
3371     string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string
3372     {
3373         if (!p) return string{};    // p might be nullptr; remember to check
3374         return string{p};
3375     }
3377     void print(const vector<int>& r)
3378     {
3379         // r refers to a vector<int>; no check needed
3380     }
3382 ##### Note
3384 It is possible, but not valid C++ to construct a reference that is essentially a `nullptr` (e.g., `T* p = nullptr; T& r = *p;`).
3385 That error is very uncommon.
3387 ##### Note
3389 If you prefer the pointer notation (`->` and/or `*` vs. `.`), `not_null<T*>` provides the same guarantee as `T&`.
3391 ##### Enforcement
3393 * Flag ???
3395 ### <a name="Rf-ptr"></a>F.22: Use `T*` or `owner<T*>` to designate a single object
3397 ##### Reason
3399 Readability: it makes the meaning of a plain pointer clear.
3400 Enables significant tool support.
3402 ##### Note
3404 In traditional C and C++ code, plain `T*` is used for many weakly-related purposes, such as:
3406 * Identify a (single) object (not to be deleted by this function)
3407 * Point to an object allocated on the free store (and delete it later)
3408 * Hold the `nullptr`
3409 * Identify a C-style string (zero-terminated array of characters)
3410 * Identify an array with a length specified separately
3411 * Identify a location in an array
3413 This makes it hard to understand what the code does and is supposed to do.
3414 It complicates checking and tool support.
3416 ##### Example
3418     void use(int* p, int n, char* s, int* q)
3419     {
3420         p[n - 1] = 666; // Bad: we don't know if p points to n elements;
3421                         // assume it does not or use span<int>
3422         cout << s;      // Bad: we don't know if that s points to a zero-terminated array of char;
3423                         // assume it does not or use zstring
3424         delete q;       // Bad: we don't know if *q is allocated on the free store;
3425                         // assume it does not or use owner
3426     }
3428 better
3430     void use2(span<int> p, zstring s, owner<int*> q)
3431     {
3432         p[p.size() - 1] = 666; // OK, a range error can be caught
3433         cout << s; // OK
3434         delete q;  // OK
3435     }
3437 ##### Note
3439 `owner<T*>` represents ownership, `zstring` represents a C-style string.
3441 **Also**: Assume that a `T*` obtained from a smart pointer to `T` (e.g., `unique_ptr<T>`) points to a single element.
3443 **See also**: [Support library](#gsl-guidelines-support-library)
3445 **See also**: [Do not pass an array as a single pointer](#Ri-array)
3447 ##### Enforcement
3449 * (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
3451 ### <a name="Rf-nullptr"></a>F.23: Use a `not_null<T>` to indicate that "null" is not a valid value
3453 ##### Reason
3455 Clarity. A function with a `not_null<T>` parameter makes it clear that the caller of the function is responsible for any `nullptr` checks that might be necessary.
3456 Similarly, a function with a return value of `not_null<T>` makes it clear that the caller of the function does not need to check for `nullptr`.
3458 ##### Example
3460 `not_null<T*>` makes it obvious to a reader (human or machine) that a test for `nullptr` is not necessary before dereference.
3461 Additionally, when debugging, `owner<T*>` and `not_null<T>` can be instrumented to check for correctness.
3463 Consider:
3465     int length(Record* p);
3467 When I call `length(p)` should I check if `p` is `nullptr` first? Should the implementation of `length()` check if `p` is `nullptr`?
3469     // it is the caller's job to make sure p != nullptr
3470     int length(not_null<Record*> p);
3472     // the implementor of length() must assume that p == nullptr is possible
3473     int length(Record* p);
3475 ##### Note
3477 A `not_null<T*>` is assumed not to be the `nullptr`; a `T*` might be the `nullptr`; both can be represented in memory as a `T*` (so no run-time overhead is implied).
3479 ##### Note
3481 `not_null` is not just for built-in pointers. It works for `unique_ptr`, `shared_ptr`, and other pointer-like types.
3483 ##### Enforcement
3485 * (Simple) Warn if a raw pointer is dereferenced without being tested against `nullptr` (or equivalent) within a function, suggest it is declared `not_null` instead.
3486 * (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against `nullptr` (or equivalent) within the function and sometimes is not.
3487 * (Simple) Warn if a `not_null` pointer is tested against `nullptr` within a function.
3489 ### <a name="Rf-range"></a>F.24: Use a `span<T>` or a `span_p<T>` to designate a half-open sequence
3491 ##### Reason
3493 Informal/non-explicit ranges are a source of errors.
3495 ##### Example
3497     X* find(span<X> r, const X& v);    // find v in r
3499     vector<X> vec;
3500     // ...
3501     auto p = find({vec.begin(), vec.end()}, X{});  // find X{} in vec
3503 ##### Note
3505 Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure.
3506 In particular, given a pair of arguments `(p, n)` designating an array `[p:p+n)`,
3507 it is in general impossible to know if there really are `n` elements to access following `*p`.
3508 `span<T>` and `span_p<T>` are simple helper classes designating a `[p:q)` range and a range starting with `p` and ending with the first element for which a predicate is true, respectively.
3510 ##### Example
3512 A `span` represents a range of elements, but how do we manipulate elements of that range?
3514     void f(span<int> s)
3515     {
3516         // range traversal (guaranteed correct)
3517         for (int x : s) cout << x << '\n';
3519         // C-style traversal (potentially checked)
3520         for (gsl::index i = 0; i < s.size(); ++i) cout << s[i] << '\n';
3522         // random access (potentially checked)
3523         s[7] = 9;
3525         // extract pointers (potentially checked)
3526         std::sort(&s[0], &s[s.size() / 2]);
3527     }
3529 ##### Note
3531 A `span<T>` object does not own its elements and is so small that it can be passed by value.
3533 Passing a `span` object as an argument is exactly as efficient as passing a pair of pointer arguments or passing a pointer and an integer count.
3535 **See also**: [Support library](#gsl-guidelines-support-library)
3537 ##### Enforcement
3539 (Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `span` instead.
3541 ### <a name="Rf-zstring"></a>F.25: Use a `zstring` or a `not_null<zstring>` to designate a C-style string
3543 ##### Reason
3545 C-style strings are ubiquitous. They are defined by convention: zero-terminated arrays of characters.
3546 We must distinguish C-style strings from a pointer to a single character or an old-fashioned pointer to an array of characters.
3548 If you don't need null termination, use `string_view`.
3550 ##### Example
3552 Consider:
3554     int length(const char* p);
3556 When I call `length(s)` should I check if `s` is `nullptr` first? Should the implementation of `length()` check if `p` is `nullptr`?
3558     // the implementor of length() must assume that p == nullptr is possible
3559     int length(zstring p);
3561     // it is the caller's job to make sure p != nullptr
3562     int length(not_null<zstring> p);
3564 ##### Note
3566 `zstring` does not represent ownership.
3568 **See also**: [Support library](#gsl-guidelines-support-library)
3570 ### <a name="Rf-unique_ptr"></a>F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed
3572 ##### Reason
3574 Using `unique_ptr` is the cheapest way to pass a pointer safely.
3576 **See also**: [C.50](#Rc-factory) regarding when to return a `shared_ptr` from a factory.
3578 ##### Example
3580     unique_ptr<Shape> get_shape(istream& is)  // assemble shape from input stream
3581     {
3582         auto kind = read_header(is); // read header and identify the next shape on input
3583         switch (kind) {
3584         case kCircle:
3585             return make_unique<Circle>(is);
3586         case kTriangle:
3587             return make_unique<Triangle>(is);
3588         // ...
3589         }
3590     }
3592 ##### Note
3594 You need to pass a pointer rather than an object if what you are transferring is an object from a class hierarchy that is to be used through an interface (base class).
3596 ##### Enforcement
3598 (Simple) Warn if a function returns a locally allocated raw pointer. Suggest using either `unique_ptr` or `shared_ptr` instead.
3600 ### <a name="Rf-shared_ptr"></a>F.27: Use a `shared_ptr<T>` to share ownership
3602 ##### Reason
3604 Using `std::shared_ptr` is the standard way to represent shared ownership. That is, the last owner deletes the object.
3606 ##### Example
3608     shared_ptr<const Image> im { read_image(somewhere) };
3610     std::thread t0 {shade, args0, top_left, im};
3611     std::thread t1 {shade, args1, top_right, im};
3612     std::thread t2 {shade, args2, bottom_left, im};
3613     std::thread t3 {shade, args3, bottom_right, im};
3615     // detach threads
3616     // last thread to finish deletes the image
3618 ##### Note
3620 Prefer a `unique_ptr` over a `shared_ptr` if there is never more than one owner at a time.
3621 `shared_ptr` is for shared ownership.
3623 Note that pervasive use of `shared_ptr` has a cost (atomic operations on the `shared_ptr`'s reference count have a measurable aggregate cost).
3625 ##### Alternative
3627 Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.
3629 ##### Enforcement
3631 (Not enforceable) This is a too complex pattern to reliably detect.
3633 ### <a name="Rf-return-ptr"></a>F.42: Return a `T*` to indicate a position (only)
3635 ##### Reason
3637 That's what pointers are good for.
3638 Returning a `T*` to transfer ownership is a misuse.
3640 ##### Example
3642     Node* find(Node* t, const string& s)  // find s in a binary tree of Nodes
3643     {
3644         if (!t || t->name == s) return t;
3645         if ((auto p = find(t->left, s))) return p;
3646         if ((auto p = find(t->right, s))) return p;
3647         return nullptr;
3648     }
3650 If it isn't the `nullptr`, the pointer returned by `find` indicates a `Node` holding `s`.
3651 Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller.
3653 ##### Note
3655 Positions can also be transferred by iterators, indices, and references.
3656 A reference is often a superior alternative to a pointer [if there is no need to use `nullptr`](#Rf-ptr-ref) or [if the object referred to should not change](???).
3658 ##### Note
3660 Do not return a pointer to something that is not in the caller's scope; see [F.43](#Rf-dangle).
3662 **See also**: [discussion of dangling pointer prevention](#???)
3664 ##### Enforcement
3666 * Flag `delete`, `std::free()`, etc. applied to a plain `T*`.
3667 Only owners should be deleted.
3668 * Flag `new`, `malloc()`, etc. assigned to a plain `T*`.
3669 Only owners should be responsible for deletion.
3671 ### <a name="Rf-dangle"></a>F.43: Never (directly or indirectly) return a pointer or a reference to a local object
3673 ##### Reason
3675 To avoid the crashes and data corruption that can result from the use of such a dangling pointer.
3677 ##### Example, bad
3679 After the return from a function its local objects no longer exist:
3681     int* f()
3682     {
3683         int fx = 9;
3684         return &fx;  // BAD
3685     }
3687     void g(int* p)   // looks innocent enough
3688     {
3689         int gx;
3690         cout << "*p == " << *p << '\n';
3691         *p = 999;
3692         cout << "gx == " << gx << '\n';
3693     }
3695     void h()
3696     {
3697         int* p = f();
3698         int z = *p;  // read from abandoned stack frame (bad)
3699         g(p);        // pass pointer to abandoned stack frame to function (bad)
3700     }
3702 Here on one popular implementation I got the output:
3704     *p == 999
3705     gx == 999
3707 I expected that because the call of `g()` reuses the stack space abandoned by the call of `f()` so `*p` refers to the space now occupied by `gx`.
3709 * Imagine what would happen if `fx` and `gx` were of different types.
3710 * Imagine what would happen if `fx` or `gx` was a type with an invariant.
3711 * Imagine what would happen if more that dangling pointer was passed around among a larger set of functions.
3712 * Imagine what a cracker could do with that dangling pointer.
3714 Fortunately, most (all?) modern compilers catch and warn against this simple case.
3716 ##### Note
3718 This applies to references as well:
3720     int& f()
3721     {
3722         int x = 7;
3723         // ...
3724         return x;  // Bad: returns reference to object that is about to be destroyed
3725     }
3727 ##### Note
3729 This applies only to non-`static` local variables.
3730 All `static` variables are (as their name indicates) statically allocated, so that pointers to them cannot dangle.
3732 ##### Example, bad
3734 Not all examples of leaking a pointer to a local variable are that obvious:
3736     int* glob;       // global variables are bad in so many ways
3738     template<class T>
3739     void steal(T x)
3740     {
3741         glob = x();  // BAD
3742     }
3744     void f()
3745     {
3746         int i = 99;
3747         steal([&] { return &i; });
3748     }
3750     int main()
3751     {
3752         f();
3753         cout << *glob << '\n';
3754     }
3756 Here I managed to read the location abandoned by the call of `f`.
3757 The pointer stored in `glob` could be used much later and cause trouble in unpredictable ways.
3759 ##### Note
3761 The address of a local variable can be "returned"/leaked by a return statement, by a `T&` out-parameter, as a member of a returned object, as an element of a returned array, and more.
3763 ##### Note
3765 Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one;
3766 such examples are handled equivalently to leaks of pointers out of a function.
3768 A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to.
3770 **See also**: Another way of getting dangling pointers is [pointer invalidation](#???).
3771 It can be detected/prevented with similar techniques.
3773 ##### Enforcement
3775 * Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals.
3776 * Static analysis can catch many common patterns of the use of pointers indicating positions (thus eliminating dangling pointers)
3778 ### <a name="Rf-return-ref"></a>F.44: Return a `T&` when copy is undesirable and "returning no object" isn't needed
3780 ##### Reason
3782 The language guarantees that a `T&` refers to an object, so that testing for `nullptr` isn't necessary.
3784 **See also**: The return of a reference must not imply transfer of ownership:
3785 [discussion of dangling pointer prevention](#???) and [discussion of ownership](#???).
3787 ##### Example
3789     class Car
3790     {
3791         array<wheel, 4> w;
3792         // ...
3793     public:
3794         wheel& get_wheel(int i) { Expects(i < w.size()); return w[i]; }
3795         // ...
3796     };
3798     void use()
3799     {
3800         Car c;
3801         wheel& w0 = c.get_wheel(0); // w0 has the same lifetime as c
3802     }
3804 ##### Enforcement
3806 Flag functions where no `return` expression could yield `nullptr`
3808 ### <a name="Rf-return-ref-ref"></a>F.45: Don't return a `T&&`
3810 ##### Reason
3812 It's asking to return a reference to a destroyed temporary object.
3813 A `&&` is a magnet for temporary objects.
3815 ##### Example
3817 A returned rvalue reference goes out of scope at the end of the full expression to which it is returned:
3819     auto&& x = max(0, 1);   // OK, so far
3820     foo(x);                 // Undefined behavior
3822 This kind of use is a frequent source of bugs, often incorrectly reported as a compiler bug.
3823 An implementer of a function should avoid setting such traps for users.
3825 The [lifetime safety profile](#SS-lifetime) will (when completely implemented) catch such problems.
3828 ##### Example
3830 Returning an rvalue reference is fine when the reference to the temporary is being passed "downward" to a callee;
3831 then, the temporary is guaranteed to outlive the function call (see [F.18](#Rf-consume) and [F.19](#Rf-forward)).
3832 However, it's not fine when passing such a reference "upward" to a larger caller scope.
3833 For passthrough functions that pass in parameters (by ordinary reference or by perfect forwarding) and want to return values, use simple `auto` return type deduction (not `auto&&`).
3835 Assume that `F` returns by value:
3837     template<class F>
3838     auto&& wrapper(F f)
3839     {
3840         log_call(typeid(f)); // or whatever instrumentation
3841         return f();          // BAD: returns a reference to a temporary
3842     }
3844 Better:
3846     template<class F>
3847     auto wrapper(F f)
3848     {
3849         log_call(typeid(f)); // or whatever instrumentation
3850         return f();          // OK
3851     }
3854 ##### Exception
3856 `std::move` and `std::forward` do return `&&`, but they are just casts -- used by convention only in expression contexts where a reference to a temporary object is passed along within the same expression before the temporary is destroyed. We don't know of any other good examples of returning `&&`.
3858 ##### Enforcement
3860 Flag any use of `&&` as a return type, except in `std::move` and `std::forward`.
3862 ### <a name="Rf-main"></a>F.46: `int` is the return type for `main()`
3864 ##### Reason
3866 It's a language rule, but violated through "language extensions" so often that it is worth mentioning.
3867 Declaring `main` (the one global `main` of a program) `void` limits portability.
3869 ##### Example
3871         void main() { /* ... */ };  // bad, not C++
3873         int main()
3874         {
3875             std::cout << "This is the way to do it\n";
3876         }
3878 ##### Note
3880 We mention this only because of the persistence of this error in the community.
3881 Note that despite its non-void return type, the main function does not require an explicit return statement.
3883 ##### Enforcement
3885 * The compiler should do it
3886 * If the compiler doesn't do it, let tools flag it
3888 ### <a name="Rf-assignment-op"></a>F.47: Return `T&` from assignment operators
3890 ##### Reason
3892 The convention for operator overloads (especially on concrete types) is for
3893 `operator=(const T&)` to perform the assignment and then return (non-`const`)
3894 `*this`.  This ensures consistency with standard-library types and follows the
3895 principle of "do as the ints do."
3897 ##### Note
3899 Historically there was some guidance to make the assignment operator return `const T&`.
3900 This was primarily to avoid code of the form `(a = b) = c` -- such code is not common enough to warrant violating consistency with standard types.
3902 ##### Example
3904     class Foo
3905     {
3906      public:
3907         ...
3908         Foo& operator=(const Foo& rhs)
3909         {
3910           // Copy members.
3911           ...
3912           return *this;
3913         }
3914     };
3916 ##### Enforcement
3918 This should be enforced by tooling by checking the return type (and return
3919 value) of any assignment operator.
3921 ### <a name="Rf-return-move-local"></a>F.48: Don't `return std::move(local)`
3923 ##### Reason
3925 With guaranteed copy elision, it is now almost always a pessimization to expressly use `std::move` in a return statement.
3927 ##### Example, bad
3929     S f()
3930     {
3931       S result;
3932       return std::move(result);
3933     }
3935 ##### Example, good
3937     S f()
3938     {
3939       S result;
3940       return result;
3941     }
3943 ##### Enforcement
3945 This should be enforced by tooling by checking the return expression .
3947 ### <a name="Rf-return-const"></a>F.49: Don't return `const T`
3949 ##### Reason
3951 It is not recommended to return a `const` value.
3952 Such older advice is now obsolete; it does not add value, and it interferes with move semantics.
3954 ##### Example
3956     const vector<int> fct();    // bad: that "const" is more trouble than it is worth
3958     void g(vector<int>& vx)
3959     {
3960         // ...
3961         fct() = vx;   // prevented by the "const"
3962         // ...
3963         vx = fct(); // expensive copy: move semantics suppressed by the "const"
3964         // ...
3965     }
3967 The argument for adding `const` to a return value is that it prevents (very rare) accidental access to a temporary.
3968 The argument against is that it prevents (very frequent) use of move semantics.
3970 **See also**: [F.20, the general item about "out" output values](#Rf-out)
3972 ##### Enforcement
3974 * Flag returning a `const` value. To fix: Remove `const` to return a non-`const` value instead.
3977 ### <a name="Rf-capture-vs-overload"></a>F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)
3979 ##### Reason
3981 Functions can't capture local variables or be defined at local scope; if you need those things, prefer a lambda where possible, and a handwritten function object where not. On the other hand, lambdas and function objects don't overload; if you need to overload, prefer a function (the workarounds to make lambdas overload are ornate). If either will work, prefer writing a function; use the simplest tool necessary.
3983 ##### Example
3985     // writing a function that should only take an int or a string
3986     // -- overloading is natural
3987     void f(int);
3988     void f(const string&);
3990     // writing a function object that needs to capture local state and appear
3991     // at statement or expression scope -- a lambda is natural
3992     vector<work> v = lots_of_work();
3993     for (int tasknum = 0; tasknum < max; ++tasknum) {
3994         pool.run([=, &v] {
3995             /*
3996             ...
3997             ... process 1 / max - th of v, the tasknum - th chunk
3998             ...
3999             */
4000         });
4001     }
4002     pool.join();
4004 ##### Exception
4006 Generic lambdas offer a concise way to write function templates and so can be useful even when a normal function template would do equally well with a little more syntax. This advantage will probably disappear in the future once all functions gain the ability to have Concept parameters.
4008 ##### Enforcement
4010 * Warn on use of a named non-generic lambda (e.g., `auto x = [](int i) { /*...*/; };`) that captures nothing and appears at global scope. Write an ordinary function instead.
4012 ### <a name="Rf-default-args"></a>F.51: Where there is a choice, prefer default arguments over overloading
4014 ##### Reason
4016 Default arguments simply provide alternative interfaces to a single implementation.
4017 There is no guarantee that a set of overloaded functions all implement the same semantics.
4018 The use of default arguments can avoid code replication.
4020 ##### Note
4022 There is a choice between using default argument and overloading when the alternatives are from a set of arguments of the same types.
4023 For example:
4025     void print(const string& s, format f = {});
4027 as opposed to
4029     void print(const string& s);  // use default format
4030     void print(const string& s, format f);
4032 There is not a choice when a set of functions are used to do a semantically equivalent operation to a set of types. For example:
4034     void print(const char&);
4035     void print(int);
4036     void print(zstring);
4038 ##### See also
4041 [Default arguments for virtual functions](#Rh-virtual-default-arg)
4043 ##### Enforcement
4045 * Warn on an overload set where the overloads have a common prefix of parameters (e.g., `f(int)`, `f(int, const string&)`, `f(int, const string&, double)`). (Note: Review this enforcement if it's too noisy in practice.)
4047 ### <a name="Rf-reference-capture"></a>F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms
4049 ##### Reason
4051 For efficiency and correctness, you nearly always want to capture by reference when using the lambda locally. This includes when writing or calling parallel algorithms that are local because they join before returning.
4053 ##### Discussion
4055 The efficiency consideration is that most types are cheaper to pass by reference than by value.
4057 The correctness consideration is that many calls want to perform side effects on the original object at the call site (see example below). Passing by value prevents this.
4059 ##### Note
4061 Unfortunately, there is no simple way to capture by reference to `const` to get the efficiency for a local call but also prevent side effects.
4063 ##### Example
4065 Here, a large object (a network message) is passed to an iterative algorithm, and it is not efficient or correct to copy the message (which might not be copyable):
4067     std::for_each(begin(sockets), end(sockets), [&message](auto& socket)
4068     {
4069         socket.send(message);
4070     });
4072 ##### Example
4074 This is a simple three-stage parallel pipeline. Each `stage` object encapsulates a worker thread and a queue, has a `process` function to enqueue work, and in its destructor automatically blocks waiting for the queue to empty before ending the thread.
4076     void send_packets(buffers& bufs)
4077     {
4078         stage encryptor([](buffer& b) { encrypt(b); });
4079         stage compressor([&](buffer& b) { compress(b); encryptor.process(b); });
4080         stage decorator([&](buffer& b) { decorate(b); compressor.process(b); });
4081         for (auto& b : bufs) { decorator.process(b); }
4082     }  // automatically blocks waiting for pipeline to finish
4084 ##### Enforcement
4086 Flag a lambda that captures by reference, but is used other than locally within the function scope or passed to a function by reference. (Note: This rule is an approximation, but does flag passing by pointer as those are more likely to be stored by the callee, writing to a heap location accessed via a parameter, returning the lambda, etc. The Lifetime rules will also provide general rules that flag escaping pointers and references including via lambdas.)
4088 ### <a name="Rf-value-capture"></a>F.53: Avoid capturing by reference in lambdas that will be used non-locally, including returned, stored on the heap, or passed to another thread
4090 ##### Reason
4092 Pointers and references to locals shouldn't outlive their scope. Lambdas that capture by reference are just another place to store a reference to a local object, and shouldn't do so if they (or a copy) outlive the scope.
4094 ##### Example, bad
4096     int local = 42;
4098     // Want a reference to local.
4099     // Note, that after program exits this scope,
4100     // local no longer exists, therefore
4101     // process() call will have undefined behavior!
4102     thread_pool.queue_work([&] { process(local); });
4104 ##### Example, good
4106     int local = 42;
4107     // Want a copy of local.
4108     // Since a copy of local is made, it will
4109     // always be available for the call.
4110     thread_pool.queue_work([=] { process(local); });
4112 ##### Note
4114 If a non-local pointer must be captured, consider using `unique_ptr`; this handles both lifetime and synchronization.
4116 If the `this` pointer must be captured, consider using `[*this]` capture, which creates a copy of the entire object.
4118 ##### Enforcement
4120 * (Simple) Warn when capture-list contains a reference to a locally declared variable
4121 * (Complex) Flag when capture-list contains a reference to a locally declared variable and the lambda is passed to a non-`const` and non-local context
4123 ### <a name="Rf-this-capture"></a>F.54: When writing a lambda that captures `this` or any class data member, don't use `[=]` default capture
4125 ##### Reason
4127 It's confusing. Writing `[=]` in a member function appears to capture by value, but actually captures data members by reference because it actually captures the invisible `this` pointer by value. If you meant to do that, write `this` explicitly.
4129 ##### Example
4131     class My_class {
4132         int x = 0;
4133         // ...
4135         void f()
4136         {
4137             int i = 0;
4138             // ...
4140             auto lambda = [=] { use(i, x); };   // BAD: "looks like" copy/value capture
4141             // [&] has identical semantics and copies the this pointer under the current rules
4142             // [=,this] and [&,this] are not much better, and confusing
4144             x = 42;
4145             lambda(); // calls use(0, 42);
4146             x = 43;
4147             lambda(); // calls use(0, 43);
4149             // ...
4151             auto lambda2 = [i, this] { use(i, x); }; // ok, most explicit and least confusing
4153             // ...
4154         }
4155     };
4157 ##### Note
4159 If you intend to capture a copy of all class data members, consider C++17 `[*this]`.
4161 ##### Enforcement
4163 * Flag any lambda capture-list that specifies a capture-default of `[=]` and also captures `this` (whether explicitly or via the default capture and a use of `this` in the body)
4165 ### <a name="F-varargs"></a>F.55: Don't use `va_arg` arguments
4167 ##### Reason
4169 Reading from a `va_arg` assumes that the correct type was actually passed.
4170 Passing to varargs assumes the correct type will be read.
4171 This is fragile because it cannot generally be enforced to be safe in the language and so relies on programmer discipline to get it right.
4173 ##### Example
4175     int sum(...)
4176     {
4177         // ...
4178         while (/*...*/)
4179             result += va_arg(list, int); // BAD, assumes it will be passed ints
4180         // ...
4181     }
4183     sum(3, 2); // ok
4184     sum(3.14159, 2.71828); // BAD, undefined
4186     template<class ...Args>
4187     auto sum(Args... args) // GOOD, and much more flexible
4188     {
4189         return (... + args); // note: C++17 "fold expression"
4190     }
4192     sum(3, 2); // ok: 5
4193     sum(3.14159, 2.71828); // ok: ~5.85987
4195 ##### Alternatives
4197 * overloading
4198 * variadic templates
4199 * `variant` arguments
4200 * `initializer_list` (homogeneous)
4202 ##### Note
4204 Declaring a `...` parameter is sometimes useful for techniques that don't involve actual argument passing, notably to declare "take-anything" functions so as to disable "everything else" in an overload set or express a catchall case in a template metaprogram.
4206 ##### Enforcement
4208 * Issue a diagnostic for using `va_list`, `va_start`, or `va_arg`.
4209 * Issue a diagnostic for passing an argument to a vararg parameter of a function that does not offer an overload for a more specific type in the position of the vararg. To fix: Use a different function, or `[[suppress(types)]]`.
4212 ### <a name="F-nesting"></a>F.56: Avoid unnecessary condition nesting
4214 ##### Reason
4216 Shallow nesting of conditions makes the code easier to follow. It also makes the intent clearer.
4217 Strive to place the essential code at outermost scope, unless this obscures intent.
4219 ##### Example
4221 Use a guard-clause to take care of exceptional cases and return early.
4223     // Bad: Deep nesting
4224     void foo() {
4225         ...
4226         if (x) {
4227             computeImportantThings(x);
4228         }
4229     }
4231     // Bad: Still a redundant else.
4232     void foo() {
4233         ...
4234         if (!x) {
4235             return;
4236         }
4237         else {
4238             computeImportantThings(x);
4239         }
4240     }
4242     // Good: Early return, no redundant else
4243     void foo() {
4244         ...
4245         if (!x)
4246             return;
4248         computeImportantThings(x);
4249     }
4251 ##### Example
4253     // Bad: Unnecessary nesting of conditions
4254     void foo() {
4255         ...
4256         if (x) {
4257             if (y) {
4258                 computeImportantThings(x);
4259             }
4260         }
4261     }
4263     // Good: Merge conditions + return early
4264     void foo() {
4265         ...
4266         if (!(x && y))
4267             return;
4269         computeImportantThings(x);
4270     }
4272 ##### Enforcement
4274 Flag a redundant `else`.
4275 Flag a functions whose body is simply a conditional statement enclosing a block.
4278 # <a name="S-class"></a>C: Classes and class hierarchies
4280 A class is a user-defined type, for which a programmer can define the representation, operations, and interfaces.
4281 Class hierarchies are used to organize related classes into hierarchical structures.
4283 Class rule summary:
4285 * [C.1: Organize related data into structures (`struct`s or `class`es)](#Rc-org)
4286 * [C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently](#Rc-struct)
4287 * [C.3: Represent the distinction between an interface and an implementation using a class](#Rc-interface)
4288 * [C.4: Make a function a member only if it needs direct access to the representation of a class](#Rc-member)
4289 * [C.5: Place helper functions in the same namespace as the class they support](#Rc-helper)
4290 * [C.7: Don't define a class or enum and declare a variable of its type in the same statement](#Rc-standalone)
4291 * [C.8: Use `class` rather than `struct` if any member is non-public](#Rc-class)
4292 * [C.9: Minimize exposure of members](#Rc-private)
4294 Subsections:
4296 * [C.concrete: Concrete types](#SS-concrete)
4297 * [C.ctor: Constructors, assignments, and destructors](#S-ctor)
4298 * [C.con: Containers and other resource handles](#SS-containers)
4299 * [C.lambdas: Function objects and lambdas](#SS-lambdas)
4300 * [C.hier: Class hierarchies (OOP)](#SS-hier)
4301 * [C.over: Overloading and overloaded operators](#SS-overload)
4302 * [C.union: Unions](#SS-union)
4304 ### <a name="Rc-org"></a>C.1: Organize related data into structures (`struct`s or `class`es)
4306 ##### Reason
4308 Ease of comprehension.
4309 If data is related (for fundamental reasons), that fact should be reflected in code.
4311 ##### Example
4313     void draw(int x, int y, int x2, int y2);  // BAD: unnecessary implicit relationships
4314     void draw(Point from, Point to);          // better
4316 ##### Note
4318 A simple class without virtual functions implies no space or time overhead.
4320 ##### Note
4322 From a language perspective `class` and `struct` differ only in the default visibility of their members.
4324 ##### Enforcement
4326 Probably impossible. Maybe a heuristic looking for data items used together is possible.
4328 ### <a name="Rc-struct"></a>C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently
4330 ##### Reason
4332 Readability.
4333 Ease of comprehension.
4334 The use of `class` alerts the programmer to the need for an invariant.
4335 This is a useful convention.
4337 ##### Note
4339 An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume.
4340 After the invariant is established (typically by a constructor) every member function can be called for the object.
4341 An invariant can be stated informally (e.g., in a comment) or more formally using `Expects`.
4343 If all data members can vary independently of each other, no invariant is possible.
4345 ##### Example
4347     struct Pair {  // the members can vary independently
4348         string name;
4349         int volume;
4350     };
4352 but:
4354     class Date {
4355     public:
4356         // validate that {yy, mm, dd} is a valid date and initialize
4357         Date(int yy, Month mm, char dd);
4358         // ...
4359     private:
4360         int y;
4361         Month m;
4362         char d;    // day
4363     };
4365 ##### Note
4367 If a class has any `private` data, a user cannot completely initialize an object without the use of a constructor.
4368 Hence, the class definer will provide a constructor and must specify its meaning.
4369 This effectively means the definer need to define an invariant.
4371 **See also**:
4373 * [define a class with private data as `class`](#Rc-class)
4374 * [Prefer to place the interface first in a class](#Rl-order)
4375 * [minimize exposure of members](#Rc-private)
4376 * [Avoid `protected` data](#Rh-protected)
4378 ##### Enforcement
4380 Look for `struct`s with all data private and `class`es with public members.
4382 ### <a name="Rc-interface"></a>C.3: Represent the distinction between an interface and an implementation using a class
4384 ##### Reason
4386 An explicit distinction between interface and implementation improves readability and simplifies maintenance.
4388 ##### Example
4390     class Date {
4391     public:
4392         Date();
4393         // validate that {yy, mm, dd} is a valid date and initialize
4394         Date(int yy, Month mm, char dd);
4396         int day() const;
4397         Month month() const;
4398         // ...
4399     private:
4400         // ... some representation ...
4401     };
4403 For example, we can now change the representation of a `Date` without affecting its users (recompilation is likely, though).
4405 ##### Note
4407 Using a class in this way to represent the distinction between interface and implementation is of course not the only way.
4408 For example, we can use a set of declarations of freestanding functions in a namespace, an abstract base class, or a function template with concepts to represent an interface.
4409 The most important issue is to explicitly distinguish between an interface and its implementation "details."
4410 Ideally, and typically, an interface is far more stable than its implementation(s).
4412 ##### Enforcement
4416 ### <a name="Rc-member"></a>C.4: Make a function a member only if it needs direct access to the representation of a class
4418 ##### Reason
4420 Less coupling than with member functions, fewer functions that can cause trouble by modifying object state, reduces the number of functions that needs to be modified after a change in representation.
4422 ##### Example
4424     class Date {
4425         // ... relatively small interface ...
4426     };
4428     // helper functions:
4429     Date next_weekday(Date);
4430     bool operator==(Date, Date);
4432 The "helper functions" have no need for direct access to the representation of a `Date`.
4434 ##### Note
4436 This rule becomes even better if C++ gets ["uniform function call"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0251r0.pdf).
4438 ##### Exception
4440 The language requires `virtual` functions to be members, and not all `virtual` functions directly access data.
4441 In particular, members of an abstract class rarely do.
4443 Note [multi-methods](https://web.archive.org/web/20200605021759/https://parasol.tamu.edu/~yuriys/papers/OMM10.pdf).
4445 ##### Exception
4447 The language requires operators `=`, `()`, `[]`, and `->` to be members.
4449 ##### Exception
4451 An overload set could have some members that do not directly access `private` data:
4453     class Foobar {
4454     public:
4455         void foo(long x) { /* manipulate private data */ }
4456         void foo(double x) { foo(std::lround(x)); }
4457         // ...
4458     private:
4459         // ...
4460     };
4462 ##### Exception
4464 Similarly, a set of functions could be designed to be used in a chain:
4466     x.scale(0.5).rotate(45).set_color(Color::red);
4468 Typically, some but not all of such functions directly access `private` data.
4470 ##### Enforcement
4472 * Look for non-`virtual` member functions that do not touch data members directly.
4473 The snag is that many member functions that do not need to touch data members directly do.
4474 * Ignore `virtual` functions.
4475 * Ignore functions that are part of an overload set out of which at least one function accesses `private` members.
4476 * Ignore functions returning `this`.
4478 ### <a name="Rc-helper"></a>C.5: Place helper functions in the same namespace as the class they support
4480 ##### Reason
4482 A helper function is a function (usually supplied by the writer of a class) that does not need direct access to the representation of the class, yet is seen as part of the useful interface to the class.
4483 Placing them in the same namespace as the class makes their relationship to the class obvious and allows them to be found by argument dependent lookup.
4485 ##### Example
4487     namespace Chrono { // here we keep time-related services
4489         class Time { /* ... */ };
4490         class Date { /* ... */ };
4492         // helper functions:
4493         bool operator==(Date, Date);
4494         Date next_weekday(Date);
4495         // ...
4496     }
4498 ##### Note
4500 This is especially important for [overloaded operators](#Ro-namespace).
4502 ##### Enforcement
4504 * Flag global functions taking argument types from a single namespace.
4506 ### <a name="Rc-standalone"></a>C.7: Don't define a class or enum and declare a variable of its type in the same statement
4508 ##### Reason
4510 Mixing a type definition and the definition of another entity in the same declaration is confusing and unnecessary.
4512 ##### Example, bad
4514     struct Data { /*...*/ } data{ /*...*/ };
4516 ##### Example, good
4518     struct Data { /*...*/ };
4519     Data data{ /*...*/ };
4521 ##### Enforcement
4523 * Flag if the `}` of a class or enumeration definition is not followed by a `;`. The `;` is missing.
4525 ### <a name="Rc-class"></a>C.8: Use `class` rather than `struct` if any member is non-public
4527 ##### Reason
4529 Readability.
4530 To make it clear that something is being hidden/abstracted.
4531 This is a useful convention.
4533 ##### Example, bad
4535     struct Date {
4536         int d, m;
4538         Date(int i, Month m);
4539         // ... lots of functions ...
4540     private:
4541         int y;  // year
4542     };
4544 There is nothing wrong with this code as far as the C++ language rules are concerned,
4545 but nearly everything is wrong from a design perspective.
4546 The private data is hidden far from the public data.
4547 The data is split in different parts of the class declaration.
4548 Different parts of the data have different access.
4549 All of this decreases readability and complicates maintenance.
4551 ##### Note
4553 Prefer to place the interface first in a class, [see NL.16](#Rl-order).
4555 ##### Enforcement
4557 Flag classes declared with `struct` if there is a `private` or `protected` member.
4559 ### <a name="Rc-private"></a>C.9: Minimize exposure of members
4561 ##### Reason
4563 Encapsulation.
4564 Information hiding.
4565 Minimize the chance of unintended access.
4566 This simplifies maintenance.
4568 ##### Example
4570     template<typename T, typename U>
4571     struct pair {
4572         T a;
4573         U b;
4574         // ...
4575     };
4577 Whatever we do in the `//`-part, an arbitrary user of a `pair` can arbitrarily and independently change its `a` and `b`.
4578 In a large code base, we cannot easily find which code does what to the members of `pair`.
4579 This might be exactly what we want, but if we want to enforce a relation among members, we need to make them `private`
4580 and enforce that relation (invariant) through constructors and member functions.
4581 For example:
4583     class Distance {
4584     public:
4585         // ...
4586         double meters() const { return magnitude*unit; }
4587         void set_unit(double u)
4588         {
4589                 // ... check that u is a factor of 10 ...
4590                 // ... change magnitude appropriately ...
4591                 unit = u;
4592         }
4593         // ...
4594     private:
4595         double magnitude;
4596         double unit;    // 1 is meters, 1000 is kilometers, 0.001 is millimeters, etc.
4597     };
4599 ##### Note
4601 If the set of direct users of a set of variables cannot be easily determined, the type or usage of that set cannot be (easily) changed/improved.
4602 For `public` and `protected` data, that's usually the case.
4604 ##### Example
4606 A class can provide two interfaces to its users.
4607 One for derived classes (`protected`) and one for general users (`public`).
4608 For example, a derived class might be allowed to skip a run-time check because it has already guaranteed correctness:
4610     class Foo {
4611     public:
4612         int bar(int x) { check(x); return do_bar(x); }
4613         // ...
4614     protected:
4615         int do_bar(int x); // do some operation on the data
4616         // ...
4617     private:
4618         // ... data ...
4619     };
4621     class Dir : public Foo {
4622         //...
4623         int mem(int x, int y)
4624         {
4625             /* ... do something ... */
4626             return do_bar(x + y); // OK: derived class can bypass check
4627         }
4628     };
4630     void user(Foo& x)
4631     {
4632         int r1 = x.bar(1);      // OK, will check
4633         int r2 = x.do_bar(2);   // error: would bypass check
4634         // ...
4635     }
4637 ##### Note
4639 [`protected` data is a bad idea](#Rh-protected).
4641 ##### Note
4643 Prefer the order `public` members before `protected` members before `private` members; see [NL.16](#Rl-order).
4645 ##### Enforcement
4647 * [Flag protected data](#Rh-protected).
4648 * Flag mixtures of `public` and `private` data
4650 ## <a name="SS-concrete"></a>C.concrete: Concrete types
4652 Concrete type rule summary:
4654 * [C.10: Prefer concrete types over class hierarchies](#Rc-concrete)
4655 * [C.11: Make concrete types regular](#Rc-regular)
4656 * [C.12: Don't make data members `const` or references in a copyable or movable type](#Rc-constref)
4659 ### <a name="Rc-concrete"></a>C.10: Prefer concrete types over class hierarchies
4661 ##### Reason
4663 A concrete type is fundamentally simpler than a type in a class hierarchy:
4664 easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster.
4665 You need a reason (use cases) for using a hierarchy.
4667 ##### Example
4669     class Point1 {
4670         int x, y;
4671         // ... operations ...
4672         // ... no virtual functions ...
4673     };
4675     class Point2 {
4676         int x, y;
4677         // ... operations, some virtual ...
4678         virtual ~Point2();
4679     };
4681     void use()
4682     {
4683         Point1 p11 {1, 2};   // make an object on the stack
4684         Point1 p12 {p11};    // a copy
4686         auto p21 = make_unique<Point2>(1, 2);   // make an object on the free store
4687         auto p22 = p21->clone();                // make a copy
4688         // ...
4689     }
4691 If a class is part of a hierarchy, we (in real code if not necessarily in small examples) must manipulate its objects through pointers or references.
4692 That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections.
4694 ##### Note
4696 Concrete types can be stack-allocated and be members of other classes.
4698 ##### Note
4700 The use of indirection is fundamental for run-time polymorphic interfaces.
4701 The allocation/deallocation overhead is not (that's just the most common case).
4702 We can use a base class as the interface of a scoped object of a derived class.
4703 This is done where dynamic allocation is prohibited (e.g. hard-real-time) and to provide a stable interface to some kinds of plug-ins.
4706 ##### Enforcement
4711 ### <a name="Rc-regular"></a>C.11: Make concrete types regular
4713 ##### Reason
4715 Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).
4717 The C++ built-in types are regular, and so are standard-library classes such as `string`, `vector`, and `map`. Concrete classes without assignment and equality can be defined, but they are (and should be) rare.
4719 ##### Example
4721     struct Bundle {
4722         string name;
4723         vector<Record> vr;
4724     };
4726     bool operator==(const Bundle& a, const Bundle& b)
4727     {
4728         return a.name == b.name && a.vr == b.vr;
4729     }
4731     Bundle b1 { "my bundle", {r1, r2, r3}};
4732     Bundle b2 = b1;
4733     if (!(b1 == b2)) error("impossible!");
4734     b2.name = "the other bundle";
4735     if (b1 == b2) error("No!");
4737 In particular, if a concrete type is copyable, prefer to also give it an equality comparison operator, and ensure that `a = b` implies `a == b`.
4739 ##### Note
4741 For structs intended to be shared with C code, defining `operator==` may not be feasible.
4743 ##### Note
4745 Handles for resources that cannot be cloned, e.g., a `scoped_lock` for a `mutex`, are concrete types but typically cannot be copied (instead, they can usually be moved),
4746 so they can't be regular; instead, they tend to be move-only.
4748 ##### Enforcement
4753 ### <a name="Rc-constref"></a>C.12: Don't make data members `const` or references in a copyable or movable type
4755 ##### Reason
4757 `const` and reference data members are not useful in a copyable or movable type, and make such types difficult to use by making them at least partly uncopyable/unmovable for subtle reasons.
4759 ##### Example; bad
4761     class bad {
4762         const int i;    // bad
4763         string& s;      // bad
4764         // ...
4765     };
4767 The `const` and `&` data members make this class "only-sort-of-copyable" -- copy-constructible but not copy-assignable.
4769 ##### Note
4771 If you need a member to point to something, use a pointer (raw or smart, and `gsl::not_null` if it should not be null) instead of a reference.
4773 ##### Enforcement
4775 Flag a data member that is `const`, `&`, or `&&` in a type that has any copy or move operation.
4779 ## <a name="S-ctor"></a>C.ctor: Constructors, assignments, and destructors
4781 These functions control the lifecycle of objects: creation, copy, move, and destruction.
4782 Define constructors to guarantee and simplify initialization of classes.
4784 These are *default operations*:
4786 * a default constructor: `X()`
4787 * a copy constructor: `X(const X&)`
4788 * a copy assignment: `operator=(const X&)`
4789 * a move constructor: `X(X&&)`
4790 * a move assignment: `operator=(X&&)`
4791 * a destructor: `~X()`
4793 By default, the compiler defines each of these operations if it is used, but the default can be suppressed.
4795 The default operations are a set of related operations that together implement the lifecycle semantics of an object.
4796 By default, C++ treats classes as value-like types, but not all types are value-like.
4798 Set of default operations rules:
4800 * [C.20: If you can avoid defining any default operations, do](#Rc-zero)
4801 * [C.21: If you define or `=delete` any copy, move, or destructor function, define or `=delete` them all](#Rc-five)
4802 * [C.22: Make default operations consistent](#Rc-matched)
4804 Destructor rules:
4806 * [C.30: Define a destructor if a class needs an explicit action at object destruction](#Rc-dtor)
4807 * [C.31: All resources acquired by a class must be released by the class's destructor](#Rc-dtor-release)
4808 * [C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning](#Rc-dtor-ptr)
4809 * [C.33: If a class has an owning pointer member, define a destructor](#Rc-dtor-ptr2)
4810 * [C.35: A base class destructor should be either public and virtual, or protected and non-virtual](#Rc-dtor-virtual)
4811 * [C.36: A destructor must not fail](#Rc-dtor-fail)
4812 * [C.37: Make destructors `noexcept`](#Rc-dtor-noexcept)
4814 Constructor rules:
4816 * [C.40: Define a constructor if a class has an invariant](#Rc-ctor)
4817 * [C.41: A constructor should create a fully initialized object](#Rc-complete)
4818 * [C.42: If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
4819 * [C.43: Ensure that a copyable class has a default constructor](#Rc-default0)
4820 * [C.44: Prefer default constructors to be simple and non-throwing](#Rc-default00)
4821 * [C.45: Don't define a default constructor that only initializes data members; use member initializers instead](#Rc-default)
4822 * [C.46: By default, declare single-argument constructors `explicit`](#Rc-explicit)
4823 * [C.47: Define and initialize member variables in the order of member declaration](#Rc-order)
4824 * [C.48: Prefer default member initializers to member initializers in constructors for constant initializers](#Rc-in-class-initializer)
4825 * [C.49: Prefer initialization to assignment in constructors](#Rc-initialize)
4826 * [C.50: Use a factory function if you need "virtual behavior" during initialization](#Rc-factory)
4827 * [C.51: Use delegating constructors to represent common actions for all constructors of a class](#Rc-delegating)
4828 * [C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization](#Rc-inheriting)
4830 Copy and move rules:
4832 * [C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`](#Rc-copy-assignment)
4833 * [C.61: A copy operation should copy](#Rc-copy-semantic)
4834 * [C.62: Make copy assignment safe for self-assignment](#Rc-copy-self)
4835 * [C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const&`](#Rc-move-assignment)
4836 * [C.64: A move operation should move and leave its source in a valid state](#Rc-move-semantic)
4837 * [C.65: Make move assignment safe for self-assignment](#Rc-move-self)
4838 * [C.66: Make move operations `noexcept`](#Rc-move-noexcept)
4839 * [C.67: A polymorphic class should suppress public copy/move](#Rc-copy-virtual)
4841 Other default operations rules:
4843 * [C.80: Use `=default` if you have to be explicit about using the default semantics](#Rc-eqdefault)
4844 * [C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)](#Rc-delete)
4845 * [C.82: Don't call virtual functions in constructors and destructors](#Rc-ctor-virtual)
4846 * [C.83: For value-like types, consider providing a `noexcept` swap function](#Rc-swap)
4847 * [C.84: A `swap` must not fail](#Rc-swap-fail)
4848 * [C.85: Make `swap` `noexcept`](#Rc-swap-noexcept)
4849 * [C.86: Make `==` symmetric with respect of operand types and `noexcept`](#Rc-eq)
4850 * [C.87: Beware of `==` on base classes](#Rc-eq-base)
4851 * [C.89: Make a `hash` `noexcept`](#Rc-hash)
4852 * [C.90: Rely on constructors and assignment operators, not memset and memcpy](#Rc-memset)
4854 ## <a name="SS-defop"></a>C.defop: Default Operations
4856 By default, the language supplies the default operations with their default semantics.
4857 However, a programmer can disable or replace these defaults.
4859 ### <a name="Rc-zero"></a>C.20: If you can avoid defining default operations, do
4861 ##### Reason
4863 It's the simplest and gives the cleanest semantics.
4865 ##### Example
4867     struct Named_map {
4868     public:
4869         // ... no default operations declared ...
4870     private:
4871         string name;
4872         map<int, int> rep;
4873     };
4875     Named_map nm;        // default construct
4876     Named_map nm2 {nm};  // copy construct
4878 Since `std::map` and `string` have all the special functions, no further work is needed.
4880 ##### Note
4882 This is known as "the rule of zero".
4884 ##### Enforcement
4886 (Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule.
4887 For example, a class with a (pointer, size) pair of members and a destructor that `delete`s the pointer could probably be converted to a `vector`.
4889 ### <a name="Rc-five"></a>C.21: If you define or `=delete` any copy, move, or destructor function, define or `=delete` them all
4891 ##### Reason
4893 The semantics of copy, move, and destruction are closely related, so if one needs to be declared, the odds are that others need consideration too.
4895 Declaring any copy/move/destructor function,
4896 even as `=default` or `=delete`, will suppress the implicit declaration
4897 of a move constructor and move assignment operator.
4898 Declaring a move constructor or move assignment operator, even as
4899 `=default` or `=delete`, will cause an implicitly generated copy constructor
4900 or implicitly generated copy assignment operator to be defined as deleted.
4901 So as soon as any of these are declared, the others should
4902 all be declared to avoid unwanted effects like turning all potential moves
4903 into more expensive copies, or making a class move-only.
4905 ##### Example, bad
4907     struct M2 {   // bad: incomplete set of copy/move/destructor operations
4908     public:
4909         // ...
4910         // ... no copy or move operations ...
4911         ~M2() { delete[] rep; }
4912     private:
4913         pair<int, int>* rep;  // zero-terminated set of pairs
4914     };
4916     void use()
4917     {
4918         M2 x;
4919         M2 y;
4920         // ...
4921         x = y;   // the default assignment
4922         // ...
4923     }
4925 Given that "special attention" was needed for the destructor (here, to deallocate), the likelihood that the implicitly-defined copy and move assignment operators will be correct is low (here, we would get double deletion).
4927 ##### Note
4929 This is known as "the rule of five."
4931 ##### Note
4933 If you want a default implementation (while defining another), write `=default` to show you're doing so intentionally for that function.
4934 If you don't want a generated default function, suppress it with `=delete`.
4936 ##### Example, good
4938 When a destructor needs to be declared just to make it `virtual`, it can be
4939 defined as defaulted.
4941     class AbstractBase {
4942     public:
4943         virtual void foo() = 0;  // at least one abstract method to make the class abstract
4944         virtual ~AbstractBase() = default;
4945         // ...
4946     };
4948 To prevent slicing as per [C.67](#Rc-copy-virtual),
4949 make the copy and move operations protected or `=delete`d, and add a `clone`:
4951     class CloneableBase {
4952     public:
4953         virtual unique_ptr<CloneableBase> clone() const;
4954         virtual ~CloneableBase() = default;
4955         CloneableBase() = default;
4956         CloneableBase(const CloneableBase&) = delete;
4957         CloneableBase& operator=(const CloneableBase&) = delete;
4958         CloneableBase(CloneableBase&&) = delete;
4959         CloneableBase& operator=(CloneableBase&&) = delete;
4960         // ... other constructors and functions ...
4961     };
4963 Defining only the move operations or only the copy operations would have the
4964 same effect here, but stating the intent explicitly for each special member
4965 makes it more obvious to the reader.
4967 ##### Note
4969 Compilers enforce much of this rule and ideally warn about any violation.
4971 ##### Note
4973 Relying on an implicitly generated copy operation in a class with a destructor is deprecated.
4975 ##### Note
4977 Writing these functions can be error-prone.
4978 Note their argument types:
4980     class X {
4981     public:
4982         // ...
4983         virtual ~X() = default;               // destructor (virtual if X is meant to be a base class)
4984         X(const X&) = default;                // copy constructor
4985         X& operator=(const X&) = default;     // copy assignment
4986         X(X&&) noexcept = default;            // move constructor
4987         X& operator=(X&&) noexcept = default; // move assignment
4988     };
4990 A minor mistake (such as a misspelling, leaving out a `const`, using `&` instead of `&&`, or leaving out a special function) can lead to errors or warnings.
4991 To avoid the tedium and the possibility of errors, try to follow the [rule of zero](#Rc-zero).
4993 ##### Enforcement
4995 (Simple) A class should have a declaration (even a `=delete` one) for either all or none of the copy/move/destructor functions.
4997 ### <a name="Rc-matched"></a>C.22: Make default operations consistent
4999 ##### Reason
5001 The default operations are conceptually a matched set. Their semantics are interrelated.
5002 Users will be surprised if copy/move construction and copy/move assignment do logically different things. Users will be surprised if constructors and destructors do not provide a consistent view of resource management. Users will be surprised if copy and move don't reflect the way constructors and destructors work.
5004 ##### Example, bad
5006     class Silly {   // BAD: Inconsistent copy operations
5007         class Impl {
5008             // ...
5009         };
5010         shared_ptr<Impl> p;
5011     public:
5012         Silly(const Silly& a) : p(make_shared<Impl>()) { *p = *a.p; }   // deep copy
5013         Silly& operator=(const Silly& a) { p = a.p; return *this; }   // shallow copy
5014         // ...
5015     };
5017 These operations disagree about copy semantics. This will lead to confusion and bugs.
5019 ##### Enforcement
5021 * (Complex) A copy/move constructor and the corresponding copy/move assignment operator should write to the same member variables at the same level of dereference.
5022 * (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors.
5023 * (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable.
5024 * (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators.
5026 ## <a name="SS-dtor"></a>C.dtor: Destructors
5028 "Does this class need a destructor?" is a surprisingly insightful design question.
5029 For most classes the answer is "no" either because the class holds no resources or because destruction is handled by [the rule of zero](#Rc-zero);
5030 that is, its members can take care of themselves as concerns destruction.
5031 If the answer is "yes", much of the design of the class follows (see [the rule of five](#Rc-five)).
5033 ### <a name="Rc-dtor"></a>C.30: Define a destructor if a class needs an explicit action at object destruction
5035 ##### Reason
5037 A destructor is implicitly invoked at the end of an object's lifetime.
5038 If the default destructor is sufficient, use it.
5039 Only define a non-default destructor if a class needs to execute code that is not already part of its members' destructors.
5041 ##### Example
5043     template<typename A>
5044     struct final_action {   // slightly simplified
5045         A act;
5046         final_action(A a) : act{a} {}
5047         ~final_action() { act(); }
5048     };
5050     template<typename A>
5051     final_action<A> finally(A act)   // deduce action type
5052     {
5053         return final_action<A>{act};
5054     }
5056     void test()
5057     {
5058         auto act = finally([] { cout << "Exit test\n"; });  // establish exit action
5059         // ...
5060         if (something) return;   // act done here
5061         // ...
5062     } // act done here
5064 The whole purpose of `final_action` is to get a piece of code (usually a lambda) executed upon destruction.
5066 ##### Note
5068 There are two general categories of classes that need a user-defined destructor:
5070 * A class with a resource that is not already represented as a class with a destructor, e.g., a `vector` or a transaction class.
5071 * A class that exists primarily to execute an action upon destruction, such as a tracer or `final_action`.
5073 ##### Example, bad
5075     class Foo {   // bad; use the default destructor
5076     public:
5077         // ...
5078         ~Foo() { s = ""; i = 0; vi.clear(); }  // clean up
5079     private:
5080         string s;
5081         int i;
5082         vector<int> vi;
5083     };
5085 The default destructor does it better, more efficiently, and can't get it wrong.
5087 ##### Note
5089 If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use `=default`.
5091 ##### Enforcement
5093 Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors.
5095 ### <a name="Rc-dtor-release"></a>C.31: All resources acquired by a class must be released by the class's destructor
5097 ##### Reason
5099 Prevention of resource leaks, especially in error cases.
5101 ##### Note
5103 For resources represented as classes with a complete set of default operations, this happens automatically.
5105 ##### Example
5107     class X {
5108         ifstream f;   // might own a file
5109         // ... no default operations defined or =deleted ...
5110     };
5112 `X`'s `ifstream` implicitly closes any file it might have open upon destruction of its `X`.
5114 ##### Example, bad
5116     class X2 {     // bad
5117         FILE* f;   // might own a file
5118         // ... no default operations defined or =deleted ...
5119     };
5121 `X2` might leak a file handle.
5123 ##### Note
5125 What about a socket that won't close? A destructor, close, or cleanup operation [should never fail](#Rc-dtor-fail).
5126 If it does nevertheless, we have a problem that has no really good solution.
5127 For starters, the writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
5128 See [discussion](#Sd-never-fail).
5129 To make the problem worse, many "close/release" operations are not retryable.
5130 Many have tried to solve this problem, but no general solution is known.
5131 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
5133 ##### Note
5135 A class can hold pointers and references to objects that it does not own.
5136 Obviously, such objects should not be `delete`d by the class's destructor.
5137 For example:
5139     Preprocessor pp { /* ... */ };
5140     Parser p { pp, /* ... */ };
5141     Type_checker tc { p, /* ... */ };
5143 Here `p` refers to `pp` but does not own it.
5145 ##### Enforcement
5147 * (Simple) If a class has pointer or reference member variables that are owners
5148   (e.g., deemed owners by using `gsl::owner`), then they should be referenced in its destructor.
5149 * (Hard) Determine if pointer or reference member variables are owners when there is no explicit statement of ownership
5150   (e.g., look into the constructors).
5152 ### <a name="Rc-dtor-ptr"></a>C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning
5154 ##### Reason
5156 There is a lot of code that is non-specific about ownership.
5158 ##### Example
5160     class legacy_class
5161     {
5162         foo* m_owning;   // Bad: change to unique_ptr<T> or owner<T*>
5163         bar* m_observer; // OK: keep
5164     }
5166 The only way to determine ownership may be code analysis.
5168 ##### Note
5170 Ownership should be clear in new code (and refactored legacy code) according to [R.20](#Rr-owner) for owning
5171 pointers and [R.3](#Rr-ptr) for non-owning pointers.  References should never own [R.4](#Rr-ref).
5173 ##### Enforcement
5175 Look at the initialization of raw member pointers and member references and see if an allocation is used.
5177 ### <a name="Rc-dtor-ptr2"></a>C.33: If a class has an owning pointer member, define a destructor
5179 ##### Reason
5181 An owned object must be `deleted` upon destruction of the object that owns it.
5183 ##### Example
5185 A pointer member could represent a resource.
5186 [A `T*` should not do so](#Rr-ptr), but in older code, that's common.
5187 Consider a `T*` a possible owner and therefore suspect.
5189     template<typename T>
5190     class Smart_ptr {
5191         T* p;   // BAD: vague about ownership of *p
5192         // ...
5193     public:
5194         // ... no user-defined default operations ...
5195     };
5197     void use(Smart_ptr<int> p1)
5198     {
5199         // error: p2.p leaked (if not nullptr and not owned by some other code)
5200         auto p2 = p1;
5201     }
5203 Note that if you define a destructor, you must define or delete [all default operations](#Rc-five):
5205     template<typename T>
5206     class Smart_ptr2 {
5207         T* p;   // BAD: vague about ownership of *p
5208         // ...
5209     public:
5210         // ... no user-defined copy operations ...
5211         ~Smart_ptr2() { delete p; }  // p is an owner!
5212     };
5214     void use(Smart_ptr2<int> p1)
5215     {
5216         auto p2 = p1;   // error: double deletion
5217     }
5219 The default copy operation will just copy the `p1.p` into `p2.p` leading to a double destruction of `p1.p`. Be explicit about ownership:
5221     template<typename T>
5222     class Smart_ptr3 {
5223         owner<T*> p;   // OK: explicit about ownership of *p
5224         // ...
5225     public:
5226         // ...
5227         // ... copy and move operations ...
5228         ~Smart_ptr3() { delete p; }
5229     };
5231     void use(Smart_ptr3<int> p1)
5232     {
5233         auto p2 = p1;   // OK: no double deletion
5234     }
5236 ##### Note
5238 Often the simplest way to get a destructor is to replace the pointer with a smart pointer (e.g., `std::unique_ptr`) and let the compiler arrange for proper destruction to be done implicitly.
5240 ##### Note
5242 Why not just require all owning pointers to be "smart pointers"?
5243 That would sometimes require non-trivial code changes and might affect ABIs.
5245 ##### Enforcement
5247 * A class with a pointer data member is suspect.
5248 * A class with an `owner<T>` should define its default operations.
5251 ### <a name="Rc-dtor-virtual"></a>C.35: A base class destructor should be either public and virtual, or protected and non-virtual
5253 ##### Reason
5255 To prevent undefined behavior.
5256 If the destructor is public, then calling code can attempt to destroy a derived class object through a base class pointer, and the result is undefined if the base class's destructor is non-virtual.
5257 If the destructor is protected, then calling code cannot destroy through a base class pointer and the destructor does not need to be virtual; it does need to be protected, not private, so that derived destructors can invoke it.
5258 In general, the writer of a base class does not know the appropriate action to be done upon destruction.
5260 ##### Discussion
5262 See [this in the Discussion section](#Sd-dtor).
5264 ##### Example, bad
5266     struct Base {  // BAD: implicitly has a public non-virtual destructor
5267         virtual void f();
5268     };
5270     struct D : Base {
5271         string s {"a resource needing cleanup"};
5272         ~D() { /* ... do some cleanup ... */ }
5273         // ...
5274     };
5276     void use()
5277     {
5278         unique_ptr<Base> p = make_unique<D>();
5279         // ...
5280     } // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more
5282 ##### Note
5284 A virtual function defines an interface to derived classes that can be used without looking at the derived classes.
5285 If the interface allows destroying, it should be safe to do so.
5287 ##### Note
5289 A destructor must be non-private or it will prevent using the type:
5291     class X {
5292         ~X();   // private destructor
5293         // ...
5294     };
5296     void use()
5297     {
5298         X a;                        // error: cannot destroy
5299         auto p = make_unique<X>();  // error: cannot destroy
5300     }
5302 ##### Exception
5304 We can imagine one case where you could want a protected virtual destructor: When an object of a derived type (and only of such a type) should be allowed to destroy *another* object (not itself) through a pointer to base. We haven't seen such a case in practice, though.
5307 ##### Enforcement
5309 * A class with any virtual functions should have a destructor that is either public and virtual or else protected and non-virtual.
5310 * If a class inherits publicly from a base class, the base class should have a destructor that is either public and virtual or else protected and non-virtual.
5312 ### <a name="Rc-dtor-fail"></a>C.36: A destructor must not fail
5314 ##### Reason
5316 In general we do not know how to write error-free code if a destructor should fail.
5317 The standard library requires that all classes it deals with have destructors that do not exit by throwing.
5319 ##### Example
5321     class X {
5322     public:
5323         ~X() noexcept;
5324         // ...
5325     };
5327     X::~X() noexcept
5328     {
5329         // ...
5330         if (cannot_release_a_resource) terminate();
5331         // ...
5332     }
5334 ##### Note
5336 Many have tried to devise a fool-proof scheme for dealing with failure in destructors.
5337 None have succeeded to come up with a general scheme.
5338 This can be a real practical problem: For example, what about a socket that won't close?
5339 The writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
5340 See [discussion](#Sd-never-fail).
5341 To make the problem worse, many "close/release" operations are not retryable.
5342 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
5344 ##### Note
5346 Declare a destructor `noexcept`. That will ensure that it either completes normally or terminates the program.
5348 ##### Note
5350 If a resource cannot be released and the program must not fail, try to signal the failure to the rest of the system somehow
5351 (maybe even by modifying some global state and hope something will notice and be able to take care of the problem).
5352 Be fully aware that this technique is special-purpose and error-prone.
5353 Consider the "my connection will not close" example.
5354 Probably there is a problem at the other end of the connection and only a piece of code responsible for both ends of the connection can properly handle the problem.
5355 The destructor could send a message (somehow) to the responsible part of the system, consider that to have closed the connection, and return normally.
5357 ##### Note
5359 If a destructor uses operations that could fail, it can catch exceptions and in some cases still complete successfully
5360 (e.g., by using a different clean-up mechanism from the one that threw an exception).
5362 ##### Enforcement
5364 (Simple) A destructor should be declared `noexcept` if it could throw.
5366 ### <a name="Rc-dtor-noexcept"></a>C.37: Make destructors `noexcept`
5368 ##### Reason
5370  [A destructor must not fail](#Rc-dtor-fail). If a destructor tries to exit with an exception, it's a bad design error and the program had better terminate.
5372 ##### Note
5374 A destructor (either user-defined or compiler-generated) is implicitly declared `noexcept` (independently of what code is in its body) if all of the members of its class have `noexcept` destructors. By explicitly marking destructors `noexcept`, an author guards against the destructor becoming implicitly `noexcept(false)` through the addition or modification of a class member.
5376 ##### Example
5378 Not all destructors are noexcept by default; one throwing member poisons the whole class hierarchy
5380     struct X {
5381         Details x;  // happens to have a throwing destructor
5382         // ...
5383         ~X() { }    // implicitly noexcept(false); aka can throw
5384     };
5386 So, if in doubt, declare a destructor noexcept.
5388 ##### Note
5390 Why not then declare all destructors noexcept?
5391 Because that would in many cases -- especially simple cases -- be distracting clutter.
5393 ##### Enforcement
5395 (Simple) A destructor should be declared `noexcept` if it could throw.
5397 ## <a name="SS-ctor"></a>C.ctor: Constructors
5399 A constructor defines how an object is initialized (constructed).
5401 ### <a name="Rc-ctor"></a>C.40: Define a constructor if a class has an invariant
5403 ##### Reason
5405 That's what constructors are for.
5407 ##### Example
5409     class Date {  // a Date represents a valid date
5410                   // in the January 1, 1900 to December 31, 2100 range
5411         Date(int dd, int mm, int yy)
5412             :d{dd}, m{mm}, y{yy}
5413         {
5414             if (!is_valid(d, m, y)) throw Bad_date{};  // enforce invariant
5415         }
5416         // ...
5417     private:
5418         int d, m, y;
5419     };
5421 It is often a good idea to express the invariant as an `Ensures` on the constructor.
5423 ##### Note
5425 A constructor can be used for convenience even if a class does not have an invariant. For example:
5427     struct Rec {
5428         string s;
5429         int i {0};
5430         Rec(const string& ss) : s{ss} {}
5431         Rec(int ii) :i{ii} {}
5432     };
5434     Rec r1 {7};
5435     Rec r2 {"Foo bar"};
5437 ##### Note
5439 The C++11 initializer list rule eliminates the need for many constructors. For example:
5441     struct Rec2{
5442         string s;
5443         int i;
5444         Rec2(const string& ss, int ii = 0) :s{ss}, i{ii} {}   // redundant
5445     };
5447     Rec2 r1 {"Foo", 7};
5448     Rec2 r2 {"Bar"};
5450 The `Rec2` constructor is redundant.
5451 Also, the default for `int` would be better done as a [default member initializer](#Rc-in-class-initializer).
5453 **See also**: [construct valid object](#Rc-complete) and [constructor throws](#Rc-throw).
5455 ##### Enforcement
5457 * Flag classes with user-defined copy operations but no constructor (a user-defined copy is a good indicator that the class has an invariant)
5459 ### <a name="Rc-complete"></a>C.41: A constructor should create a fully initialized object
5461 ##### Reason
5463 A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
5465 ##### Example, bad
5467     class X1 {
5468         FILE* f;   // call init() before any other function
5469         // ...
5470     public:
5471         X1() {}
5472         void init();   // initialize f
5473         void read();   // read from f
5474         // ...
5475     };
5477     void f()
5478     {
5479         X1 file;
5480         file.read();   // crash or bad read!
5481         // ...
5482         file.init();   // too late
5483         // ...
5484     }
5486 Compilers do not read comments.
5488 ##### Exception
5490 If a valid object cannot conveniently be constructed by a constructor, [use a factory function](#Rc-factory).
5492 ##### Enforcement
5494 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
5495 * (Unknown) If a constructor has an `Ensures` contract, try to see if it holds as a postcondition.
5497 ##### Note
5499 If a constructor acquires a resource (to create a valid object), that resource should be [released by the destructor](#Rc-dtor-release).
5500 The idiom of having constructors acquire resources and destructors release them is called [RAII](#Rr-raii) ("Resource Acquisition Is Initialization").
5502 ### <a name="Rc-throw"></a>C.42: If a constructor cannot construct a valid object, throw an exception
5504 ##### Reason
5506 Leaving behind an invalid object is asking for trouble.
5508 ##### Example
5510     class X2 {
5511         FILE* f;
5512         // ...
5513     public:
5514         X2(const string& name)
5515             :f{fopen(name.c_str(), "r")}
5516         {
5517             if (!f) throw runtime_error{"could not open" + name};
5518             // ...
5519         }
5521         void read();      // read from f
5522         // ...
5523     };
5525     void f()
5526     {
5527         X2 file {"Zeno"}; // throws if file isn't open
5528         file.read();      // fine
5529         // ...
5530     }
5532 ##### Example, bad
5534     class X3 {     // bad: the constructor leaves a non-valid object behind
5535         FILE* f;   // call is_valid() before any other function
5536         bool valid;
5537         // ...
5538     public:
5539         X3(const string& name)
5540             :f{fopen(name.c_str(), "r")}, valid{false}
5541         {
5542             if (f) valid = true;
5543             // ...
5544         }
5546         bool is_valid() { return valid; }
5547         void read();   // read from f
5548         // ...
5549     };
5551     void f()
5552     {
5553         X3 file {"Heraclides"};
5554         file.read();   // crash or bad read!
5555         // ...
5556         if (file.is_valid()) {
5557             file.read();
5558             // ...
5559         }
5560         else {
5561             // ... handle error ...
5562         }
5563         // ...
5564     }
5566 ##### Note
5568 For a variable definition (e.g., on the stack or as a member of another object) there is no explicit function call from which an error code could be returned.
5569 Leaving behind an invalid object and relying on users to consistently check an `is_valid()` function before use is tedious, error-prone, and inefficient.
5571 ##### Exception
5573 There are domains, such as some hard-real-time systems (think airplane controls) where (without additional tool support) exception handling is not sufficiently predictable from a timing perspective.
5574 There the `is_valid()` technique must be used. In such cases, check `is_valid()` consistently and immediately to simulate [RAII](#Rr-raii).
5576 ##### Alternative
5578 If you feel tempted to use some "post-constructor initialization" or "two-stage initialization" idiom, try not to do that.
5579 If you really have to, look at [factory functions](#Rc-factory).
5581 ##### Note
5583 One reason people have used `init()` functions rather than doing the initialization work in a constructor has been to avoid code replication.
5584 [Delegating constructors](#Rc-delegating) and [default member initialization](#Rc-in-class-initializer) do that better.
5585 Another reason has been to delay initialization until an object is needed; the solution to that is often [not to declare a variable until it can be properly initialized](#Res-init)
5587 ##### Enforcement
5591 ### <a name="Rc-default0"></a>C.43: Ensure that a copyable class has a default constructor
5593 ##### Reason
5595 That is, ensure that if a concrete class is copyable it also satisfies the rest of "semiregular."
5597 Many language and library facilities rely on default constructors to initialize their elements, e.g. `T a[10]` and `std::vector<T> v(10)`.
5598 A default constructor often simplifies the task of defining a suitable [moved-from state](#???) for a type that is also copyable.
5600 ##### Example
5602     class Date { // BAD: no default constructor
5603     public:
5604         Date(int dd, int mm, int yyyy);
5605         // ...
5606     };
5608     vector<Date> vd1(1000);   // default Date needed here
5609     vector<Date> vd2(1000, Date{7, Month::October, 1885});   // alternative
5611 The default constructor is only auto-generated if there is no user-declared constructor, hence it's impossible to initialize the vector `vd1` in the example above.
5612 The absence of a default value can cause surprises for users and complicate its use, so if one can be reasonably defined, it should be.
5614 `Date` is chosen to encourage thought:
5615 There is no "natural" default date (the big bang is too far back in time to be useful for most people), so this example is non-trivial.
5616 `{0, 0, 0}` is not a valid date in most calendar systems, so choosing that would be introducing something like floating-point's `NaN`.
5617 However, most realistic `Date` classes have a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial.
5619     class Date {
5620     public:
5621         Date(int dd, int mm, int yyyy);
5622         Date() = default; // [See also](#Rc-default)
5623         // ...
5624     private:
5625         int dd {1};
5626         int mm {1};
5627         int yyyy {1970};
5628         // ...
5629     };
5631     vector<Date> vd1(1000);
5633 ##### Note
5635 A class with members that all have default constructors implicitly gets a default constructor:
5637     struct X {
5638         string s;
5639         vector<int> v;
5640     };
5642     X x; // means X{{}, {}}; that is the empty string and the empty vector
5644 Beware that built-in types are not properly default constructed:
5646     struct X {
5647         string s;
5648         int i;
5649     };
5651     void f()
5652     {
5653         X x;    // x.s is initialized to the empty string; x.i is uninitialized
5655         cout << x.s << ' ' << x.i << '\n';
5656         ++x.i;
5657     }
5659 Statically allocated objects of built-in types are by default initialized to `0`, but local built-in variables are not.
5660 Beware that your compiler might default initialize local built-in variables, whereas an optimized build will not.
5661 Thus, code like the example above might appear to work, but it relies on undefined behavior.
5662 Assuming that you want initialization, an explicit default initialization can help:
5664     struct X {
5665         string s;
5666         int i {};   // default initialize (to 0)
5667     };
5669 ##### Notes
5671 Classes that don't have a reasonable default construction are usually not copyable either, so they don't fall under this guideline.
5673 For example, a base class should not be copyable, and so does not necessarily need a default constructor:
5675     // Shape is an abstract base class, not a copyable type.
5676     // It might or might not need a default constructor.
5677     struct Shape {
5678         virtual void draw() = 0;
5679         virtual void rotate(int) = 0;
5680         // =delete copy/move functions
5681         // ...
5682     };
5684 A class that must acquire a caller-provided resource during construction often cannot have a default constructor, but it does not fall under this guideline because such a class is usually not copyable anyway:
5686     // std::lock_guard is not a copyable type.
5687     // It does not have a default constructor.
5688     lock_guard g {mx};  // guard the mutex mx
5689     lock_guard g2;      // error: guarding nothing
5691 A class that has a "special state" that must be handled separately from other states by member functions or users causes extra work
5692 (and most likely more errors). Such a type can naturally use the special state as a default constructed value, whether or not it is copyable:
5694     // std::ofstream is not a copyable type.
5695     // It does happen to have a default constructor
5696     // that goes along with a special "not open" state.
5697     ofstream out {"Foobar"};
5698     // ...
5699     out << log(time, transaction);
5701 Similar special-state types that are copyable, such as copyable smart pointers that have the special state "==nullptr", should use the special state as their default constructed value.
5703 However, it is preferable to have a default constructor default to a meaningful state such as `std::string`s `""` and `std::vector`s `{}`.
5705 ##### Enforcement
5707 * Flag classes that are copyable by `=` without a default constructor
5708 * Flag classes that are comparable with `==` but not copyable
5711 ### <a name="Rc-default00"></a>C.44: Prefer default constructors to be simple and non-throwing
5713 ##### Reason
5715 Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.
5717 ##### Example, problematic
5719     template<typename T>
5720     // elem points to space-elem element allocated using new
5721     class Vector0 {
5722     public:
5723         Vector0() :Vector0{0} {}
5724         Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
5725         // ...
5726     private:
5727         own<T*> elem;
5728         T* space;
5729         T* last;
5730     };
5732 This is nice and general, but setting a `Vector0` to empty after an error involves an allocation, which might fail.
5733 Also, having a default `Vector` represented as `{new T[0], 0, 0}` seems wasteful.
5734 For example, `Vector0<int> v[100]` costs 100 allocations.
5736 ##### Example
5738     template<typename T>
5739     // elem is nullptr or elem points to space-elem element allocated using new
5740     class Vector1 {
5741     public:
5742         // sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
5743         Vector1() noexcept {}
5744         Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
5745         // ...
5746     private:
5747         own<T*> elem {};
5748         T* space {};
5749         T* last {};
5750     };
5752 Using `{nullptr, nullptr, nullptr}` makes `Vector1{}` cheap, but a special case and implies run-time checks.
5753 Setting a `Vector1` to empty after detecting an error is trivial.
5755 ##### Enforcement
5757 * Flag throwing default constructors
5759 ### <a name="Rc-default"></a>C.45: Don't define a default constructor that only initializes data members; use default member initializers instead
5761 ##### Reason
5763 Using default member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
5765 ##### Example, bad
5767     class X1 { // BAD: doesn't use member initializers
5768         string s;
5769         int i;
5770     public:
5771         X1() :s{"default"}, i{1} { }
5772         // ...
5773     };
5775 ##### Example
5777     class X2 {
5778         string s {"default"};
5779         int i {1};
5780     public:
5781         // use compiler-generated default constructor
5782         // ...
5783     };
5785 ##### Enforcement
5787 (Simple) A default constructor should do more than just initialize member variables with constants.
5789 ### <a name="Rc-explicit"></a>C.46: By default, declare single-argument constructors explicit
5791 ##### Reason
5793 To avoid unintended conversions.
5795 ##### Example, bad
5797     class String {
5798     public:
5799         String(int);   // BAD
5800         // ...
5801     };
5803     String s = 10;   // surprise: string of size 10
5805 ##### Exception
5807 If you really want an implicit conversion from the constructor argument type to the class type, don't use `explicit`:
5809     class Complex {
5810     public:
5811         Complex(double d);   // OK: we want a conversion from d to {d, 0}
5812         // ...
5813     };
5815     Complex z = 10.7;   // unsurprising conversion
5817 **See also**: [Discussion of implicit conversions](#Ro-conversion)
5819 ##### Note
5821 Copy and move constructors should not be made `explicit` because they do not perform conversions. Explicit copy/move constructors make passing and returning by value difficult.
5823 ##### Enforcement
5825 (Simple) Single-argument constructors should be declared `explicit`. Good single argument non-`explicit` constructors are rare in most code bases. Warn for all that are not on a "positive list".
5827 ### <a name="Rc-order"></a>C.47: Define and initialize member variables in the order of member declaration
5829 ##### Reason
5831 To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).
5833 ##### Example, bad
5835     class Foo {
5836         int m1;
5837         int m2;
5838     public:
5839         Foo(int x) :m2{x}, m1{++x} { }   // BAD: misleading initializer order
5840         // ...
5841     };
5843     Foo x(1); // surprise: x.m1 == x.m2 == 2
5845 ##### Enforcement
5847 (Simple) A member initializer list should mention the members in the same order they are declared.
5849 **See also**: [Discussion](#Sd-order)
5851 ### <a name="Rc-in-class-initializer"></a>C.48: Prefer default member initializers to member initializers in constructors for constant initializers
5853 ##### Reason
5855 Makes it explicit that the same value is expected to be used in all constructors. Avoids repetition. Avoids maintenance problems. It leads to the shortest and most efficient code.
5857 ##### Example, bad
5859     class X {   // BAD
5860         int i;
5861         string s;
5862         int j;
5863     public:
5864         X() :i{666}, s{"qqq"} { }   // j is uninitialized
5865         X(int ii) :i{ii} {}         // s is "" and j is uninitialized
5866         // ...
5867     };
5869 How would a maintainer know whether `j` was deliberately uninitialized (probably a bad idea anyway) and whether it was intentional to give `s` the default value `""` in one case and `qqq` in another (almost certainly a bug)? The problem with `j` (forgetting to initialize a member) often happens when a new member is added to an existing class.
5871 ##### Example
5873     class X2 {
5874         int i {666};
5875         string s {"qqq"};
5876         int j {0};
5877     public:
5878         X2() = default;        // all members are initialized to their defaults
5879         X2(int ii) :i{ii} {}   // s and j initialized to their defaults
5880         // ...
5881     };
5883 **Alternative**: We can get part of the benefits from default arguments to constructors, and that is not uncommon in older code. However, that is less explicit, causes more arguments to be passed, and is repetitive when there is more than one constructor:
5885     class X3 {   // BAD: inexplicit, argument passing overhead
5886         int i;
5887         string s;
5888         int j;
5889     public:
5890         X3(int ii = 666, const string& ss = "qqq", int jj = 0)
5891             :i{ii}, s{ss}, j{jj} { }   // all members are initialized to their defaults
5892         // ...
5893     };
5895 ##### Enforcement
5897 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
5898 * (Simple) Default arguments to constructors suggest a default member initializer might be more appropriate.
5900 ### <a name="Rc-initialize"></a>C.49: Prefer initialization to assignment in constructors
5902 ##### Reason
5904 An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.
5906 ##### Example, good
5908     class A {   // Good
5909         string s1;
5910     public:
5911         A(czstring p) : s1{p} { }    // GOOD: directly construct (and the C-string is explicitly named)
5912         // ...
5913     };
5915 ##### Example, bad
5917     class B {   // BAD
5918         string s1;
5919     public:
5920         B(const char* p) { s1 = p; }   // BAD: default constructor followed by assignment
5921         // ...
5922     };
5924     class C {   // UGLY, aka very bad
5925         int* p;
5926     public:
5927         C() { cout << *p; p = new int{10}; }   // accidental use before initialized
5928         // ...
5929     };
5931 ##### Example, better still
5933 Instead of those `const char*`s we could use C++17 `std::string_view` or `gsl::span<char>`
5934 as [a more general way to present arguments to a function](#Rstr-view):
5936     class D {   // Good
5937         string s1;
5938     public:
5939         D(string_view v) : s1{v} { }    // GOOD: directly construct
5940         // ...
5941     };
5943 ### <a name="Rc-factory"></a>C.50: Use a factory function if you need "virtual behavior" during initialization
5945 ##### Reason
5947 If the state of a base class object must depend on the state of a derived part of the object, we need to use a virtual function (or equivalent) while minimizing the window of opportunity to misuse an imperfectly constructed object.
5949 ##### Note
5951 The return type of the factory should normally be `unique_ptr` by default; if some uses are shared, the caller can `move` the `unique_ptr` into a `shared_ptr`. However, if the factory author knows that all uses of the returned object will be shared uses, return `shared_ptr` and use `make_shared` in the body to save an allocation.
5953 ##### Example, bad
5955     class B {
5956     public:
5957         B()
5958         {
5959             /* ... */
5960             f(); // BAD: C.82: Don't call virtual functions in constructors and destructors
5961             /* ... */
5962         }
5964         virtual void f() = 0;
5965     };
5967 ##### Example
5969     class B {
5970     protected:
5971         class Token {};
5973     public:
5974         explicit B(Token) { /* ... */ }  // create an imperfectly initialized object
5975         virtual void f() = 0;
5977         template<class T>
5978         static shared_ptr<T> create()    // interface for creating shared objects
5979         {
5980             auto p = make_shared<T>(typename T::Token{});
5981             p->post_initialize();
5982             return p;
5983         }
5985     protected:
5986         virtual void post_initialize()   // called right after construction
5987             { /* ... */ f(); /* ... */ } // GOOD: virtual dispatch is safe
5988     };
5990     class D : public B {                 // some derived class
5991     protected:
5992         class Token {};
5994     public:
5995         explicit D(Token) : B{ B::Token{} } {}
5996         void f() override { /* ...  */ };
5998     protected:
5999         template<class T>
6000         friend shared_ptr<T> B::create();
6001     };
6003     shared_ptr<D> p = D::create<D>();  // creating a D object
6005 `make_shared` requires that the constructor is public. By requiring a protected `Token` the constructor cannot be publicly called anymore, so we avoid an incompletely constructed object escaping into the wild.
6006 By providing the factory function `create()`, we make construction (on the free store) convenient.
6008 ##### Note
6010 Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object.
6012 **See also**: [Discussion](#Sd-factory)
6014 ### <a name="Rc-delegating"></a>C.51: Use delegating constructors to represent common actions for all constructors of a class
6016 ##### Reason
6018 To avoid repetition and accidental differences.
6020 ##### Example, bad
6022     class Date {   // BAD: repetitive
6023         int d;
6024         Month m;
6025         int y;
6026     public:
6027         Date(int dd, Month mm, year yy)
6028             :d{dd}, m{mm}, y{yy}
6029             { if (!valid(d, m, y)) throw Bad_date{}; }
6031         Date(int dd, Month mm)
6032             :d{dd}, m{mm} y{current_year()}
6033             { if (!valid(d, m, y)) throw Bad_date{}; }
6034         // ...
6035     };
6037 The common action gets tedious to write and might accidentally not be common.
6039 ##### Example
6041     class Date2 {
6042         int d;
6043         Month m;
6044         int y;
6045     public:
6046         Date2(int dd, Month mm, year yy)
6047             :d{dd}, m{mm}, y{yy}
6048             { if (!valid(d, m, y)) throw Bad_date{}; }
6050         Date2(int dd, Month mm)
6051             :Date2{dd, mm, current_year()} {}
6052         // ...
6053     };
6055 **See also**: If the "repeated action" is a simple initialization, consider [a default member initializer](#Rc-in-class-initializer).
6057 ##### Enforcement
6059 (Moderate) Look for similar constructor bodies.
6061 ### <a name="Rc-inheriting"></a>C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization
6063 ##### Reason
6065 If you need those constructors for a derived class, re-implementing them is tedious and error-prone.
6067 ##### Example
6069 `std::vector` has a lot of tricky constructors, so if I want my own `vector`, I don't want to reimplement them:
6071     class Rec {
6072         // ... data and lots of nice constructors ...
6073     };
6075     class Oper : public Rec {
6076         using Rec::Rec;
6077         // ... no data members ...
6078         // ... lots of nice utility functions ...
6079     };
6081 ##### Example, bad
6083     struct Rec2 : public Rec {
6084         int x;
6085         using Rec::Rec;
6086     };
6088     Rec2 r {"foo", 7};
6089     int val = r.x;   // uninitialized
6091 ##### Enforcement
6093 Make sure that every member of the derived class is initialized.
6095 ## <a name="SS-copy"></a>C.copy: Copy and move
6097 Concrete types should generally be copyable, but interfaces in a class hierarchy should not.
6098 Resource handles might or might not be copyable.
6099 Types can be defined to move for logical as well as performance reasons.
6101 ### <a name="Rc-copy-assignment"></a>C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`
6103 ##### Reason
6105 It is simple and efficient. If you want to optimize for rvalues, provide an overload that takes a `&&` (see [F.18](#Rf-consume)).
6107 ##### Example
6109     class Foo {
6110     public:
6111         Foo& operator=(const Foo& x)
6112         {
6113             // GOOD: no need to check for self-assignment (other than performance)
6114             auto tmp = x;
6115             swap(tmp); // see C.83
6116             return *this;
6117         }
6118         // ...
6119     };
6121     Foo a;
6122     Foo b;
6123     Foo f();
6125     a = b;    // assign lvalue: copy
6126     a = f();  // assign rvalue: potentially move
6128 ##### Note
6130 The `swap` implementation technique offers the [strong guarantee](#Abrahams01).
6132 ##### Example
6134 But what if you can get significantly better performance by not making a temporary copy? Consider a simple `Vector` intended for a domain where assignment of large, equal-sized `Vector`s is common. In this case, the copy of elements implied by the `swap` implementation technique could cause an order of magnitude increase in cost:
6136     template<typename T>
6137     class Vector {
6138     public:
6139         Vector& operator=(const Vector&);
6140         // ...
6141     private:
6142         T* elem;
6143         int sz;
6144     };
6146     Vector& Vector::operator=(const Vector& a)
6147     {
6148         if (a.sz > sz) {
6149             // ... use the swap technique, it can't be bettered ...
6150             return *this;
6151         }
6152         // ... copy sz elements from *a.elem to elem ...
6153         if (a.sz < sz) {
6154             // ... destroy the surplus elements in *this and adjust size ...
6155         }
6156         return *this;
6157     }
6159 By writing directly to the target elements, we will get only [the basic guarantee](#Abrahams01) rather than the strong guarantee offered by the `swap` technique. Beware of [self-assignment](#Rc-copy-self).
6161 **Alternatives**: If you think you need a `virtual` assignment operator, and understand why that's deeply problematic, don't call it `operator=`. Make it a named function like `virtual void assign(const Foo&)`.
6162 See [copy constructor vs. `clone()`](#Rc-copy-virtual).
6164 ##### Enforcement
6166 * (Simple) An assignment operator should not be virtual. Here be dragons!
6167 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
6168 * (Moderate) An assignment operator should (implicitly or explicitly) invoke all base and member assignment operators.
6169   Look at the destructor to determine if the type has pointer semantics or value semantics.
6171 ### <a name="Rc-copy-semantic"></a>C.61: A copy operation should copy
6173 ##### Reason
6175 That is the generally assumed semantics. After `x = y`, we should have `x == y`.
6176 After a copy `x` and `y` can be independent objects (value semantics, the way non-pointer built-in types and the standard-library types work) or refer to a shared object (pointer semantics, the way pointers work).
6178 ##### Example
6180     class X {   // OK: value semantics
6181     public:
6182         X();
6183         X(const X&);     // copy X
6184         void modify();   // change the value of X
6185         // ...
6186         ~X() { delete[] p; }
6187     private:
6188         T* p;
6189         int sz;
6190     };
6192     bool operator==(const X& a, const X& b)
6193     {
6194         return a.sz == b.sz && equal(a.p, a.p + a.sz, b.p, b.p + b.sz);
6195     }
6197     X::X(const X& a)
6198         :p{new T[a.sz]}, sz{a.sz}
6199     {
6200         copy(a.p, a.p + sz, p);
6201     }
6203     X x;
6204     X y = x;
6205     if (x != y) throw Bad{};
6206     x.modify();
6207     if (x == y) throw Bad{};   // assume value semantics
6209 ##### Example
6211     class X2 {  // OK: pointer semantics
6212     public:
6213         X2();
6214         X2(const X2&) = default; // shallow copy
6215         ~X2() = default;
6216         void modify();          // change the pointed-to value
6217         // ...
6218     private:
6219         T* p;
6220         int sz;
6221     };
6223     bool operator==(const X2& a, const X2& b)
6224     {
6225         return a.sz == b.sz && a.p == b.p;
6226     }
6228     X2 x;
6229     X2 y = x;
6230     if (x != y) throw Bad{};
6231     x.modify();
6232     if (x != y) throw Bad{};  // assume pointer semantics
6234 ##### Note
6236 Prefer value semantics unless you are building a "smart pointer". Value semantics is the simplest to reason about and what the standard-library facilities expect.
6238 ##### Enforcement
6240 (Not enforceable)
6242 ### <a name="Rc-copy-self"></a>C.62: Make copy assignment safe for self-assignment
6244 ##### Reason
6246 If `x = x` changes the value of `x`, people will be surprised and bad errors will occur (often including leaks).
6248 ##### Example
6250 The standard-library containers handle self-assignment elegantly and efficiently:
6252     std::vector<int> v = {3, 1, 4, 1, 5, 9};
6253     v = v;
6254     // the value of v is still {3, 1, 4, 1, 5, 9}
6256 ##### Note
6258 The default assignment generated from members that handle self-assignment correctly handles self-assignment.
6260     struct Bar {
6261         vector<pair<int, int>> v;
6262         map<string, int> m;
6263         string s;
6264     };
6266     Bar b;
6267     // ...
6268     b = b;   // correct and efficient
6270 ##### Note
6272 You can handle self-assignment by explicitly testing for self-assignment, but often it is faster and more elegant to cope without such a test (e.g., [using `swap`](#Rc-swap)).
6274     class Foo {
6275         string s;
6276         int i;
6277     public:
6278         Foo& operator=(const Foo& a);
6279         // ...
6280     };
6282     Foo& Foo::operator=(const Foo& a)   // OK, but there is a cost
6283     {
6284         if (this == &a) return *this;
6285         s = a.s;
6286         i = a.i;
6287         return *this;
6288     }
6290 This is obviously safe and apparently efficient.
6291 However, what if we do one self-assignment per million assignments?
6292 That's about a million redundant tests (but since the answer is essentially always the same, the computer's branch predictor will guess right essentially every time).
6293 Consider:
6295     Foo& Foo::operator=(const Foo& a)   // simpler, and probably much better
6296     {
6297         s = a.s;
6298         i = a.i;
6299         return *this;
6300     }
6302 `std::string` is safe for self-assignment and so are `int`. All the cost is carried by the (rare) case of self-assignment.
6304 ##### Enforcement
6306 (Simple) Assignment operators should not contain the pattern `if (this == &a) return *this;` ???
6308 ### <a name="Rc-move-assignment"></a>C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const&`
6310 ##### Reason
6312 It is simple and efficient.
6314 **See**: [The rule for copy-assignment](#Rc-copy-assignment).
6316 ##### Enforcement
6318 Equivalent to what is done for [copy-assignment](#Rc-copy-assignment).
6320 * (Simple) An assignment operator should not be virtual. Here be dragons!
6321 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
6322 * (Moderate) A move assignment operator should (implicitly or explicitly) invoke all base and member move assignment operators.
6324 ### <a name="Rc-move-semantic"></a>C.64: A move operation should move and leave its source in a valid state
6326 ##### Reason
6328 That is the generally assumed semantics.
6329 After `y = std::move(x)` the value of `y` should be the value `x` had and `x` should be in a valid state.
6331 ##### Example
6333     class X {   // OK: value semantics
6334     public:
6335         X();
6336         X(X&& a) noexcept;  // move X
6337         X& operator=(X&& a) noexcept; // move-assign X
6338         void modify();     // change the value of X
6339         // ...
6340         ~X() { delete[] p; }
6341     private:
6342         T* p;
6343         int sz;
6344     };
6346     X::X(X&& a) noexcept
6347         :p{a.p}, sz{a.sz}  // steal representation
6348     {
6349         a.p = nullptr;     // set to "empty"
6350         a.sz = 0;
6351     }
6353     void use()
6354     {
6355         X x{};
6356         // ...
6357         X y = std::move(x);
6358         x = X{};   // OK
6359     } // OK: x can be destroyed
6361 ##### Note
6363 Ideally, that moved-from should be the default value of the type.
6364 Ensure that unless there is an exceptionally good reason not to.
6365 However, not all types have a default value and for some types establishing the default value can be expensive.
6366 The standard requires only that the moved-from object can be destroyed.
6367 Often, we can easily and cheaply do better: The standard library assumes that it is possible to assign to a moved-from object.
6368 Always leave the moved-from object in some (necessarily specified) valid state.
6370 ##### Note
6372 Unless there is an exceptionally strong reason not to, make `x = std::move(y); y = z;` work with the conventional semantics.
6374 ##### Enforcement
6376 (Not enforceable) Look for assignments to members in the move operation. If there is a default constructor, compare those assignments to the initializations in the default constructor.
6378 ### <a name="Rc-move-self"></a>C.65: Make move assignment safe for self-assignment
6380 ##### Reason
6382 If `x = x` changes the value of `x`, people will be surprised and bad errors can occur. However, people don't usually directly write a self-assignment that turn into a move, but it can occur. However, `std::swap` is implemented using move operations so if you accidentally do `swap(a, b)` where `a` and `b` refer to the same object, failing to handle self-move could be a serious and subtle error.
6384 ##### Example
6386     class Foo {
6387         string s;
6388         int i;
6389     public:
6390         Foo& operator=(Foo&& a) noexcept;
6391         // ...
6392     };
6394     Foo& Foo::operator=(Foo&& a) noexcept  // OK, but there is a cost
6395     {
6396         if (this == &a) return *this;  // this line is redundant
6397         s = std::move(a.s);
6398         i = a.i;
6399         return *this;
6400     }
6402 The one-in-a-million argument against `if (this == &a) return *this;` tests from the discussion of [self-assignment](#Rc-copy-self) is even more relevant for self-move.
6404 ##### Note
6406 There is no known general way of avoiding an `if (this == &a) return *this;` test for a move assignment and still get a correct answer (i.e., after `x = x` the value of `x` is unchanged).
6408 ##### Note
6410 The ISO standard guarantees only a "valid but unspecified" state for the standard-library containers. Apparently this has not been a problem in about 10 years of experimental and production use. Please contact the editors if you find a counter example. The rule here is more caution and insists on complete safety.
6412 ##### Example
6414 Here is a way to move a pointer without a test (imagine it as code in the implementation a move assignment):
6416     // move from other.ptr to this->ptr
6417     T* temp = other.ptr;
6418     other.ptr = nullptr;
6419     delete ptr; // in self-move, this->ptr is also null; delete is a no-op
6420     ptr = temp; // in self-move, the original ptr is restored
6422 ##### Enforcement
6424 * (Moderate) In the case of self-assignment, a move assignment operator should not leave the object holding pointer members that have been `delete`d or set to `nullptr`.
6425 * (Not enforceable) Look at the use of standard-library container types (incl. `string`) and consider them safe for ordinary (not life-critical) uses.
6427 ### <a name="Rc-move-noexcept"></a>C.66: Make move operations `noexcept`
6429 ##### Reason
6431 A throwing move violates most people's reasonable assumptions.
6432 A non-throwing move will be used more efficiently by standard-library and language facilities.
6434 ##### Example
6436     template<typename T>
6437     class Vector {
6438     public:
6439         Vector(Vector&& a) noexcept :elem{a.elem}, sz{a.sz} { a.elem = nullptr; a.sz = 0; }
6440         Vector& operator=(Vector&& a) noexcept {
6441             if (&a != this) {
6442                 delete elem;
6443                 elem = a.elem; a.elem = nullptr;
6444                 sz   = a.sz;   a.sz   = 0;
6445             }
6446             return *this;
6447         }
6448         // ...
6449     private:
6450         T* elem;
6451         int sz;
6452     };
6454 These operations do not throw.
6456 ##### Example, bad
6458     template<typename T>
6459     class Vector2 {
6460     public:
6461         Vector2(Vector2&& a) noexcept { *this = a; }             // just use the copy
6462         Vector2& operator=(Vector2&& a) noexcept { *this = a; }  // just use the copy
6463         // ...
6464     private:
6465         T* elem;
6466         int sz;
6467     };
6469 This `Vector2` is not just inefficient, but since a vector copy requires allocation, it can throw.
6471 ##### Enforcement
6473 (Simple) A move operation should be marked `noexcept`.
6475 ### <a name="Rc-copy-virtual"></a>C.67: A polymorphic class should suppress public copy/move
6477 ##### Reason
6479 A *polymorphic class* is a class that defines or inherits at least one virtual function. It is likely that it will be used as a base class for other derived classes with polymorphic behavior. If it is accidentally passed by value, with the implicitly generated copy constructor and assignment, we risk slicing: only the base portion of a derived object will be copied, and the polymorphic behavior will be corrupted.
6481 If the class has no data, `=delete` the copy/move functions. Otherwise, make them protected.
6483 ##### Example, bad
6485     class B { // BAD: polymorphic base class doesn't suppress copying
6486     public:
6487         virtual char m() { return 'B'; }
6488         // ... nothing about copy operations, so uses default ...
6489     };
6491     class D : public B {
6492     public:
6493         char m() override { return 'D'; }
6494         // ...
6495     };
6497     void f(B& b)
6498     {
6499         auto b2 = b; // oops, slices the object; b2.m() will return 'B'
6500     }
6502     D d;
6503     f(d);
6505 ##### Example
6507     class B { // GOOD: polymorphic class suppresses copying
6508     public:
6509         B() = default;
6510         B(const B&) = delete;
6511         B& operator=(const B&) = delete;
6512         virtual char m() { return 'B'; }
6513         // ...
6514     };
6516     class D : public B {
6517     public:
6518         char m() override { return 'D'; }
6519         // ...
6520     };
6522     void f(B& b)
6523     {
6524         auto b2 = b; // ok, compiler will detect inadvertent copying, and protest
6525     }
6527     D d;
6528     f(d);
6530 ##### Note
6532 If you need to create deep copies of polymorphic objects, use `clone()` functions: see [C.130](#Rh-copy).
6534 ##### Exception
6536 Classes that represent exception objects need both to be polymorphic and copy-constructible.
6538 ##### Enforcement
6540 * Flag a polymorphic class with a public copy operation.
6541 * Flag an assignment of polymorphic class objects.
6543 ## C.other: Other default operation rules
6545 In addition to the operations for which the language offers default implementations,
6546 there are a few operations that are so foundational that specific rules for their definition are needed:
6547 comparisons, `swap`, and `hash`.
6549 ### <a name="Rc-eqdefault"></a>C.80: Use `=default` if you have to be explicit about using the default semantics
6551 ##### Reason
6553 The compiler is more likely to get the default semantics right and you cannot implement these functions better than the compiler.
6555 ##### Example
6557     class Tracer {
6558         string message;
6559     public:
6560         Tracer(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
6561         ~Tracer() { cerr << "exiting " << message << '\n'; }
6563         Tracer(const Tracer&) = default;
6564         Tracer& operator=(const Tracer&) = default;
6565         Tracer(Tracer&&) noexcept = default;
6566         Tracer& operator=(Tracer&&) noexcept = default;
6567     };
6569 Because we defined the destructor, we must define the copy and move operations. The `= default` is the best and simplest way of doing that.
6571 ##### Example, bad
6573     class Tracer2 {
6574         string message;
6575     public:
6576         Tracer2(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
6577         ~Tracer2() { cerr << "exiting " << message << '\n'; }
6579         Tracer2(const Tracer2& a) : message{a.message} {}
6580         Tracer2& operator=(const Tracer2& a) { message = a.message; return *this; }
6581         Tracer2(Tracer2&& a) noexcept :message{a.message} {}
6582         Tracer2& operator=(Tracer2&& a) noexcept { message = a.message; return *this; }
6583     };
6585 Writing out the bodies of the copy and move operations is verbose, tedious, and error-prone. A compiler does it better.
6587 ##### Enforcement
6589 (Moderate) The body of a special operation should not have the same accessibility and semantics as the compiler-generated version, because that would be redundant
6591 ### <a name="Rc-delete"></a>C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)
6593 ##### Reason
6595 In a few cases, a default operation is not desirable.
6597 ##### Example
6599     class Immortal {
6600     public:
6601         ~Immortal() = delete;   // do not allow destruction
6602         // ...
6603     };
6605     void use()
6606     {
6607         Immortal ugh;   // error: ugh cannot be destroyed
6608         Immortal* p = new Immortal{};
6609         delete p;       // error: cannot destroy *p
6610     }
6612 ##### Example
6614 A `unique_ptr` can be moved, but not copied. To achieve that its copy operations are deleted. To avoid copying it is necessary to `=delete` its copy operations from lvalues:
6616     template<class T, class D = default_delete<T>> class unique_ptr {
6617     public:
6618         // ...
6619         constexpr unique_ptr() noexcept;
6620         explicit unique_ptr(pointer p) noexcept;
6621         // ...
6622         unique_ptr(unique_ptr&& u) noexcept;   // move constructor
6623         // ...
6624         unique_ptr(const unique_ptr&) = delete; // disable copy from lvalue
6625         // ...
6626     };
6628     unique_ptr<int> make();   // make "something" and return it by moving
6630     void f()
6631     {
6632         unique_ptr<int> pi {};
6633         auto pi2 {pi};      // error: no move constructor from lvalue
6634         auto pi3 {make()};  // OK, move: the result of make() is an rvalue
6635     }
6637 Note that deleted functions should be public.
6639 ##### Enforcement
6641 The elimination of a default operation is (should be) based on the desired semantics of the class. Consider such classes suspect, but maintain a "positive list" of classes where a human has asserted that the semantics is correct.
6643 ### <a name="Rc-ctor-virtual"></a>C.82: Don't call virtual functions in constructors and destructors
6645 ##### Reason
6647 The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class.
6648 This can be most confusing.
6649 Worse, a direct or indirect call to an unimplemented pure virtual function from a constructor or destructor results in undefined behavior.
6651 ##### Example, bad
6653     class Base {
6654     public:
6655         virtual void f() = 0;   // not implemented
6656         virtual void g();       // implemented with Base version
6657         virtual void h();       // implemented with Base version
6658         virtual ~Base();        // implemented with Base version
6659     };
6661     class Derived : public Base {
6662     public:
6663         void g() override;   // provide Derived implementation
6664         void h() final;      // provide Derived implementation
6666         Derived()
6667         {
6668             // BAD: attempt to call an unimplemented virtual function
6669             f();
6671             // BAD: will call Derived::g, not dispatch further virtually
6672             g();
6674             // GOOD: explicitly state intent to call only the visible version
6675             Derived::g();
6677             // ok, no qualification needed, h is final
6678             h();
6679         }
6680     };
6682 Note that calling a specific explicitly qualified function is not a virtual call even if the function is `virtual`.
6684 **See also** [factory functions](#Rc-factory) for how to achieve the effect of a call to a derived class function without risking undefined behavior.
6686 ##### Note
6688 There is nothing inherently wrong with calling virtual functions from constructors and destructors.
6689 The semantics of such calls is type safe.
6690 However, experience shows that such calls are rarely needed, easily confuse maintainers, and become a source of errors when used by novices.
6692 ##### Enforcement
6694 * Flag calls of virtual functions from constructors and destructors.
6696 ### <a name="Rc-swap"></a>C.83: For value-like types, consider providing a `noexcept` swap function
6698 ##### Reason
6700 A `swap` can be handy for implementing a number of idioms, from smoothly moving objects around to implementing assignment easily to providing a guaranteed commit function that enables strongly error-safe calling code. Consider using swap to implement copy assignment in terms of copy construction. See also [destructors, deallocation, and swap must never fail](#Re-never-fail).
6702 ##### Example, good
6704     class Foo {
6705     public:
6706         void swap(Foo& rhs) noexcept
6707         {
6708             m1.swap(rhs.m1);
6709             std::swap(m2, rhs.m2);
6710         }
6711     private:
6712         Bar m1;
6713         int m2;
6714     };
6716 Providing a non-member `swap` function in the same namespace as your type for callers' convenience.
6718     void swap(Foo& a, Foo& b)
6719     {
6720         a.swap(b);
6721     }
6723 ##### Enforcement
6725 * Non-trivially copyable types should provide a member swap or a free swap overload.
6726 * (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6728 ### <a name="Rc-swap-fail"></a>C.84: A `swap` function must not fail
6730 ##### Reason
6732  `swap` is widely used in ways that are assumed never to fail and programs cannot easily be written to work correctly in the presence of a failing `swap`. The standard-library containers and algorithms will not work correctly if a swap of an element type fails.
6734 ##### Example, bad
6736     void swap(My_vector& x, My_vector& y)
6737     {
6738         auto tmp = x;   // copy elements
6739         x = y;
6740         y = tmp;
6741     }
6743 This is not just slow, but if a memory allocation occurs for the elements in `tmp`, this `swap` could throw and would make STL algorithms fail if used with them.
6745 ##### Enforcement
6747 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6749 ### <a name="Rc-swap-noexcept"></a>C.85: Make `swap` `noexcept`
6751 ##### Reason
6753  [A `swap` must not fail](#Rc-swap-fail).
6754 If a `swap` tries to exit with an exception, it's a bad design error and the program had better terminate.
6756 ##### Enforcement
6758 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6760 ### <a name="Rc-eq"></a>C.86: Make `==` symmetric with respect to operand types and `noexcept`
6762 ##### Reason
6764 Asymmetric treatment of operands is surprising and a source of errors where conversions are possible.
6765 `==` is a fundamental operation and programmers should be able to use it without fear of failure.
6767 ##### Example
6769     struct X {
6770         string name;
6771         int number;
6772     };
6774     bool operator==(const X& a, const X& b) noexcept {
6775         return a.name == b.name && a.number == b.number;
6776     }
6778 ##### Example, bad
6780     class B {
6781         string name;
6782         int number;
6783         bool operator==(const B& a) const {
6784             return name == a.name && number == a.number;
6785         }
6786         // ...
6787     };
6789 `B`'s comparison accepts conversions for its second operand, but not its first.
6791 ##### Note
6793 If a class has a failure state, like `double`'s `NaN`, there is a temptation to make a comparison against the failure state throw.
6794 The alternative is to make two failure states compare equal and any valid state compare false against the failure state.
6796 ##### Note
6798 This rule applies to all the usual comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6800 ##### Enforcement
6802 * Flag an `operator==()` for which the argument types differ; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6803 * Flag member `operator==()`s; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6805 ### <a name="Rc-eq-base"></a>C.87: Beware of `==` on base classes
6807 ##### Reason
6809 It is really hard to write a foolproof and useful `==` for a hierarchy.
6811 ##### Example, bad
6813     class B {
6814         string name;
6815         int number;
6816     public:
6817         virtual bool operator==(const B& a) const
6818         {
6819              return name == a.name && number == a.number;
6820         }
6821         // ...
6822     };
6824 `B`'s comparison accepts conversions for its second operand, but not its first.
6826     class D : public B {
6827         char character;
6828     public:
6829         virtual bool operator==(const D& a) const
6830         {
6831             return B::operator==(a) && character == a.character;
6832         }
6833         // ...
6834     };
6836     B b = ...
6837     D d = ...
6838     b == d;    // compares name and number, ignores d's character
6839     d == b;    // compares name and number, ignores d's character
6840     D d2;
6841     d == d2;   // compares name, number, and character
6842     B& b2 = d2;
6843     b2 == d;   // compares name and number, ignores d2's and d's character
6845 Of course there are ways of making `==` work in a hierarchy, but the naive approaches do not scale
6847 ##### Note
6849 This rule applies to all the usual comparison operators: `!=`, `<`, `<=`, `>`, `>=`, and `<=>`.
6851 ##### Enforcement
6853 * Flag a virtual `operator==()`; same for other comparison operators: `!=`, `<`, `<=`, `>`, `>=`, and `<=>`.
6855 ### <a name="Rc-hash"></a>C.89: Make a `hash` `noexcept`
6857 ##### Reason
6859 Users of hashed containers use hash indirectly and don't expect simple access to throw.
6860 It's a standard-library requirement.
6862 ##### Example, bad
6864     template<>
6865     struct hash<My_type> {  // thoroughly bad hash specialization
6866         using result_type = size_t;
6867         using argument_type = My_type;
6869         size_t operator()(const My_type & x) const
6870         {
6871             size_t xs = x.s.size();
6872             if (xs < 4) throw Bad_My_type{};    // "Nobody expects the Spanish inquisition!"
6873             return hash<size_t>()(x.s.size()) ^ trim(x.s);
6874         }
6875     };
6877     int main()
6878     {
6879         unordered_map<My_type, int> m;
6880         My_type mt{ "asdfg" };
6881         m[mt] = 7;
6882         cout << m[My_type{ "asdfg" }] << '\n';
6883     }
6885 If you have to define a `hash` specialization, try simply to let it combine standard-library `hash` specializations with `^` (xor).
6886 That tends to work better than "cleverness" for non-specialists.
6888 ##### Enforcement
6890 * Flag throwing `hash`es.
6892 ### <a name="Rc-memset"></a>C.90: Rely on constructors and assignment operators, not `memset` and `memcpy`
6894 ##### Reason
6896 The standard C++ mechanism to construct an instance of a type is to call its constructor. As specified in guideline [C.41](#Rc-complete): a constructor should create a fully initialized object. No additional initialization, such as by `memcpy`, should be required.
6897 A type will provide a copy constructor and/or copy assignment operator to appropriately make a copy of the class, preserving the type's invariants.  Using memcpy to copy a non-trivially copyable type has undefined behavior.  Frequently this results in slicing, or data corruption.
6899 ##### Example, good
6901     struct base {
6902         virtual void update() = 0;
6903         std::shared_ptr<int> sp;
6904     };
6906     struct derived : public base {
6907         void update() override {}
6908     };
6910 ##### Example, bad
6912     void init(derived& a)
6913     {
6914         memset(&a, 0, sizeof(derived));
6915     }
6917 This is type-unsafe and overwrites the vtable.
6919 ##### Example, bad
6921     void copy(derived& a, derived& b)
6922     {
6923         memcpy(&a, &b, sizeof(derived));
6924     }
6926 This is also type-unsafe and overwrites the vtable.
6928 ##### Enforcement
6930 * Flag passing a non-trivially-copyable type to `memset` or `memcpy`.
6932 ## <a name="SS-containers"></a>C.con: Containers and other resource handles
6934 A container is an object holding a sequence of objects of some type; `std::vector` is the archetypical container.
6935 A resource handle is a class that owns a resource; `std::vector` is the typical resource handle; its resource is its sequence of elements.
6937 Summary of container rules:
6939 * [C.100: Follow the STL when defining a container](#Rcon-stl)
6940 * [C.101: Give a container value semantics](#Rcon-val)
6941 * [C.102: Give a container move operations](#Rcon-move)
6942 * [C.103: Give a container an initializer list constructor](#Rcon-init)
6943 * [C.104: Give a container a default constructor that sets it to empty](#Rcon-empty)
6944 * ???
6945 * [C.109: If a resource handle has pointer semantics, provide `*` and `->`](#Rcon-ptr)
6947 **See also**: [Resources](#S-resource)
6950 ### <a name="Rcon-stl"></a>C.100: Follow the STL when defining a container
6952 ##### Reason
6954 The STL containers are familiar to most C++ programmers and a fundamentally sound design.
6956 ##### Note
6958 There are of course other fundamentally sound design styles and sometimes reasons to depart from
6959 the style of the standard library, but in the absence of a solid reason to differ, it is simpler
6960 and easier for both implementers and users to follow the standard.
6962 In particular, `std::vector` and `std::map` provide useful relatively simple models.
6964 ##### Example
6966     // simplified (e.g., no allocators):
6968     template<typename T>
6969     class Sorted_vector {
6970         using value_type = T;
6971         // ... iterator types ...
6973         Sorted_vector() = default;
6974         Sorted_vector(initializer_list<T>);    // initializer-list constructor: sort and store
6975         Sorted_vector(const Sorted_vector&) = default;
6976         Sorted_vector(Sorted_vector&&) noexcept = default;
6977         Sorted_vector& operator=(const Sorted_vector&) = default;     // copy assignment
6978         Sorted_vector& operator=(Sorted_vector&&) noexcept = default; // move assignment
6979         ~Sorted_vector() = default;
6981         Sorted_vector(const std::vector<T>& v);   // store and sort
6982         Sorted_vector(std::vector<T>&& v);        // sort and "steal representation"
6984         const T& operator[](int i) const { return rep[i]; }
6985         // no non-const direct access to preserve order
6987         void push_back(const T&);   // insert in the right place (not necessarily at back)
6988         void push_back(T&&);        // insert in the right place (not necessarily at back)
6990         // ... cbegin(), cend() ...
6991     private:
6992         std::vector<T> rep;  // use a std::vector to hold elements
6993     };
6995     template<typename T> bool operator==(const Sorted_vector<T>&, const Sorted_vector<T>&);
6996     template<typename T> bool operator!=(const Sorted_vector<T>&, const Sorted_vector<T>&);
6997     // ...
6999 Here, the STL style is followed, but incompletely.
7000 That's not uncommon.
7001 Provide only as much functionality as makes sense for a specific container.
7002 The key is to define the conventional constructors, assignments, destructors, and iterators
7003 (as meaningful for the specific container) with their conventional semantics.
7004 From that base, the container can be expanded as needed.
7005 Here, special constructors from `std::vector` were added.
7007 ##### Enforcement
7011 ### <a name="Rcon-val"></a>C.101: Give a container value semantics
7013 ##### Reason
7015 Regular objects are simpler to think and reason about than irregular ones.
7016 Familiarity.
7018 ##### Note
7020 If meaningful, make a container `Regular` (the concept).
7021 In particular, ensure that an object compares equal to its copy.
7023 ##### Example
7025     void f(const Sorted_vector<string>& v)
7026     {
7027         Sorted_vector<string> v2 {v};
7028         if (v != v2)
7029             cout << "Behavior against reason and logic.\n";
7030         // ...
7031     }
7033 ##### Enforcement
7037 ### <a name="Rcon-move"></a>C.102: Give a container move operations
7039 ##### Reason
7041 Containers tend to get large; without a move constructor and a copy constructor an object can be
7042 expensive to move around, thus tempting people to pass pointers to it around and getting into
7043 resource management problems.
7045 ##### Example
7047     Sorted_vector<int> read_sorted(istream& is)
7048     {
7049         vector<int> v;
7050         cin >> v;   // assume we have a read operation for vectors
7051         Sorted_vector<int> sv = v;  // sorts
7052         return sv;
7053     }
7055 A user can reasonably assume that returning a standard-like container is cheap.
7057 ##### Enforcement
7061 ### <a name="Rcon-init"></a>C.103: Give a container an initializer list constructor
7063 ##### Reason
7065 People expect to be able to initialize a container with a set of values.
7066 Familiarity.
7068 ##### Example
7070     Sorted_vector<int> sv {1, 3, -1, 7, 0, 0}; // Sorted_vector sorts elements as needed
7072 ##### Enforcement
7076 ### <a name="Rcon-empty"></a>C.104: Give a container a default constructor that sets it to empty
7078 ##### Reason
7080 To make it `Regular`.
7082 ##### Example
7084     vector<Sorted_sequence<string>> vs(100);    // 100 Sorted_sequences each with the value ""
7086 ##### Enforcement
7090 ### <a name="Rcon-ptr"></a>C.109: If a resource handle has pointer semantics, provide `*` and `->`
7092 ##### Reason
7094 That's what is expected from pointers.
7095 Familiarity.
7097 ##### Example
7099     ???
7101 ##### Enforcement
7105 ## <a name="SS-lambdas"></a>C.lambdas: Function objects and lambdas
7107 A function object is an object supplying an overloaded `()` so that you can call it.
7108 A lambda expression (colloquially often shortened to "a lambda") is a notation for generating a function object.
7109 Function objects should be cheap to copy (and therefore [passed by value](#Rf-in)).
7111 Summary:
7113 * [F.10: If an operation can be reused, give it a name](#Rf-name)
7114 * [F.11: Use an unnamed lambda if you need a simple function object in one place only](#Rf-lambda)
7115 * [F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)](#Rf-capture-vs-overload)
7116 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
7117 * [F.53: Avoid capturing by reference in lambdas that will be used non-locally, including returned, stored on the heap, or passed to another thread](#Rf-value-capture)
7118 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
7120 ## <a name="SS-hier"></a>C.hier: Class hierarchies (OOP)
7122 A class hierarchy is constructed to represent a set of hierarchically organized concepts (only).
7123 Typically base classes act as interfaces.
7124 There are two major uses for hierarchies, often named implementation inheritance and interface inheritance.
7126 Class hierarchy rule summary:
7128 * [C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)](#Rh-domain)
7129 * [C.121: If a base class is used as an interface, make it a pure abstract class](#Rh-abstract)
7130 * [C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed](#Rh-separation)
7132 Designing rules for classes in a hierarchy summary:
7134 * [C.126: An abstract class typically doesn't need a user-written constructor](#Rh-abstract-ctor)
7135 * [C.127: A class with a virtual function should have a virtual or protected destructor](#Rh-dtor)
7136 * [C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final`](#Rh-override)
7137 * [C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance](#Rh-kind)
7138 * [C.130: For making deep copies of polymorphic classes prefer a virtual `clone` function instead of public copy construction/assignment](#Rh-copy)
7139 * [C.131: Avoid trivial getters and setters](#Rh-get)
7140 * [C.132: Don't make a function `virtual` without reason](#Rh-virtual)
7141 * [C.133: Avoid `protected` data](#Rh-protected)
7142 * [C.134: Ensure all non-`const` data members have the same access level](#Rh-public)
7143 * [C.135: Use multiple inheritance to represent multiple distinct interfaces](#Rh-mi-interface)
7144 * [C.136: Use multiple inheritance to represent the union of implementation attributes](#Rh-mi-implementation)
7145 * [C.137: Use `virtual` bases to avoid overly general base classes](#Rh-vbase)
7146 * [C.138: Create an overload set for a derived class and its bases with `using`](#Rh-using)
7147 * [C.139: Use `final` on classes sparingly](#Rh-final)
7148 * [C.140: Do not provide different default arguments for a virtual function and an overrider](#Rh-virtual-default-arg)
7150 Accessing objects in a hierarchy rule summary:
7152 * [C.145: Access polymorphic objects through pointers and references](#Rh-poly)
7153 * [C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable](#Rh-dynamic_cast)
7154 * [C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error](#Rh-ref-cast)
7155 * [C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative](#Rh-ptr-cast)
7156 * [C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`](#Rh-smart)
7157 * [C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s](#Rh-make_unique)
7158 * [C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s](#Rh-make_shared)
7159 * [C.152: Never assign a pointer to an array of derived class objects to a pointer to its base](#Rh-array)
7160 * [C.153: Prefer virtual function to casting](#Rh-use-virtual)
7162 ### <a name="Rh-domain"></a>C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)
7164 ##### Reason
7166 Direct representation of ideas in code eases comprehension and maintenance. Make sure the idea represented in the base class exactly matches all derived types and there is not a better way to express it than using the tight coupling of inheritance.
7168 Do *not* use inheritance when simply having a data member will do. Usually this means that the derived type needs to override a base virtual function or needs access to a protected member.
7170 ##### Example
7172     class DrawableUIElement {
7173     public:
7174         virtual void render() const = 0;
7175         // ...
7176     };
7178     class AbstractButton : public DrawableUIElement {
7179     public:
7180         virtual void onClick() = 0;
7181         // ...
7182     };
7184     class PushButton : public AbstractButton {
7185         void render() const override;
7186         void onClick() override;
7187         // ...
7188     };
7190     class Checkbox : public AbstractButton {
7191     // ...
7192     };
7194 ##### Example, bad
7196 Do *not* represent non-hierarchical domain concepts as class hierarchies.
7198     template<typename T>
7199     class Container {
7200     public:
7201         // list operations:
7202         virtual T& get() = 0;
7203         virtual void put(T&) = 0;
7204         virtual void insert(Position) = 0;
7205         // ...
7206         // vector operations:
7207         virtual T& operator[](int) = 0;
7208         virtual void sort() = 0;
7209         // ...
7210         // tree operations:
7211         virtual void balance() = 0;
7212         // ...
7213     };
7215 Here most overriding classes cannot implement most of the functions required in the interface well.
7216 Thus the base class becomes an implementation burden.
7217 Furthermore, the user of `Container` cannot rely on the member functions actually performing meaningful operations reasonably efficiently;
7218 it might throw an exception instead.
7219 Thus users have to resort to run-time checking and/or
7220 not using this (over)general interface in favor of a particular interface found by a run-time type inquiry (e.g., a `dynamic_cast`).
7222 ##### Enforcement
7224 * Look for classes with lots of members that do nothing but throw.
7225 * Flag every use of a non-public base class `B` where the derived class `D` does not override a virtual function or access a protected member in `B`, and `B` is not one of the following: empty, a template parameter or parameter pack of `D`, a class template specialized with `D`.
7227 ### <a name="Rh-abstract"></a>C.121: If a base class is used as an interface, make it a pure abstract class
7229 ##### Reason
7231 A class is more stable (less brittle) if it does not contain data.
7232 Interfaces should normally be composed entirely of public pure virtual functions and a default/empty virtual destructor.
7234 ##### Example
7236     class My_interface {
7237     public:
7238         // ...only pure virtual functions here ...
7239         virtual ~My_interface() {}   // or =default
7240     };
7242 ##### Example, bad
7244     class Goof {
7245     public:
7246         // ...only pure virtual functions here ...
7247         // no virtual destructor
7248     };
7250     class Derived : public Goof {
7251         string s;
7252         // ...
7253     };
7255     void use()
7256     {
7257         unique_ptr<Goof> p {new Derived{"here we go"}};
7258         f(p.get()); // use Derived through the Goof interface
7259         g(p.get()); // use Derived through the Goof interface
7260     } // leak
7262 The `Derived` is `delete`d through its `Goof` interface, so its `string` is leaked.
7263 Give `Goof` a virtual destructor and all is well.
7266 ##### Enforcement
7268 * Warn on any class that contains data members and also has an overridable (non-`final`) virtual function that wasn't inherited from a base class.
7270 ### <a name="Rh-separation"></a>C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed
7272 ##### Reason
7274 Such as on an ABI (link) boundary.
7276 ##### Example
7278     struct Device {
7279         virtual ~Device() = default;
7280         virtual void write(span<const char> outbuf) = 0;
7281         virtual void read(span<char> inbuf) = 0;
7282     };
7284     class D1 : public Device {
7285         // ... data ...
7287         void write(span<const char> outbuf) override;
7288         void read(span<char> inbuf) override;
7289     };
7291     class D2 : public Device {
7292         // ... different data ...
7294         void write(span<const char> outbuf) override;
7295         void read(span<char> inbuf) override;
7296     };
7298 A user can now use `D1`s and `D2`s interchangeably through the interface provided by `Device`.
7299 Furthermore, we can update `D1` and `D2` in ways that are not binary compatible with older versions as long as all access goes through `Device`.
7301 ##### Enforcement
7303     ???
7305 ## C.hierclass: Designing classes in a hierarchy:
7307 ### <a name="Rh-abstract-ctor"></a>C.126: An abstract class typically doesn't need a user-written constructor
7309 ##### Reason
7311 An abstract class typically does not have any data for a constructor to initialize.
7313 ##### Example
7315     class Shape {
7316     public:
7317         // no user-written constructor needed in abstract base class
7318         virtual Point center() const = 0;    // pure virtual
7319         virtual void move(Point to) = 0;
7320         // ... more pure virtual functions...
7321         virtual ~Shape() {}                 // destructor
7322     };
7324     class Circle : public Shape {
7325     public:
7326         Circle(Point p, int rad);           // constructor in derived class
7327         Point center() const override { return x; }
7328     };
7330 ##### Exception
7332 * A base class constructor that does work, such as registering an object somewhere, might need a constructor.
7333 * In extremely rare cases, you might find it reasonable for an abstract class to have a bit of data shared by all derived classes
7334   (e.g., use statistics data, debug information, etc.); such classes tend to have constructors. But be warned: Such classes also tend to be prone to requiring virtual inheritance.
7336 ##### Enforcement
7338 Flag abstract classes with constructors.
7340 ### <a name="Rh-dtor"></a>C.127: A class with a virtual function should have a virtual or protected destructor
7342 ##### Reason
7344 A class with a virtual function is usually (and in general) used via a pointer to base. Usually, the last user has to call delete on a pointer to base, often via a smart pointer to base, so the destructor should be public and virtual. Less commonly, if deletion through a pointer to base is not intended to be supported, the destructor should be protected and non-virtual; see [C.35](#Rc-dtor-virtual).
7346 ##### Example, bad
7348     struct B {
7349         virtual int f() = 0;
7350         // ... no user-written destructor, defaults to public non-virtual ...
7351     };
7353     // bad: derived from a class without a virtual destructor
7354     struct D : B {
7355         string s {"default"};
7356         // ...
7357     };
7359     void use()
7360     {
7361         unique_ptr<B> p = make_unique<D>();
7362         // ...
7363     } // undefined behavior, might call B::~B only and leak the string
7365 ##### Note
7367 There are people who don't follow this rule because they plan to use a class only through a `shared_ptr`: `std::shared_ptr<B> p = std::make_shared<D>(args);` Here, the shared pointer will take care of deletion, so no leak will occur from an inappropriate `delete` of the base. People who do this consistently can get a false positive, but the rule is important -- what if one was allocated using `make_unique`? It's not safe unless the author of `B` ensures that it can never be misused, such as by making all constructors private and providing a factory function to enforce the allocation with `make_shared`.
7369 ##### Enforcement
7371 * A class with any virtual functions should have a destructor that is either public and virtual or else protected and non-virtual.
7372 * Flag `delete` of a class with a virtual function but no virtual destructor.
7374 ### <a name="Rh-override"></a>C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final`
7376 ##### Reason
7378 Readability.
7379 Detection of mistakes.
7380 Writing explicit `virtual`, `override`, or `final` is self-documenting and enables the compiler to catch mismatch of types and/or names between base and derived classes. However, writing more than one of these three is both redundant and a potential source of errors.
7382 It's simple and clear:
7384 * `virtual` means exactly and only "this is a new virtual function."
7385 * `override` means exactly and only "this is a non-final overrider."
7386 * `final` means exactly and only "this is a final overrider."
7388 ##### Example, bad
7390     struct B {
7391         void f1(int);
7392         virtual void f2(int) const;
7393         virtual void f3(int);
7394         // ...
7395     };
7397     struct D : B {
7398         void f1(int);        // bad (hope for a warning): D::f1() hides B::f1()
7399         void f2(int) const;  // bad (but conventional and valid): no explicit override
7400         void f3(double);     // bad (hope for a warning): D::f3() hides B::f3()
7401         // ...
7402     };
7404 ##### Example, good
7406     struct Better : B {
7407         void f1(int) override;        // error (caught): Better::f1() hides B::f1()
7408         void f2(int) const override;
7409         void f3(double) override;     // error (caught): Better::f3() hides B::f3()
7410         // ...
7411     };
7413 #### Discussion
7415 We want to eliminate two particular classes of errors:
7417 * **implicit virtual**: the programmer intended the function to be implicitly virtual and it is (but readers of the code can't tell); or the programmer intended the function to be implicitly virtual but it isn't (e.g., because of a subtle parameter list mismatch); or the programmer did not intend the function to be virtual but it is (because it happens to have the same signature as a virtual in the base class)
7418 * **implicit override**: the programmer intended the function to be implicitly an overrider and it is (but readers of the code can't tell); or the programmer intended the function to be implicitly an overrider but it isn't (e.g., because of a subtle parameter list mismatch); or the programmer did not intend the function to be an overrider but it is (because it happens to have the same signature as a virtual in the base class -- note this problem arises whether or not the function is explicitly declared virtual, because the programmer might have intended to create either a new virtual function or a new non-virtual function)
7420 Note: On a class defined as `final`, it doesn't matter whether you put `override` or `final` on an individual virtual function.
7422 Note: Use `final` on functions sparingly. It does not necessarily lead to optimization, and it precludes further overriding.
7424 ##### Enforcement
7426 * Compare virtual function names in base and derived classes and flag uses of the same name that does not override.
7427 * Flag overrides with neither `override` nor `final`.
7428 * Flag function declarations that use more than one of `virtual`, `override`, and `final`.
7430 ### <a name="Rh-kind"></a>C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance
7432 ##### Reason
7434 Implementation details in an interface make the interface brittle;
7435 that is, make its users vulnerable to having to recompile after changes in the implementation.
7436 Data in a base class increases the complexity of implementing the base and can lead to replication of code.
7438 ##### Note
7440 Definition:
7442 * interface inheritance is the use of inheritance to separate users from implementations,
7443 in particular to allow derived classes to be added and changed without affecting the users of base classes.
7444 * implementation inheritance is the use of inheritance to simplify implementation of new facilities
7445 by making useful operations available for implementers of related new operations (sometimes called "programming by difference").
7447 A pure interface class is simply a set of pure virtual functions; see [I.25](#Ri-abstract).
7449 In early OOP (e.g., in the 1980s and 1990s), implementation inheritance and interface inheritance were often mixed
7450 and bad habits die hard.
7451 Even now, mixtures are not uncommon in old code bases and in old-style teaching material.
7453 The importance of keeping the two kinds of inheritance increases
7455 * with the size of a hierarchy (e.g., dozens of derived classes),
7456 * with the length of time the hierarchy is used (e.g., decades), and
7457 * with the number of distinct organizations in which a hierarchy is used
7458 (e.g., it can be difficult to distribute an update to a base class)
7461 ##### Example, bad
7463     class Shape {   // BAD, mixed interface and implementation
7464     public:
7465         Shape();
7466         Shape(Point ce = {0, 0}, Color co = none): cent{ce}, col {co} { /* ... */}
7468         Point center() const { return cent; }
7469         Color color() const { return col; }
7471         virtual void rotate(int) = 0;
7472         virtual void move(Point p) { cent = p; redraw(); }
7474         virtual void redraw();
7476         // ...
7477     private:
7478         Point cent;
7479         Color col;
7480     };
7482     class Circle : public Shape {
7483     public:
7484         Circle(Point c, int r) : Shape{c}, rad{r} { /* ... */ }
7486         // ...
7487     private:
7488         int rad;
7489     };
7491     class Triangle : public Shape {
7492     public:
7493         Triangle(Point p1, Point p2, Point p3); // calculate center
7494         // ...
7495     };
7497 Problems:
7499 * As the hierarchy grows and more data is added to `Shape`, the constructors get harder to write and maintain.
7500 * Why calculate the center for the `Triangle`? we might never use it.
7501 * Add a data member to `Shape` (e.g., drawing style or canvas)
7502 and all classes derived from `Shape` and all code using `Shape` will need to be reviewed, possibly changed, and probably recompiled.
7504 The implementation of `Shape::move()` is an example of implementation inheritance:
7505 we have defined `move()` once and for all, for all derived classes.
7506 The more code there is in such base class member function implementations and the more data is shared by placing it in the base,
7507 the more benefits we gain - and the less stable the hierarchy is.
7509 ##### Example
7511 This Shape hierarchy can be rewritten using interface inheritance:
7513     class Shape {  // pure interface
7514     public:
7515         virtual Point center() const = 0;
7516         virtual Color color() const = 0;
7518         virtual void rotate(int) = 0;
7519         virtual void move(Point p) = 0;
7521         virtual void redraw() = 0;
7523         // ...
7524     };
7526 Note that a pure interface rarely has constructors: there is nothing to construct.
7528     class Circle : public Shape {
7529     public:
7530         Circle(Point c, int r, Color c) : cent{c}, rad{r}, col{c} { /* ... */ }
7532         Point center() const override { return cent; }
7533         Color color() const override { return col; }
7535         // ...
7536     private:
7537         Point cent;
7538         int rad;
7539         Color col;
7540     };
7542 The interface is now less brittle, but there is more work in implementing the member functions.
7543 For example, `center` has to be implemented by every class derived from `Shape`.
7545 ##### Example, dual hierarchy
7547 How can we gain the benefit of stable hierarchies from interface hierarchies and the benefit of implementation reuse from implementation inheritance?
7548 One popular technique is dual hierarchies.
7549 There are many ways of implementing the idea of dual hierarchies; here, we use a multiple-inheritance variant.
7551 First we devise a hierarchy of interface classes:
7553     class Shape {   // pure interface
7554     public:
7555         virtual Point center() const = 0;
7556         virtual Color color() const = 0;
7558         virtual void rotate(int) = 0;
7559         virtual void move(Point p) = 0;
7561         virtual void redraw() = 0;
7563         // ...
7564     };
7566     class Circle : public virtual Shape {   // pure interface
7567     public:
7568         virtual int radius() = 0;
7569         // ...
7570     };
7572 To make this interface useful, we must provide its implementation classes (here, named equivalently, but in the `Impl` namespace):
7574     class Impl::Shape : public virtual ::Shape { // implementation
7575     public:
7576         // constructors, destructor
7577         // ...
7578         Point center() const override { /* ... */ }
7579         Color color() const override { /* ... */ }
7581         void rotate(int) override { /* ... */ }
7582         void move(Point p) override { /* ... */ }
7584         void redraw() override { /* ... */ }
7586         // ...
7587     };
7589 Now `Shape` is a poor example of a class with an implementation,
7590 but bear with us because this is just a simple example of a technique aimed at more complex hierarchies.
7592     class Impl::Circle : public virtual ::Circle, public Impl::Shape {   // implementation
7593     public:
7594         // constructors, destructor
7596         int radius() override { /* ... */ }
7597         // ...
7598     };
7600 And we could extend the hierarchies by adding a Smiley class (:-)):
7602     class Smiley : public virtual Circle { // pure interface
7603     public:
7604         // ...
7605     };
7607     class Impl::Smiley : public virtual ::Smiley, public Impl::Circle {   // implementation
7608     public:
7609         // constructors, destructor
7610         // ...
7611     }
7613 There are now two hierarchies:
7615 * interface: Smiley -> Circle -> Shape
7616 * implementation: Impl::Smiley -> Impl::Circle -> Impl::Shape
7618 Since each implementation is derived from its interface as well as its implementation base class we get a lattice (DAG):
7620     Smiley     ->         Circle     ->  Shape
7621       ^                     ^               ^
7622       |                     |               |
7623     Impl::Smiley -> Impl::Circle -> Impl::Shape
7625 As mentioned, this is just one way to construct a dual hierarchy.
7627 The implementation hierarchy can be used directly, rather than through the abstract interface.
7629     void work_with_shape(Shape&);
7631     int user()
7632     {
7633         Impl::Smiley my_smiley{ /* args */ };   // create concrete shape
7634         // ...
7635         my_smiley.some_member();        // use implementation class directly
7636         // ...
7637         work_with_shape(my_smiley);     // use implementation through abstract interface
7638         // ...
7639     }
7641 This can be useful when the implementation class has members that are not offered in the abstract interface
7642 or if direct use of a member offers optimization opportunities (e.g., if an implementation member function is `final`)
7644 ##### Note
7646 Another (related) technique for separating interface and implementation is [Pimpl](#Ri-pimpl).
7648 ##### Note
7650 There is often a choice between offering common functionality as (implemented) base class functions and freestanding functions
7651 (in an implementation namespace).
7652 Base classes give a shorter notation and easier access to shared data (in the base)
7653 at the cost of the functionality being available only to users of the hierarchy.
7655 ##### Enforcement
7657 * Flag a derived to base conversion to a base with both data and virtual functions
7658 (except for calls from a derived class member to a base class member)
7659 * ???
7662 ### <a name="Rh-copy"></a>C.130: For making deep copies of polymorphic classes prefer a virtual `clone` function instead of public copy construction/assignment
7664 ##### Reason
7666 Copying a polymorphic class is discouraged due to the slicing problem, see [C.67](#Rc-copy-virtual). If you really need copy semantics, copy deeply: Provide a virtual `clone` function that will copy the actual most-derived type and return an owning pointer to the new object, and then in derived classes return the derived type (use a covariant return type).
7668 ##### Example
7670     class B {
7671     public:
7672         B() = default;
7673         virtual ~B() = default;
7674         virtual gsl::owner<B*> clone() const = 0;
7675     protected:
7676          B(const B&) = default;
7677          B& operator=(const B&) = default;
7678          B(B&&) noexcept = default;
7679          B& operator=(B&&) noexcept = default;
7680         // ...
7681     };
7683     class D : public B {
7684     public:
7685         gsl::owner<D*> clone() const override
7686         {
7687             return new D{*this};
7688         };
7689     };
7691 Generally, it is recommended to use smart pointers to represent ownership (see [R.20](#Rr-owner)). However, because of language rules, the covariant return type cannot be a smart pointer: `D::clone` can't return a `unique_ptr<D>` while `B::clone` returns `unique_ptr<B>`. Therefore, you either need to consistently return `unique_ptr<B>` in all overrides, or use `owner<>` utility from the [Guidelines Support Library](#SS-views).
7695 ### <a name="Rh-get"></a>C.131: Avoid trivial getters and setters
7697 ##### Reason
7699 A trivial getter or setter adds no semantic value; the data item could just as well be `public`.
7701 ##### Example
7703     class Point {   // Bad: verbose
7704         int x;
7705         int y;
7706     public:
7707         Point(int xx, int yy) : x{xx}, y{yy} { }
7708         int get_x() const { return x; }
7709         void set_x(int xx) { x = xx; }
7710         int get_y() const { return y; }
7711         void set_y(int yy) { y = yy; }
7712         // no behavioral member functions
7713     };
7715 Consider making such a class a `struct` -- that is, a behaviorless bunch of variables, all public data and no member functions.
7717     struct Point {
7718         int x {0};
7719         int y {0};
7720     };
7722 Note that we can put default initializers on member variables: [C.49: Prefer initialization to assignment in constructors](#Rc-initialize).
7724 ##### Note
7726 The key to this rule is whether the semantics of the getter/setter are trivial. While it is not a complete definition of "trivial", consider whether there would be any difference beyond syntax if the getter/setter was a public data member instead. Examples of non-trivial semantics would be: maintaining a class invariant or converting between an internal type and an interface type.
7728 ##### Enforcement
7730 Flag multiple `get` and `set` member functions that simply access a member without additional semantics.
7732 ### <a name="Rh-virtual"></a>C.132: Don't make a function `virtual` without reason
7734 ##### Reason
7736 Redundant `virtual` increases run-time and object-code size.
7737 A virtual function can be overridden and is thus open to mistakes in a derived class.
7738 A virtual function ensures code replication in a templated hierarchy.
7740 ##### Example, bad
7742     template<class T>
7743     class Vector {
7744     public:
7745         // ...
7746         virtual int size() const { return sz; }   // bad: what good could a derived class do?
7747     private:
7748         T* elem;   // the elements
7749         int sz;    // number of elements
7750     };
7752 This kind of "vector" isn't meant to be used as a base class at all.
7754 ##### Enforcement
7756 * Flag a class with virtual functions but no derived classes.
7757 * Flag a class where all member functions are virtual and have implementations.
7759 ### <a name="Rh-protected"></a>C.133: Avoid `protected` data
7761 ##### Reason
7763 `protected` data is a source of complexity and errors.
7764 `protected` data complicates the statement of invariants.
7765 `protected` data inherently violates the guidance against putting data in base classes, which usually leads to having to deal with virtual inheritance as well.
7767 ##### Example, bad
7769     class Shape {
7770     public:
7771         // ... interface functions ...
7772     protected:
7773         // data for use in derived classes:
7774         Color fill_color;
7775         Color edge_color;
7776         Style st;
7777     };
7779 Now it is up to every derived `Shape` to manipulate the protected data correctly.
7780 This has been popular, but also a major source of maintenance problems.
7781 In a large class hierarchy, the consistent use of protected data is hard to maintain because there can be a lot of code,
7782 spread over a lot of classes.
7783 The set of classes that can touch that data is open: anyone can derive a new class and start manipulating the protected data.
7784 Often, it is not possible to examine the complete set of classes, so any change to the representation of the class becomes infeasible.
7785 There is no enforced invariant for the protected data; it is much like a set of global variables.
7786 The protected data has de facto become global to a large body of code.
7788 ##### Note
7790 Protected data often looks tempting to enable arbitrary improvements through derivation.
7791 Often, what you get is unprincipled changes and errors.
7792 [Prefer `private` data](#Rc-private) with a well-specified and enforced invariant.
7793 Alternative, and often better, [keep data out of any class used as an interface](#Rh-abstract).
7795 ##### Note
7797 Protected member function can be just fine.
7799 ##### Enforcement
7801 Flag classes with `protected` data.
7803 ### <a name="Rh-public"></a>C.134: Ensure all non-`const` data members have the same access level
7805 ##### Reason
7807 Prevention of logical confusion leading to errors.
7808 If the non-`const` data members don't have the same access level, the type is confused about what it's trying to do.
7809 Is it a type that maintains an invariant or simply a collection of values?
7811 ##### Discussion
7813 The core question is: What code is responsible for maintaining a meaningful/correct value for that variable?
7815 There are exactly two kinds of data members:
7817 * A: Ones that don't participate in the object's invariant. Any combination of values for these members is valid.
7818 * B: Ones that do participate in the object's invariant. Not every combination of values is meaningful (else there'd be no invariant). Therefore all code that has write access to these variables must know about the invariant, know the semantics, and know (and actively implement and enforce) the rules for keeping the values correct.
7820 Data members in category A should just be `public` (or, more rarely, `protected` if you only want derived classes to see them). They don't need encapsulation. All code in the system might as well see and manipulate them.
7822 Data members in category B should be `private` or `const`. This is because encapsulation is important. To make them non-`private` and non-`const` would mean that the object can't control its own state: An unbounded amount of code beyond the class would need to know about the invariant and participate in maintaining it accurately -- if these data members were `public`, that would be all calling code that uses the object; if they were `protected`, it would be all the code in current and future derived classes. This leads to brittle and tightly coupled code that quickly becomes a nightmare to maintain. Any code that inadvertently sets the data members to an invalid or unexpected combination of values would corrupt the object and all subsequent uses of the object.
7824 Most classes are either all A or all B:
7826 * *All public*: If you're writing an aggregate bundle-of-variables without an invariant across those variables, then all the variables should be `public`.
7827   [By convention, declare such classes `struct` rather than `class`](#Rc-struct)
7828 * *All private*: If you're writing a type that maintains an invariant, then all the non-`const` variables should be private -- it should be encapsulated.
7830 ##### Exception
7832 Occasionally classes will mix A and B, usually for debug reasons. An encapsulated object might contain something like non-`const` debug instrumentation that isn't part of the invariant and so falls into category A -- it isn't really part of the object's value or meaningful observable state either. In that case, the A parts should be treated as A's (made `public`, or in rarer cases `protected` if they should be visible only to derived classes) and the B parts should still be treated like B's (`private` or `const`).
7834 ##### Enforcement
7836 Flag any class that has non-`const` data members with different access levels.
7838 ### <a name="Rh-mi-interface"></a>C.135: Use multiple inheritance to represent multiple distinct interfaces
7840 ##### Reason
7842 Not all classes will necessarily support all interfaces, and not all callers will necessarily want to deal with all operations.
7843 Especially to break apart monolithic interfaces into "aspects" of behavior supported by a given derived class.
7845 ##### Example
7847     class iostream : public istream, public ostream {   // very simplified
7848         // ...
7849     };
7851 `istream` provides the interface to input operations; `ostream` provides the interface to output operations.
7852 `iostream` provides the union of the `istream` and `ostream` interfaces and the synchronization needed to allow both on a single stream.
7854 ##### Note
7856 This is a very common use of inheritance because the need for multiple different interfaces to an implementation is common
7857 and such interfaces are often not easily or naturally organized into a single-rooted hierarchy.
7859 ##### Note
7861 Such interfaces are typically abstract classes.
7863 ##### Enforcement
7867 ### <a name="Rh-mi-implementation"></a>C.136: Use multiple inheritance to represent the union of implementation attributes
7869 ##### Reason
7871 Some forms of mixins have state and often operations on that state.
7872 If the operations are virtual the use of inheritance is necessary, if not using inheritance can avoid boilerplate and forwarding.
7874 ##### Example
7876     class iostream : public istream, public ostream {   // very simplified
7877         // ...
7878     };
7880 `istream` provides the interface to input operations (and some data); `ostream` provides the interface to output operations (and some data).
7881 `iostream` provides the union of the `istream` and `ostream` interfaces and the synchronization needed to allow both on a single stream.
7883 ##### Note
7885 This a relatively rare use because implementation can often be organized into a single-rooted hierarchy.
7887 ##### Example
7889 Sometimes, an "implementation attribute" is more like a "mixin" that determine the behavior of an implementation and inject
7890 members to enable the implementation of the policies it requires.
7891 For example, see `std::enable_shared_from_this`
7892 or various bases from boost.intrusive (e.g. `list_base_hook` or `intrusive_ref_counter`).
7894 ##### Enforcement
7898 ### <a name="Rh-vbase"></a>C.137: Use `virtual` bases to avoid overly general base classes
7900 ##### Reason
7902  Allow separation of shared data and interface.
7903  To avoid all shared data to being put into an ultimate base class.
7905 ##### Example
7907     struct Interface {
7908         virtual void f();
7909         virtual int g();
7910         // ... no data here ...
7911     };
7913     class Utility {  // with data
7914         void utility1();
7915         virtual void utility2();    // customization point
7916     public:
7917         int x;
7918         int y;
7919     };
7921     class Derive1 : public Interface, virtual protected Utility {
7922         // override Interface functions
7923         // Maybe override Utility virtual functions
7924         // ...
7925     };
7927     class Derive2 : public Interface, virtual protected Utility {
7928         // override Interface functions
7929         // Maybe override Utility virtual functions
7930         // ...
7931     };
7933 Factoring out `Utility` makes sense if many derived classes share significant "implementation details."
7936 ##### Note
7938 Obviously, the example is too "theoretical", but it is hard to find a *small* realistic example.
7939 `Interface` is the root of an [interface hierarchy](#Rh-abstract)
7940 and `Utility` is the root of an [implementation hierarchy](#Rh-kind).
7941 Here is [a slightly more realistic example](https://www.quora.com/What-are-the-uses-and-advantages-of-virtual-base-class-in-C%2B%2B/answer/Lance-Diduck) with an explanation.
7943 ##### Note
7945 Often, linearization of a hierarchy is a better solution.
7947 ##### Enforcement
7949 Flag mixed interface and implementation hierarchies.
7951 ### <a name="Rh-using"></a>C.138: Create an overload set for a derived class and its bases with `using`
7953 ##### Reason
7955 Without a using declaration, member functions in the derived class hide the entire inherited overload sets.
7957 ##### Example, bad
7959     #include <iostream>
7960     class B {
7961     public:
7962         virtual int f(int i) { std::cout << "f(int): "; return i; }
7963         virtual double f(double d) { std::cout << "f(double): "; return d; }
7964         virtual ~B() = default;
7965     };
7966     class D: public B {
7967     public:
7968         int f(int i) override { std::cout << "f(int): "; return i + 1; }
7969     };
7970     int main()
7971     {
7972         D d;
7973         std::cout << d.f(2) << '\n';   // prints "f(int): 3"
7974         std::cout << d.f(2.3) << '\n'; // prints "f(int): 3"
7975     }
7977 ##### Example, good
7979     class D: public B {
7980     public:
7981         int f(int i) override { std::cout << "f(int): "; return i + 1; }
7982         using B::f; // exposes f(double)
7983     };
7985 ##### Note
7987 This issue affects both virtual and non-virtual member functions
7989 For variadic bases, C++17 introduced a variadic form of the using-declaration,
7991     template<class... Ts>
7992     struct Overloader : Ts... {
7993         using Ts::operator()...; // exposes operator() from every base
7994     };
7996 ##### Enforcement
7998 Diagnose name hiding
8000 ### <a name="Rh-final"></a>C.139: Use `final` on classes sparingly
8002 ##### Reason
8004 Capping a hierarchy with `final` classes is rarely needed for logical reasons and can be damaging to the extensibility of a hierarchy.
8006 ##### Example, bad
8008     class Widget { /* ... */ };
8010     // nobody will ever want to improve My_widget (or so you thought)
8011     class My_widget final : public Widget { /* ... */ };
8013     class My_improved_widget : public My_widget { /* ... */ };  // error: can't do that
8015 ##### Note
8017 Not every class is meant to be a base class.
8018 Most standard-library classes are examples of that (e.g., `std::vector` and `std::string` are not designed to be derived from).
8019 This rule is about using `final` on classes with virtual functions meant to be interfaces for a class hierarchy.
8021 ##### Note
8023 Capping an individual virtual function with `final` is error-prone as `final` can easily be overlooked when defining/overriding a set of functions.
8024 Fortunately, the compiler catches such mistakes: You cannot re-declare/re-open a `final` member in a derived class.
8026 ##### Note
8028 Claims of performance improvements from `final` should be substantiated.
8029 Too often, such claims are based on conjecture or experience with other languages.
8031 There are examples where `final` can be important for both logical and performance reasons.
8032 One example is a performance-critical AST hierarchy in a compiler or language analysis tool.
8033 New derived classes are not added every year and only by library implementers.
8034 However, misuses are (or at least have been) far more common.
8036 ##### Enforcement
8038 Flag uses of `final` on classes.
8041 ### <a name="Rh-virtual-default-arg"></a>C.140: Do not provide different default arguments for a virtual function and an overrider
8043 ##### Reason
8045 That can cause confusion: An overrider does not inherit default arguments.
8047 ##### Example, bad
8049     class Base {
8050     public:
8051         virtual int multiply(int value, int factor = 2) = 0;
8052         virtual ~Base() = default;
8053     };
8055     class Derived : public Base {
8056     public:
8057         int multiply(int value, int factor = 10) override;
8058     };
8060     Derived d;
8061     Base& b = d;
8063     b.multiply(10);  // these two calls will call the same function but
8064     d.multiply(10);  // with different arguments and so different results
8066 ##### Enforcement
8068 Flag default arguments on virtual functions if they differ between base and derived declarations.
8070 ## C.hier-access: Accessing objects in a hierarchy
8072 ### <a name="Rh-poly"></a>C.145: Access polymorphic objects through pointers and references
8074 ##### Reason
8076 If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.
8078 ##### Example
8080     struct B { int a; virtual int f(); virtual ~B() = default };
8081     struct D : B { int b; int f() override; };
8083     void use(B b)
8084     {
8085         D d;
8086         B b2 = d;   // slice
8087         B b3 = b;
8088     }
8090     void use2()
8091     {
8092         D d;
8093         use(d);   // slice
8094     }
8096 Both `d`s are sliced.
8098 ##### Exception
8100 You can safely access a named polymorphic object in the scope of its definition, just don't slice it.
8102     void use3()
8103     {
8104         D d;
8105         d.f();   // OK
8106     }
8108 ##### See also
8110 [A polymorphic class should suppress copying](#Rc-copy-virtual)
8112 ##### Enforcement
8114 Flag all slicing.
8116 ### <a name="Rh-dynamic_cast"></a>C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable
8118 ##### Reason
8120 `dynamic_cast` is checked at run time.
8122 ##### Example
8124     struct B {   // an interface
8125         virtual void f();
8126         virtual void g();
8127         virtual ~B();
8128     };
8130     struct D : B {   // a wider interface
8131         void f() override;
8132         virtual void h();
8133     };
8135     void user(B* pb)
8136     {
8137         if (D* pd = dynamic_cast<D*>(pb)) {
8138             // ... use D's interface ...
8139         }
8140         else {
8141             // ... make do with B's interface ...
8142         }
8143     }
8145 Use of the other casts can violate type safety and cause the program to access a variable that is actually of type `X` to be accessed as if it were of an unrelated type `Z`:
8147     void user2(B* pb)   // bad
8148     {
8149         D* pd = static_cast<D*>(pb);    // I know that pb really points to a D; trust me
8150         // ... use D's interface ...
8151     }
8153     void user3(B* pb)    // unsafe
8154     {
8155         if (some_condition) {
8156             D* pd = static_cast<D*>(pb);   // I know that pb really points to a D; trust me
8157             // ... use D's interface ...
8158         }
8159         else {
8160             // ... make do with B's interface ...
8161         }
8162     }
8164     void f()
8165     {
8166         B b;
8167         user(&b);   // OK
8168         user2(&b);  // bad error
8169         user3(&b);  // OK *if* the programmer got the some_condition check right
8170     }
8172 ##### Note
8174 Like other casts, `dynamic_cast` is overused.
8175 [Prefer virtual functions to casting](#Rh-use-virtual).
8176 Prefer [static polymorphism](#???) to hierarchy navigation where it is possible (no run-time resolution necessary)
8177 and reasonably convenient.
8179 ##### Note
8181 Some people use `dynamic_cast` where a `typeid` would have been more appropriate;
8182 `dynamic_cast` is a general "is kind of" operation for discovering the best interface to an object,
8183 whereas `typeid` is a "give me the exact type of this object" operation to discover the actual type of an object.
8184 The latter is an inherently simpler operation that ought to be faster.
8185 The latter (`typeid`) is easily hand-crafted if necessary (e.g., if working on a system where RTTI is -- for some reason -- prohibited),
8186 the former (`dynamic_cast`) is far harder to implement correctly in general.
8188 Consider:
8190     struct B {
8191         const char* name {"B"};
8192         // if pb1->id() == pb2->id() *pb1 is the same type as *pb2
8193         virtual const char* id() const { return name; }
8194         // ...
8195     };
8197     struct D : B {
8198         const char* name {"D"};
8199         const char* id() const override { return name; }
8200         // ...
8201     };
8203     void use()
8204     {
8205         B* pb1 = new B;
8206         B* pb2 = new D;
8208         cout << pb1->id(); // "B"
8209         cout << pb2->id(); // "D"
8212         if (pb2->id() == "D") {         // looks innocent
8213             D* pd = static_cast<D*>(pb2);
8214             // ...
8215         }
8216         // ...
8217     }
8219 The result of `pb2->id() == "D"` is actually implementation defined.
8220 We added it to warn of the dangers of home-brew RTTI.
8221 This code might work as expected for years, just to fail on a new machine, new compiler, or a new linker that does not unify character literals.
8223 If you implement your own RTTI, be careful.
8225 ##### Exception
8227 If your implementation provided a really slow `dynamic_cast`, you might have to use a workaround.
8228 However, all workarounds that cannot be statically resolved involve explicit casting (typically `static_cast`) and are error-prone.
8229 You will basically be crafting your own special-purpose `dynamic_cast`.
8230 So, first make sure that your `dynamic_cast` really is as slow as you think it is (there are a fair number of unsupported rumors about)
8231 and that your use of `dynamic_cast` is really performance critical.
8233 We are of the opinion that current implementations of `dynamic_cast` are unnecessarily slow.
8234 For example, under suitable conditions, it is possible to perform a `dynamic_cast` in [fast constant time](http://www.stroustrup.com/fast_dynamic_casting.pdf).
8235 However, compatibility makes changes difficult even if all agree that an effort to optimize is worthwhile.
8237 In very rare cases, if you have measured that the `dynamic_cast` overhead is material, you have other means to statically guarantee that a downcast will succeed (e.g., you are using CRTP carefully), and there is no virtual inheritance involved, consider tactically resorting `static_cast` with a prominent comment and disclaimer summarizing this paragraph and that human attention is needed under maintenance because the type system can't verify correctness. Even so, in our experience such "I know what I'm doing" situations are still a known bug source.
8239 ##### Exception
8241 Consider:
8243     template<typename B>
8244     class Dx : B {
8245         // ...
8246     };
8248 ##### Enforcement
8250 * Flag all uses of `static_cast` for downcasts, including C-style casts that perform a `static_cast`.
8251 * This rule is part of the [type-safety profile](#Pro-type-downcast).
8253 ### <a name="Rh-ref-cast"></a>C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error
8255 ##### Reason
8257 Casting to a reference expresses that you intend to end up with a valid object, so the cast must succeed. `dynamic_cast` will then throw if it does not succeed.
8259 ##### Example
8261     std::string f(Base& b)
8262     {
8263         return dynamic_cast<Derived&>(b).to_string();
8264     }
8266 ##### Enforcement
8270 ### <a name="Rh-ptr-cast"></a>C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative
8272 ##### Reason
8274 The `dynamic_cast` conversion allows to test whether a pointer is pointing at a polymorphic object that has a given class in its hierarchy. Since failure to find the class merely returns a null value, it can be tested during run time. This allows writing code that can choose alternative paths depending on the results.
8276 Contrast with [C.147](#Rh-ref-cast), where failure is an error, and should not be used for conditional execution.
8278 ##### Example
8280 The example below describes the `add` function of a `Shape_owner` that takes ownership of constructed `Shape` objects. The objects are also sorted into views, according to their geometric attributes.
8281 In this example, `Shape` does not inherit from `Geometric_attributes`. Only its subclasses do.
8283     void add(Shape* const item)
8284     {
8285       // Ownership is always taken
8286       owned_shapes.emplace_back(item);
8288       // Check the Geometric_attributes and add the shape to none/one/some/all of the views
8290       if (auto even = dynamic_cast<Even_sided*>(item))
8291       {
8292         view_of_evens.emplace_back(even);
8293       }
8295       if (auto trisym = dynamic_cast<Trilaterally_symmetrical*>(item))
8296       {
8297         view_of_trisyms.emplace_back(trisym);
8298       }
8299     }
8301 ##### Notes
8303 A failure to find the required class will cause `dynamic_cast` to return a null value, and de-referencing a null-valued pointer will lead to undefined behavior.
8304 Therefore the result of the `dynamic_cast` should always be treated as if it might contain a null value, and tested.
8306 ##### Enforcement
8308 * (Complex) Unless there is a null test on the result of a `dynamic_cast` of a pointer type, warn upon dereference of the pointer.
8310 ### <a name="Rh-smart"></a>C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`
8312 ##### Reason
8314 Avoid resource leaks.
8316 ##### Example
8318     void use(int i)
8319     {
8320         auto p = new int {7};           // bad: initialize local pointers with new
8321         auto q = make_unique<int>(9);   // ok: guarantee the release of the memory-allocated for 9
8322         if (0 < i) return;              // maybe return and leak
8323         delete p;                       // too late
8324     }
8326 ##### Enforcement
8328 * Flag initialization of a naked pointer with the result of a `new`
8329 * Flag `delete` of local variable
8331 ### <a name="Rh-make_unique"></a>C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s
8333 See [R.23](#Rr-make_unique)
8335 ### <a name="Rh-make_shared"></a>C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s
8337 See [R.22](#Rr-make_shared)
8339 ### <a name="Rh-array"></a>C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
8341 ##### Reason
8343 Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.
8345 ##### Example
8347     struct B { int x; };
8348     struct D : B { int y; };
8350     void use(B*);
8352     D a[] = {{1, 2}, {3, 4}, {5, 6}};
8353     B* p = a;     // bad: a decays to &a[0] which is converted to a B*
8354     p[1].x = 7;   // overwrite a[0].y
8356     use(a);       // bad: a decays to &a[0] which is converted to a B*
8358 ##### Enforcement
8360 * Flag all combinations of array decay and base to derived conversions.
8361 * Pass an array as a `span` rather than as a pointer, and don't let the array name suffer a derived-to-base conversion before getting into the `span`
8364 ### <a name="Rh-use-virtual"></a>C.153: Prefer virtual function to casting
8366 ##### Reason
8368 A virtual function call is safe, whereas casting is error-prone.
8369 A virtual function call reaches the most derived function, whereas a cast might reach an intermediate class and therefore
8370 give a wrong result (especially as a hierarchy is modified during maintenance).
8372 ##### Example
8374     ???
8376 ##### Enforcement
8378 See [C.146](#Rh-dynamic_cast) and ???
8380 ## <a name="SS-overload"></a>C.over: Overloading and overloaded operators
8382 You can overload ordinary functions, function templates, and operators.
8383 You cannot overload function objects.
8385 Overload rule summary:
8387 * [C.160: Define operators primarily to mimic conventional usage](#Ro-conventional)
8388 * [C.161: Use non-member functions for symmetric operators](#Ro-symmetric)
8389 * [C.162: Overload operations that are roughly equivalent](#Ro-equivalent)
8390 * [C.163: Overload only for operations that are roughly equivalent](#Ro-equivalent-2)
8391 * [C.164: Avoid implicit conversion operators](#Ro-conversion)
8392 * [C.165: Use `using` for customization points](#Ro-custom)
8393 * [C.166: Overload unary `&` only as part of a system of smart pointers and references](#Ro-address-of)
8394 * [C.167: Use an operator for an operation with its conventional meaning](#Ro-overload)
8395 * [C.168: Define overloaded operators in the namespace of their operands](#Ro-namespace)
8396 * [C.170: If you feel like overloading a lambda, use a generic lambda](#Ro-lambda)
8398 ### <a name="Ro-conventional"></a>C.160: Define operators primarily to mimic conventional usage
8400 ##### Reason
8402 Minimize surprises.
8404 ##### Example
8406     class X {
8407     public:
8408         // ...
8409         X& operator=(const X&); // member function defining assignment
8410         friend bool operator==(const X&, const X&); // == needs access to representation
8411                                                     // after a = b we have a == b
8412         // ...
8413     };
8415 Here, the conventional semantics is maintained: [Copies compare equal](#SS-copy).
8417 ##### Example, bad
8419     X operator+(X a, X b) { return a.v - b.v; }   // bad: makes + subtract
8421 ##### Note
8423 Non-member operators should be either friends or defined in [the same namespace as their operands](#Ro-namespace).
8424 [Binary operators should treat their operands equivalently](#Ro-symmetric).
8426 ##### Enforcement
8428 Possibly impossible.
8430 ### <a name="Ro-symmetric"></a>C.161: Use non-member functions for symmetric operators
8432 ##### Reason
8434 If you use member functions, you need two.
8435 Unless you use a non-member function for (say) `==`, `a == b` and `b == a` will be subtly different.
8437 ##### Example
8439     bool operator==(Point a, Point b) { return a.x == b.x && a.y == b.y; }
8441 ##### Enforcement
8443 Flag member operator functions.
8445 ### <a name="Ro-equivalent"></a>C.162: Overload operations that are roughly equivalent
8447 ##### Reason
8449 Having different names for logically equivalent operations on different argument types is confusing, leads to encoding type information in function names, and inhibits generic programming.
8451 ##### Example
8453 Consider:
8455     void print(int a);
8456     void print(int a, int base);
8457     void print(const string&);
8459 These three functions all print their arguments (appropriately). Conversely:
8461     void print_int(int a);
8462     void print_based(int a, int base);
8463     void print_string(const string&);
8465 These three functions all print their arguments (appropriately). Adding to the name just introduced verbosity and inhibits generic code.
8467 ##### Enforcement
8471 ### <a name="Ro-equivalent-2"></a>C.163: Overload only for operations that are roughly equivalent
8473 ##### Reason
8475 Having the same name for logically different functions is confusing and leads to errors when using generic programming.
8477 ##### Example
8479 Consider:
8481     void open_gate(Gate& g);   // remove obstacle from garage exit lane
8482     void fopen(const char* name, const char* mode);   // open file
8484 The two operations are fundamentally different (and unrelated) so it is good that their names differ. Conversely:
8486     void open(Gate& g);   // remove obstacle from garage exit lane
8487     void open(const char* name, const char* mode ="r");   // open file
8489 The two operations are still fundamentally different (and unrelated) but the names have been reduced to their (common) minimum, opening opportunities for confusion.
8490 Fortunately, the type system will catch many such mistakes.
8492 ##### Note
8494 Be particularly careful about common and popular names, such as `open`, `move`, `+`, and `==`.
8496 ##### Enforcement
8500 ### <a name="Ro-conversion"></a>C.164: Avoid implicit conversion operators
8502 ##### Reason
8504 Implicit conversions can be essential (e.g., `double` to `int`) but often cause surprises (e.g., `String` to C-style string).
8506 ##### Note
8508 Prefer explicitly named conversions until a serious need is demonstrated.
8509 By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion)
8510 and frequently needed. Do not introduce implicit conversions (through conversion operators or non-`explicit` constructors)
8511 just to gain a minor convenience.
8513 ##### Example
8515     struct S1 {
8516         string s;
8517         // ...
8518         operator char*() { return s.data(); }  // BAD, likely to cause surprises
8519     };
8521     struct S2 {
8522         string s;
8523         // ...
8524         explicit operator char*() { return s.data(); }
8525     };
8527     void f(S1 s1, S2 s2)
8528     {
8529         char* x1 = s1;     // OK, but can cause surprises in many contexts
8530         char* x2 = s2;     // error (and that's usually a good thing)
8531         char* x3 = static_cast<char*>(s2); // we can be explicit (on your head be it)
8532     }
8534 The surprising and potentially damaging implicit conversion can occur in arbitrarily hard-to spot contexts, e.g.,
8536     S1 ff();
8538     char* g()
8539     {
8540         return ff();
8541     }
8543 The string returned by `ff()` is destroyed before the returned pointer into it can be used.
8545 ##### Enforcement
8547 Flag all non-explicit conversion operators.
8549 ### <a name="Ro-custom"></a>C.165: Use `using` for customization points
8551 ##### Reason
8553 To find function objects and functions defined in a separate namespace to "customize" a common function.
8555 ##### Example
8557 Consider `swap`. It is a general (standard-library) function with a definition that will work for just about any type.
8558 However, it is desirable to define specific `swap()`s for specific types.
8559 For example, the general `swap()` will copy the elements of two `vector`s being swapped, whereas a good specific implementation will not copy elements at all.
8561     namespace N {
8562         My_type X { /* ... */ };
8563         void swap(X&, X&);   // optimized swap for N::X
8564         // ...
8565     }
8567     void f1(N::X& a, N::X& b)
8568     {
8569         std::swap(a, b);   // probably not what we wanted: calls std::swap()
8570     }
8572 The `std::swap()` in `f1()` does exactly what we asked it to do: it calls the `swap()` in namespace `std`.
8573 Unfortunately, that's probably not what we wanted.
8574 How do we get `N::X` considered?
8576     void f2(N::X& a, N::X& b)
8577     {
8578         swap(a, b);   // calls N::swap
8579     }
8581 But that might not be what we wanted for generic code.
8582 There, we typically want the specific function if it exists and the general function if not.
8583 This is done by including the general function in the lookup for the function:
8585     void f3(N::X& a, N::X& b)
8586     {
8587         using std::swap;  // make std::swap available
8588         swap(a, b);        // calls N::swap if it exists, otherwise std::swap
8589     }
8591 ##### Enforcement
8593 Unlikely, except for known customization points, such as `swap`.
8594 The problem is that the unqualified and qualified lookups both have uses.
8596 ### <a name="Ro-address-of"></a>C.166: Overload unary `&` only as part of a system of smart pointers and references
8598 ##### Reason
8600 The `&` operator is fundamental in C++.
8601 Many parts of the C++ semantics assume its default meaning.
8603 ##### Example
8605     class Ptr { // a somewhat smart pointer
8606         Ptr(X* pp) : p(pp) { /* check */ }
8607         X* operator->() { /* check */ return p; }
8608         X operator[](int i);
8609         X operator*();
8610     private:
8611         T* p;
8612     };
8614     class X {
8615         Ptr operator&() { return Ptr{this}; }
8616         // ...
8617     };
8619 ##### Note
8621 If you "mess with" operator `&` be sure that its definition has matching meanings for `->`, `[]`, `*`, and `.` on the result type.
8622 Note that operator `.` currently cannot be overloaded so a perfect system is impossible.
8623 We hope to remedy that: [Operator Dot (R2)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf).
8624 Note that `std::addressof()` always yields a built-in pointer.
8626 ##### Enforcement
8628 Tricky. Warn if `&` is user-defined without also defining `->` for the result type.
8630 ### <a name="Ro-overload"></a>C.167: Use an operator for an operation with its conventional meaning
8632 ##### Reason
8634 Readability. Convention. Reusability. Support for generic code
8636 ##### Example
8638     void cout_my_class(const My_class& c) // confusing, not conventional,not generic
8639     {
8640         std::cout << /* class members here */;
8641     }
8643     std::ostream& operator<<(std::ostream& os, const my_class& c) // OK
8644     {
8645         return os << /* class members here */;
8646     }
8648 By itself, `cout_my_class` would be OK, but it is not usable/composable with code that rely on the `<<` convention for output:
8650     My_class var { /* ... */ };
8651     // ...
8652     cout << "var = " << var << '\n';
8654 ##### Note
8656 There are strong and vigorous conventions for the meaning of most operators, such as
8658 * comparisons (`==`, `!=`, `<`, `<=`, `>`, `>=`, and `<=>`),
8659 * arithmetic operations (`+`, `-`, `*`, `/`, and `%`)
8660 * access operations (`.`, `->`, unary `*`, and `[]`)
8661 * assignment (`=`)
8663 Don't define those unconventionally and don't invent your own names for them.
8665 ##### Enforcement
8667 Tricky. Requires semantic insight.
8669 ### <a name="Ro-namespace"></a>C.168: Define overloaded operators in the namespace of their operands
8671 ##### Reason
8673 Readability.
8674 Ability for find operators using ADL.
8675 Avoiding inconsistent definition in different namespaces
8677 ##### Example
8679     struct S { };
8680     S operator+(S, S);   // OK: in the same namespace as S, and even next to S
8681     S s;
8683     S r = s + s;
8685 ##### Example
8687     namespace N {
8688         struct S { };
8689         S operator+(S, S);   // OK: in the same namespace as S, and even next to S
8690     }
8692     N::S s;
8694     S r = s + s;  // finds N::operator+() by ADL
8696 ##### Example, bad
8698     struct S { };
8699     S s;
8701     namespace N {
8702         bool operator!(S a) { return true; }
8703         bool not_s = !s;
8704     }
8706     namespace M {
8707         bool operator!(S a) { return false; }
8708         bool not_s = !s;
8709     }
8711 Here, the meaning of `!s` differs in `N` and `M`.
8712 This can be most confusing.
8713 Remove the definition of `namespace M` and the confusion is replaced by an opportunity to make the mistake.
8715 ##### Note
8717 If a binary operator is defined for two types that are defined in different namespaces, you cannot follow this rule.
8718 For example:
8720     Vec::Vector operator*(const Vec::Vector&, const Mat::Matrix&);
8722 This might be something best avoided.
8724 ##### See also
8726 This is a special case of the rule that [helper functions should be defined in the same namespace as their class](#Rc-helper).
8728 ##### Enforcement
8730 * Flag operator definitions that are not in the namespace of their operands
8732 ### <a name="Ro-lambda"></a>C.170: If you feel like overloading a lambda, use a generic lambda
8734 ##### Reason
8736 You cannot overload by defining two different lambdas with the same name.
8738 ##### Example
8740     void f(int);
8741     void f(double);
8742     auto f = [](char);   // error: cannot overload variable and function
8744     auto g = [](int) { /* ... */ };
8745     auto g = [](double) { /* ... */ };   // error: cannot overload variables
8747     auto h = [](auto) { /* ... */ };   // OK
8749 ##### Enforcement
8751 The compiler catches the attempt to overload a lambda.
8753 ## <a name="SS-union"></a>C.union: Unions
8755 A `union` is a `struct` where all members start at the same address so that it can hold only one member at a time.
8756 A `union` does not keep track of which member is stored so the programmer has to get it right;
8757 this is inherently error-prone, but there are ways to compensate.
8759 A type that is a `union` plus an indicator of which member is currently held is called a *tagged union*, a *discriminated union*, or a *variant*.
8761 Union rule summary:
8763 * [C.180: Use `union`s to save Memory](#Ru-union)
8764 * [C.181: Avoid "naked" `union`s](#Ru-naked)
8765 * [C.182: Use anonymous `union`s to implement tagged unions](#Ru-anonymous)
8766 * [C.183: Don't use a `union` for type punning](#Ru-pun)
8767 * ???
8769 ### <a name="Ru-union"></a>C.180: Use `union`s to save memory
8771 ##### Reason
8773 A `union` allows a single piece of memory to be used for different types of objects at different times.
8774 Consequently, it can be used to save memory when we have several objects that are never used at the same time.
8776 ##### Example
8778     union Value {
8779         int x;
8780         double d;
8781     };
8783     Value v = { 123 };  // now v holds an int
8784     cout << v.x << '\n';    // write 123
8785     v.d = 987.654;  // now v holds a double
8786     cout << v.d << '\n';    // write 987.654
8788 But heed the warning: [Avoid "naked" `union`s](#Ru-naked)
8790 ##### Example
8792     // Short-string optimization
8794     constexpr size_t buffer_size = 16; // Slightly larger than the size of a pointer
8796     class Immutable_string {
8797     public:
8798         Immutable_string(const char* str) :
8799             size(strlen(str))
8800         {
8801             if (size < buffer_size)
8802                 strcpy_s(string_buffer, buffer_size, str);
8803             else {
8804                 string_ptr = new char[size + 1];
8805                 strcpy_s(string_ptr, size + 1, str);
8806             }
8807         }
8809         ~Immutable_string()
8810         {
8811             if (size >= buffer_size)
8812                 delete[] string_ptr;
8813         }
8815         const char* get_str() const
8816         {
8817             return (size < buffer_size) ? string_buffer : string_ptr;
8818         }
8820     private:
8821         // If the string is short enough, we store the string itself
8822         // instead of a pointer to the string.
8823         union {
8824             char* string_ptr;
8825             char string_buffer[buffer_size];
8826         };
8828         const size_t size;
8829     };
8831 ##### Enforcement
8835 ### <a name="Ru-naked"></a>C.181: Avoid "naked" `union`s
8837 ##### Reason
8839 A *naked union* is a union without an associated indicator which member (if any) it holds,
8840 so that the programmer has to keep track.
8841 Naked unions are a source of type errors.
8843 ##### Example, bad
8845     union Value {
8846         int x;
8847         double d;
8848     };
8850     Value v;
8851     v.d = 987.654;  // v holds a double
8853 So far, so good, but we can easily misuse the `union`:
8855     cout << v.x << '\n';    // BAD, undefined behavior: v holds a double, but we read it as an int
8857 Note that the type error happened without any explicit cast.
8858 When we tested that program the last value printed was `1683627180` which is the integer value for the bit pattern for `987.654`.
8859 What we have here is an "invisible" type error that happens to give a result that could easily look innocent.
8861 And, talking about "invisible", this code produced no output:
8863     v.x = 123;
8864     cout << v.d << '\n';    // BAD: undefined behavior
8866 ##### Alternative
8868 Wrap a `union` in a class together with a type field.
8870 The C++17 `variant` type (found in `<variant>`) does that for you:
8872     variant<int, double> v;
8873     v = 123;        // v holds an int
8874     int x = get<int>(v);
8875     v = 123.456;    // v holds a double
8876     double w = get<double>(v);
8878 ##### Enforcement
8882 ### <a name="Ru-anonymous"></a>C.182: Use anonymous `union`s to implement tagged unions
8884 ##### Reason
8886 A well-designed tagged union is type safe.
8887 An *anonymous* union simplifies the definition of a class with a (tag, union) pair.
8889 ##### Example
8891 This example is mostly borrowed from TC++PL4 pp216-218.
8892 You can look there for an explanation.
8894 The code is somewhat elaborate.
8895 Handling a type with user-defined assignment and destructor is tricky.
8896 Saving programmers from having to write such code is one reason for including `variant` in the standard.
8898     class Value { // two alternative representations represented as a union
8899     private:
8900         enum class Tag { number, text };
8901         Tag type; // discriminant
8903         union { // representation (note: anonymous union)
8904             int i;
8905             string s; // string has default constructor, copy operations, and destructor
8906         };
8907     public:
8908         struct Bad_entry { }; // used for exceptions
8910         ~Value();
8911         Value& operator=(const Value&);   // necessary because of the string variant
8912         Value(const Value&);
8913         // ...
8914         int number() const;
8915         string text() const;
8917         void set_number(int n);
8918         void set_text(const string&);
8919         // ...
8920     };
8922     int Value::number() const
8923     {
8924         if (type != Tag::number) throw Bad_entry{};
8925         return i;
8926     }
8928     string Value::text() const
8929     {
8930         if (type != Tag::text) throw Bad_entry{};
8931         return s;
8932     }
8934     void Value::set_number(int n)
8935     {
8936         if (type == Tag::text) {
8937             s.~string();      // explicitly destroy string
8938             type = Tag::number;
8939         }
8940         i = n;
8941     }
8943     void Value::set_text(const string& ss)
8944     {
8945         if (type == Tag::text)
8946             s = ss;
8947         else {
8948             new(&s) string{ss};   // placement new: explicitly construct string
8949             type = Tag::text;
8950         }
8951     }
8953     Value& Value::operator=(const Value& e)   // necessary because of the string variant
8954     {
8955         if (type == Tag::text && e.type == Tag::text) {
8956             s = e.s;    // usual string assignment
8957             return *this;
8958         }
8960         if (type == Tag::text) s.~string(); // explicit destroy
8962         switch (e.type) {
8963         case Tag::number:
8964             i = e.i;
8965             break;
8966         case Tag::text:
8967             new(&s) string(e.s);   // placement new: explicit construct
8968         }
8970         type = e.type;
8971         return *this;
8972     }
8974     Value::~Value()
8975     {
8976         if (type == Tag::text) s.~string(); // explicit destroy
8977     }
8979 ##### Enforcement
8983 ### <a name="Ru-pun"></a>C.183: Don't use a `union` for type punning
8985 ##### Reason
8987 It is undefined behavior to read a `union` member with a different type from the one with which it was written.
8988 Such punning is invisible, or at least harder to spot than using a named cast.
8989 Type punning using a `union` is a source of errors.
8991 ##### Example, bad
8993     union Pun {
8994         int x;
8995         unsigned char c[sizeof(int)];
8996     };
8998 The idea of `Pun` is to be able to look at the character representation of an `int`.
9000     void bad(Pun& u)
9001     {
9002         u.x = 'x';
9003         cout << u.c[0] << '\n';     // undefined behavior
9004     }
9006 If you wanted to see the bytes of an `int`, use a (named) cast:
9008     void if_you_must_pun(int& x)
9009     {
9010         auto p = reinterpret_cast<std::byte*>(&x);
9011         cout << p[0] << '\n';     // OK; better
9012         // ...
9013     }
9015 Accessing the result of a `reinterpret_cast` from the object's declared type to `char*`, `unsigned char*`, or `std::byte*` is defined behavior. (Using `reinterpret_cast` is discouraged,
9016 but at least we can see that something tricky is going on.)
9018 ##### Note
9020 Unfortunately, `union`s are commonly used for type punning.
9021 We don't consider "sometimes, it works as expected" a conclusive argument.
9023 C++17 introduced a distinct type `std::byte` to facilitate operations on raw object representation.  Use that type instead of `unsigned char` or `char` for these operations.
9025 ##### Enforcement
9031 # <a name="S-enum"></a>Enum: Enumerations
9033 Enumerations are used to define sets of integer values and for defining types for such sets of values.
9034 There are two kinds of enumerations, "plain" `enum`s and `class enum`s.
9036 Enumeration rule summary:
9038 * [Enum.1: Prefer enumerations over macros](#Renum-macro)
9039 * [Enum.2: Use enumerations to represent sets of related named constants](#Renum-set)
9040 * [Enum.3: Prefer `enum class`es over "plain" `enum`s](#Renum-class)
9041 * [Enum.4: Define operations on enumerations for safe and simple use](#Renum-oper)
9042 * [Enum.5: Don't use `ALL_CAPS` for enumerators](#Renum-caps)
9043 * [Enum.6: Avoid unnamed enumerations](#Renum-unnamed)
9044 * [Enum.7: Specify the underlying type of an enumeration only when necessary](#Renum-underlying)
9045 * [Enum.8: Specify enumerator values only when necessary](#Renum-value)
9047 ### <a name="Renum-macro"></a>Enum.1: Prefer enumerations over macros
9049 ##### Reason
9051 Macros do not obey scope and type rules. Also, macro names are removed during preprocessing and so usually don't appear in tools like debuggers.
9053 ##### Example
9055 First some bad old code:
9057     // webcolors.h (third party header)
9058     #define RED   0xFF0000
9059     #define GREEN 0x00FF00
9060     #define BLUE  0x0000FF
9062     // productinfo.h
9063     // The following define product subtypes based on color
9064     #define RED    0
9065     #define PURPLE 1
9066     #define BLUE   2
9068     int webby = BLUE;   // webby == 2; probably not what was desired
9070 Instead use an `enum`:
9072     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
9073     enum class Product_info { red = 0, purple = 1, blue = 2 };
9075     int webby = blue;   // error: be specific
9076     Web_color webby = Web_color::blue;
9078 We used an `enum class` to avoid name clashes.
9080 ##### Note
9082 Also consider `constexpr` and `const inline` variables.
9084 ##### Enforcement
9086 Flag macros that define integer values. Use `enum` or `const inline` or another non-macro alternative instead.
9089 ### <a name="Renum-set"></a>Enum.2: Use enumerations to represent sets of related named constants
9091 ##### Reason
9093 An enumeration shows the enumerators to be related and can be a named type.
9097 ##### Example
9099     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
9102 ##### Note
9104 Switching on an enumeration is common and the compiler can warn against unusual patterns of case labels. For example:
9106     enum class Product_info { red = 0, purple = 1, blue = 2 };
9108     void print(Product_info inf)
9109     {
9110         switch (inf) {
9111         case Product_info::red: cout << "red"; break;
9112         case Product_info::purple: cout << "purple"; break;
9113         }
9114     }
9116 Such off-by-one `switch`-statements are often the results of an added enumerator and insufficient testing.
9118 ##### Enforcement
9120 * Flag `switch`-statements where the `case`s cover most but not all enumerators of an enumeration.
9121 * Flag `switch`-statements where the `case`s cover a few enumerators of an enumeration, but there is no `default`.
9124 ### <a name="Renum-class"></a>Enum.3: Prefer class enums over "plain" enums
9126 ##### Reason
9128 To minimize surprises: traditional enums convert to int too readily.
9130 ##### Example
9132     void Print_color(int color);
9134     enum Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
9135     enum Product_info { red = 0, purple = 1, blue = 2 };
9137     Web_color webby = Web_color::blue;
9139     // Clearly at least one of these calls is buggy.
9140     Print_color(webby);
9141     Print_color(Product_info::blue);
9143 Instead use an `enum class`:
9145     void Print_color(int color);
9147     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
9148     enum class Product_info { red = 0, purple = 1, blue = 2 };
9150     Web_color webby = Web_color::blue;
9151     Print_color(webby);  // Error: cannot convert Web_color to int.
9152     Print_color(Product_info::red);  // Error: cannot convert Product_info to int.
9154 ##### Enforcement
9156 (Simple) Warn on any non-class `enum` definition.
9158 ### <a name="Renum-oper"></a>Enum.4: Define operations on enumerations for safe and simple use
9160 ##### Reason
9162 Convenience of use and avoidance of errors.
9164 ##### Example
9166     enum class Day { mon, tue, wed, thu, fri, sat, sun };
9168     Day& operator++(Day& d)
9169     {
9170         return d = (d == Day::sun) ? Day::mon : static_cast<Day>(static_cast<int>(d)+1);
9171     }
9173     Day today = Day::sat;
9174     Day tomorrow = ++today;
9176 The use of a `static_cast` is not pretty, but
9178     Day& operator++(Day& d)
9179     {
9180         return d = (d == Day::sun) ? Day::mon : Day{++d};    // error
9181     }
9183 is an infinite recursion, and writing it without a cast, using a `switch` on all cases is long-winded.
9186 ##### Enforcement
9188 Flag repeated expressions cast back into an enumeration.
9191 ### <a name="Renum-caps"></a>Enum.5: Don't use `ALL_CAPS` for enumerators
9193 ##### Reason
9195 Avoid clashes with macros.
9197 ##### Example, bad
9199      // webcolors.h (third party header)
9200     #define RED   0xFF0000
9201     #define GREEN 0x00FF00
9202     #define BLUE  0x0000FF
9204     // productinfo.h
9205     // The following define product subtypes based on color
9207     enum class Product_info { RED, PURPLE, BLUE };   // syntax error
9209 ##### Enforcement
9211 Flag ALL_CAPS enumerators.
9213 ### <a name="Renum-unnamed"></a>Enum.6: Avoid unnamed enumerations
9215 ##### Reason
9217 If you can't name an enumeration, the values are not related
9219 ##### Example, bad
9221     enum { red = 0xFF0000, scale = 4, is_signed = 1 };
9223 Such code is not uncommon in code written before there were convenient alternative ways of specifying integer constants.
9225 ##### Alternative
9227 Use `constexpr` values instead. For example:
9229     constexpr int red = 0xFF0000;
9230     constexpr short scale = 4;
9231     constexpr bool is_signed = true;
9233 ##### Enforcement
9235 Flag unnamed enumerations.
9238 ### <a name="Renum-underlying"></a>Enum.7: Specify the underlying type of an enumeration only when necessary
9240 ##### Reason
9242 The default is the easiest to read and write.
9243 `int` is the default integer type.
9244 `int` is compatible with C `enum`s.
9246 ##### Example
9248     enum class Direction : char { n, s, e, w,
9249                                   ne, nw, se, sw };  // underlying type saves space
9251     enum class Web_color : int32_t { red   = 0xFF0000,
9252                                      green = 0x00FF00,
9253                                      blue  = 0x0000FF };  // underlying type is redundant
9255 ##### Note
9257 Specifying the underlying type is necessary to forward-declare an enum or enum class:
9259     enum Flags : char;
9261     void f(Flags);
9263     // ....
9265     enum Flags : char { /* ... */ };
9267 or to ensure that values of that type have a specified bit-precision:
9269     enum Bitboard : uint64_t { /* ... */ };
9271 ##### Enforcement
9273 ????
9276 ### <a name="Renum-value"></a>Enum.8: Specify enumerator values only when necessary
9278 ##### Reason
9280 It's the simplest.
9281 It avoids duplicate enumerator values.
9282 The default gives a consecutive set of values that is good for `switch`-statement implementations.
9284 ##### Example
9286     enum class Col1 { red, yellow, blue };
9287     enum class Col2 { red = 1, yellow = 2, blue = 2 }; // typo
9288     enum class Month { jan = 1, feb, mar, apr, may, jun,
9289                        jul, august, sep, oct, nov, dec }; // starting with 1 is conventional
9290     enum class Base_flag { dec = 1, oct = dec << 1, hex = dec << 2 }; // set of bits
9292 Specifying values is necessary to match conventional values (e.g., `Month`)
9293 and where consecutive values are undesirable (e.g., to get separate bits as in `Base_flag`).
9295 ##### Enforcement
9297 * Flag duplicate enumerator values
9298 * Flag explicitly specified all-consecutive enumerator values
9301 # <a name="S-resource"></a>R: Resource management
9303 This section contains rules related to resources.
9304 A resource is anything that must be acquired and (explicitly or implicitly) released, such as memory, file handles, sockets, and locks.
9305 The reason it must be released is typically that it can be in short supply, so even delayed release might do harm.
9306 The fundamental aim is to ensure that we don't leak any resources and that we don't hold a resource longer than we need to.
9307 An entity that is responsible for releasing a resource is called an owner.
9309 There are a few cases where leaks can be acceptable or even optimal:
9310 If you are writing a program that simply produces an output based on an input and the amount of memory needed is proportional to the size of the input, the optimal strategy (for performance and ease of programming) is sometimes simply never to delete anything.
9311 If you have enough memory to handle your largest input, leak away, but be sure to give a good error message if you are wrong.
9312 Here, we ignore such cases.
9314 * Resource management rule summary:
9316   * [R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)](#Rr-raii)
9317   * [R.2: In interfaces, use raw pointers to denote individual objects (only)](#Rr-use-ptr)
9318   * [R.3: A raw pointer (a `T*`) is non-owning](#Rr-ptr)
9319   * [R.4: A raw reference (a `T&`) is non-owning](#Rr-ref)
9320   * [R.5: Prefer scoped objects, don't heap-allocate unnecessarily](#Rr-scoped)
9321   * [R.6: Avoid non-`const` global variables](#Rr-global)
9323 * Allocation and deallocation rule summary:
9325   * [R.10: Avoid `malloc()` and `free()`](#Rr-mallocfree)
9326   * [R.11: Avoid calling `new` and `delete` explicitly](#Rr-newdelete)
9327   * [R.12: Immediately give the result of an explicit resource allocation to a manager object](#Rr-immediate-alloc)
9328   * [R.13: Perform at most one explicit resource allocation in a single expression statement](#Rr-single-alloc)
9329   * [R.14: Avoid `[]` parameters, prefer `span`](#Rr-ap)
9330   * [R.15: Always overload matched allocation/deallocation pairs](#Rr-pair)
9332 * <a name="Rr-summary-smartptrs"></a>Smart pointer rule summary:
9334   * [R.20: Use `unique_ptr` or `shared_ptr` to represent ownership](#Rr-owner)
9335   * [R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership](#Rr-unique)
9336   * [R.22: Use `make_shared()` to make `shared_ptr`s](#Rr-make_shared)
9337   * [R.23: Use `make_unique()` to make `unique_ptr`s](#Rr-make_unique)
9338   * [R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s](#Rr-weak_ptr)
9339   * [R.30: Take smart pointers as parameters only to explicitly express lifetime semantics](#Rr-smartptrparam)
9340   * [R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`](#Rr-smart)
9341   * [R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`](#Rr-uniqueptrparam)
9342   * [R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the `widget`](#Rr-reseat)
9343   * [R.34: Take a `shared_ptr<widget>` parameter to express shared ownership](#Rr-sharedptrparam-owner)
9344   * [R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer](#Rr-sharedptrparam)
9345   * [R.36: Take a `const shared_ptr<widget>&` parameter to express that it might retain a reference count to the object ???](#Rr-sharedptrparam-const)
9346   * [R.37: Do not pass a pointer or reference obtained from an aliased smart pointer](#Rr-smartptrget)
9348 ### <a name="Rr-raii"></a>R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)
9350 ##### Reason
9352 To avoid leaks and the complexity of manual resource management.
9353 C++'s language-enforced constructor/destructor symmetry mirrors the symmetry inherent in resource acquire/release function pairs such as `fopen`/`fclose`, `lock`/`unlock`, and `new`/`delete`.
9354 Whenever you deal with a resource that needs paired acquire/release function calls, encapsulate that resource in an object that enforces pairing for you -- acquire the resource in its constructor, and release it in its destructor.
9356 ##### Example, bad
9358 Consider:
9360     void send(X* x, string_view destination)
9361     {
9362         auto port = open_port(destination);
9363         my_mutex.lock();
9364         // ...
9365         send(port, x);
9366         // ...
9367         my_mutex.unlock();
9368         close_port(port);
9369         delete x;
9370     }
9372 In this code, you have to remember to `unlock`, `close_port`, and `delete` on all paths, and do each exactly once.
9373 Further, if any of the code marked `...` throws an exception, then `x` is leaked and `my_mutex` remains locked.
9375 ##### Example
9377 Consider:
9379     void send(unique_ptr<X> x, string_view destination)  // x owns the X
9380     {
9381         Port port{destination};            // port owns the PortHandle
9382         lock_guard<mutex> guard{my_mutex}; // guard owns the lock
9383         // ...
9384         send(port, x);
9385         // ...
9386     } // automatically unlocks my_mutex and deletes the pointer in x
9388 Now all resource cleanup is automatic, performed once on all paths whether or not there is an exception. As a bonus, the function now advertises that it takes over ownership of the pointer.
9390 What is `Port`? A handy wrapper that encapsulates the resource:
9392     class Port {
9393         PortHandle port;
9394     public:
9395         Port(string_view destination) : port{open_port(destination)} { }
9396         ~Port() { close_port(port); }
9397         operator PortHandle() { return port; }
9399         // port handles can't usually be cloned, so disable copying and assignment if necessary
9400         Port(const Port&) = delete;
9401         Port& operator=(const Port&) = delete;
9402     };
9404 ##### Note
9406 Where a resource is "ill-behaved" in that it isn't represented as a class with a destructor, wrap it in a class or use [`finally`](#Re-finally)
9408 **See also**: [RAII](#Re-raii)
9410 ### <a name="Rr-use-ptr"></a>R.2: In interfaces, use raw pointers to denote individual objects (only)
9412 ##### Reason
9414 Arrays are best represented by a container type (e.g., `vector` (owning)) or a `span` (non-owning).
9415 Such containers and views hold sufficient information to do range checking.
9417 ##### Example, bad
9419     void f(int* p, int n)   // n is the number of elements in p[]
9420     {
9421         // ...
9422         p[2] = 7;   // bad: subscript raw pointer
9423         // ...
9424     }
9426 The compiler does not read comments, and without reading other code you do not know whether `p` really points to `n` elements.
9427 Use a `span` instead.
9429 ##### Example
9431     void g(int* p, int fmt)   // print *p using format #fmt
9432     {
9433         // ... uses *p and p[0] only ...
9434     }
9436 ##### Exception
9438 C-style strings are passed as single pointers to a zero-terminated sequence of characters.
9439 Use `zstring` rather than `char*` to indicate that you rely on that convention.
9441 ##### Note
9443 Many current uses of pointers to a single element could be references.
9444 However, where `nullptr` is a possible value, a reference might not be a reasonable alternative.
9446 ##### Enforcement
9448 * Flag pointer arithmetic (including `++`) on a pointer that is not part of a container, view, or iterator.
9449   This rule would generate a huge number of false positives if applied to an older code base.
9450 * Flag array names passed as simple pointers
9452 ### <a name="Rr-ptr"></a>R.3: A raw pointer (a `T*`) is non-owning
9454 ##### Reason
9456 There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning.
9457 We want owning pointers identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
9459 ##### Example
9461     void f()
9462     {
9463         int* p1 = new int{7};           // bad: raw owning pointer
9464         auto p2 = make_unique<int>(7);  // OK: the int is owned by a unique pointer
9465         // ...
9466     }
9468 The `unique_ptr` protects against leaks by guaranteeing the deletion of its object (even in the presence of exceptions). The `T*` does not.
9470 ##### Example
9472     template<typename T>
9473     class X {
9474     public:
9475         T* p;   // bad: it is unclear whether p is owning or not
9476         T* q;   // bad: it is unclear whether q is owning or not
9477         // ...
9478     };
9480 We can fix that problem by making ownership explicit:
9482     template<typename T>
9483     class X2 {
9484     public:
9485         owner<T*> p;  // OK: p is owning
9486         T* q;         // OK: q is not owning
9487         // ...
9488     };
9490 ##### Exception
9492 A major class of exception is legacy code, especially code that must remain compilable as C or interface with C and C-style C++ through ABIs.
9493 The fact that there are billions of lines of code that violate this rule against owning `T*`s cannot be ignored.
9494 We'd love to see program transformation tools turning 20-year-old "legacy" code into shiny modern code,
9495 we encourage the development, deployment and use of such tools,
9496 we hope the guidelines will help the development of such tools,
9497 and we even contributed (and contribute) to the research and development in this area.
9498 However, it will take time: "legacy code" is generated faster than we can renovate old code, and so it will be for a few years.
9500 This code cannot all be rewritten (even assuming good code transformation software), especially not soon.
9501 This problem cannot be solved (at scale) by transforming all owning pointers to `unique_ptr`s and `shared_ptr`s,
9502 partly because we need/use owning "raw pointers" as well as simple pointers in the implementation of our fundamental resource handles.
9503 For example, common `vector` implementations have one owning pointer and two non-owning pointers.
9504 Many ABIs (and essentially all interfaces to C code) use `T*`s, some of them owning.
9505 Some interfaces cannot be simply annotated with `owner` because they need to remain compilable as C
9506 (although this would be a rare good use for a macro, that expands to `owner` in C++ mode only).
9508 ##### Note
9510 `owner<T*>` has no default semantics beyond `T*`. It can be used without changing any code using it and without affecting ABIs.
9511 It is simply an indicator to programmers and analysis tools.
9512 For example, if an `owner<T*>` is a member of a class, that class better have a destructor that `delete`s it.
9514 ##### Example, bad
9516 Returning a (raw) pointer imposes a lifetime management uncertainty on the caller; that is, who deletes the pointed-to object?
9518     Gadget* make_gadget(int n)
9519     {
9520         auto p = new Gadget{n};
9521         // ...
9522         return p;
9523     }
9525     void caller(int n)
9526     {
9527         auto p = make_gadget(n);   // remember to delete p
9528         // ...
9529         delete p;
9530     }
9532 In addition to suffering from the problem from [leak](#???), this adds a spurious allocation and deallocation operation, and is needlessly verbose. If Gadget is cheap to move out of a function (i.e., is small or has an efficient move operation), just return it "by value" (see ["out" return values](#Rf-out)):
9534     Gadget make_gadget(int n)
9535     {
9536         Gadget g{n};
9537         // ...
9538         return g;
9539     }
9541 ##### Note
9543 This rule applies to factory functions.
9545 ##### Note
9547 If pointer semantics are required (e.g., because the return type needs to refer to a base class of a class hierarchy (an interface)), return a "smart pointer."
9549 ##### Enforcement
9551 * (Simple) Warn on `delete` of a raw pointer that is not an `owner<T>`.
9552 * (Moderate) Warn on failure to either `reset` or explicitly `delete` an `owner<T>` pointer on every code path.
9553 * (Simple) Warn if the return value of `new` is assigned to a raw pointer.
9554 * (Simple) Warn if a function returns an object that was allocated within the function but has a move constructor.
9555   Suggest considering returning it by value instead.
9557 ### <a name="Rr-ref"></a>R.4: A raw reference (a `T&`) is non-owning
9559 ##### Reason
9561 There is nothing (in the C++ standard or in most code) to say otherwise and most raw references are non-owning.
9562 We want owners identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
9564 ##### Example
9566     void f()
9567     {
9568         int& r = *new int{7};  // bad: raw owning reference
9569         // ...
9570         delete &r;             // bad: violated the rule against deleting raw pointers
9571     }
9573 **See also**: [The raw pointer rule](#Rr-ptr)
9575 ##### Enforcement
9577 See [the raw pointer rule](#Rr-ptr)
9579 ### <a name="Rr-scoped"></a>R.5: Prefer scoped objects, don't heap-allocate unnecessarily
9581 ##### Reason
9583 A scoped object is a local object, a global object, or a member.
9584 This implies that there is no separate allocation and deallocation cost in excess of that already used for the containing scope or object.
9585 The members of a scoped object are themselves scoped and the scoped object's constructor and destructor manage the members' lifetimes.
9587 ##### Example
9589 The following example is inefficient (because it has unnecessary allocation and deallocation), vulnerable to exception throws and returns in the `...` part (leading to leaks), and verbose:
9591     void f(int n)
9592     {
9593         auto p = new Gadget{n};
9594         // ...
9595         delete p;
9596     }
9598 Instead, use a local variable:
9600     void f(int n)
9601     {
9602         Gadget g{n};
9603         // ...
9604     }
9606 ##### Enforcement
9608 * (Moderate) Warn if an object is allocated and then deallocated on all paths within a function. Suggest it should be a local stack object instead.
9609 * (Simple) Warn if a local `Unique_pointer` or `Shared_pointer` that is not moved, copied, reassigned or `reset` before its lifetime ends is not declared `const`.
9610 Exception: Do not produce such a warning on a local `Unique_pointer` to an unbounded array. (See below.)
9612 ##### Exception
9614 It is OK to create a local `const unique_ptr<T[]>` to a heap-allocated buffer, as this is a valid way to represent a scoped dynamic array.
9616 ##### Example
9618 A valid use case for a local `const unique_ptr<T[]>` variable:
9620     int get_median_value(const std::list<int>& integers)
9621     {
9622       const auto size = integers.size();
9624       // OK: declaring a local unique_ptr<T[]>.
9625       const auto local_buffer = std::make_unique_for_overwrite<int[]>(size);
9627       std::copy_n(begin(integers), size, local_buffer.get());
9628       std::nth_element(local_buffer.get(), local_buffer.get() + size/2, local_buffer.get() + size);
9630       return local_buffer[size/2];
9631     }
9633 ### <a name="Rr-global"></a>R.6: Avoid non-`const` global variables
9635 See [I.2](#Ri-global)
9637 ## <a name="SS-alloc"></a>R.alloc: Allocation and deallocation
9639 ### <a name="Rr-mallocfree"></a>R.10: Avoid `malloc()` and `free()`
9641 ##### Reason
9643  `malloc()` and `free()` do not support construction and destruction, and do not mix well with `new` and `delete`.
9645 ##### Example
9647     class Record {
9648         int id;
9649         string name;
9650         // ...
9651     };
9653     void use()
9654     {
9655         // p1 might be nullptr
9656         // *p1 is not initialized; in particular,
9657         // that string isn't a string, but a string-sized bag of bits
9658         Record* p1 = static_cast<Record*>(malloc(sizeof(Record)));
9660         auto p2 = new Record;
9662         // unless an exception is thrown, *p2 is default initialized
9663         auto p3 = new(nothrow) Record;
9664         // p3 might be nullptr; if not, *p3 is default initialized
9666         // ...
9668         delete p1;    // error: cannot delete object allocated by malloc()
9669         free(p2);    // error: cannot free() object allocated by new
9670     }
9672 In some implementations that `delete` and that `free()` might work, or maybe they will cause run-time errors.
9674 ##### Exception
9676 There are applications and sections of code where exceptions are not acceptable.
9677 Some of the best such examples are in life-critical hard-real-time code.
9678 Beware that many bans on exception use are based on superstition (bad)
9679 or by concerns for older code bases with unsystematic resource management (unfortunately, but sometimes necessary).
9680 In such cases, consider the `nothrow` versions of `new`.
9682 ##### Enforcement
9684 Flag explicit use of `malloc` and `free`.
9686 ### <a name="Rr-newdelete"></a>R.11: Avoid calling `new` and `delete` explicitly
9688 ##### Reason
9690 The pointer returned by `new` should belong to a resource handle (that can call `delete`).
9691 If the pointer returned by `new` is assigned to a plain/naked pointer, the object can be leaked.
9693 ##### Note
9695 In a large program, a naked `delete` (that is a `delete` in application code, rather than part of code devoted to resource management)
9696 is a likely bug: if you have N `delete`s, how can you be certain that you don't need N+1 or N-1?
9697 The bug might be latent: it might emerge only during maintenance.
9698 If you have a naked `new`, you probably need a naked `delete` somewhere, so you probably have a bug.
9700 ##### Enforcement
9702 (Simple) Warn on any explicit use of `new` and `delete`. Suggest using `make_unique` instead.
9704 ### <a name="Rr-immediate-alloc"></a>R.12: Immediately give the result of an explicit resource allocation to a manager object
9706 ##### Reason
9708 If you don't, an exception or a return might lead to a leak.
9710 ##### Example, bad
9712     void func(const string& name)
9713     {
9714         FILE* f = fopen(name, "r");            // open the file
9715         vector<char> buf(1024);
9716         auto _ = finally([f] { fclose(f); });  // remember to close the file
9717         // ...
9718     }
9720 The allocation of `buf` might fail and leak the file handle.
9722 ##### Example
9724     void func(const string& name)
9725     {
9726         ifstream f{name};   // open the file
9727         vector<char> buf(1024);
9728         // ...
9729     }
9731 The use of the file handle (in `ifstream`) is simple, efficient, and safe.
9733 ##### Enforcement
9735 * Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?)
9737 ### <a name="Rr-single-alloc"></a>R.13: Perform at most one explicit resource allocation in a single expression statement
9739 ##### Reason
9741 If you perform two explicit resource allocations in one statement, you could leak resources because the order of evaluation of many subexpressions, including function arguments, is unspecified.
9743 ##### Example
9745     void fun(shared_ptr<Widget> sp1, shared_ptr<Widget> sp2);
9747 This `fun` can be called like this:
9749     // BAD: potential leak
9750     fun(shared_ptr<Widget>(new Widget(a, b)), shared_ptr<Widget>(new Widget(c, d)));
9752 This is exception-unsafe because the compiler might reorder the two expressions building the function's two arguments.
9753 In particular, the compiler can interleave execution of the two expressions:
9754 Memory allocation (by calling `operator new`) could be done first for both objects, followed by attempts to call the two `Widget` constructors.
9755 If one of the constructor calls throws an exception, then the other object's memory will never be released!
9757 This subtle problem has a simple solution: Never perform more than one explicit resource allocation in a single expression statement.
9758 For example:
9760     shared_ptr<Widget> sp1(new Widget(a, b)); // Better, but messy
9761     fun(sp1, new Widget(c, d));
9763 The best solution is to avoid explicit allocation entirely use factory functions that return owning objects:
9765     fun(make_shared<Widget>(a, b), make_shared<Widget>(c, d)); // Best
9767 Write your own factory wrapper if there is not one already.
9769 ##### Enforcement
9771 * Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?)
9773 ### <a name="Rr-ap"></a>R.14: Avoid `[]` parameters, prefer `span`
9775 ##### Reason
9777 An array decays to a pointer, thereby losing its size, opening the opportunity for range errors.
9778 Use `span` to preserve size information.
9780 ##### Example
9782     void f(int[]);          // not recommended
9784     void f(int*);           // not recommended for multiple objects
9785                             // (a pointer should point to a single object, do not subscript)
9787     void f(gsl::span<int>); // good, recommended
9789 ##### Enforcement
9791 Flag `[]` parameters. Use `span` instead.
9793 ### <a name="Rr-pair"></a>R.15: Always overload matched allocation/deallocation pairs
9795 ##### Reason
9797 Otherwise you get mismatched operations and chaos.
9799 ##### Example
9801     class X {
9802         // ...
9803         void* operator new(size_t s);
9804         void operator delete(void*);
9805         // ...
9806     };
9808 ##### Note
9810 If you want memory that cannot be deallocated, `=delete` the deallocation operation.
9811 Don't leave it undeclared.
9813 ##### Enforcement
9815 Flag incomplete pairs.
9817 ## <a name="SS-smart"></a>R.smart: Smart pointers
9819 ### <a name="Rr-owner"></a>R.20: Use `unique_ptr` or `shared_ptr` to represent ownership
9821 ##### Reason
9823 They can prevent resource leaks.
9825 ##### Example
9827 Consider:
9829     void f()
9830     {
9831         X* p1 { new X };              // bad, p1 will leak
9832         auto p2 = make_unique<X>();   // good, unique ownership
9833         auto p3 = make_shared<X>();   // good, shared ownership
9834     }
9836 This will leak the object used to initialize `p1` (only).
9838 ##### Enforcement
9840 * (Simple) Warn if the return value of `new` is assigned to a raw pointer.
9841 * (Simple) Warn if the result of a function returning a raw owning pointer is assigned to a raw pointer.
9843 ### <a name="Rr-unique"></a>R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership
9845 ##### Reason
9847 A `unique_ptr` is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count).
9849 ##### Example, bad
9851 This needlessly adds and maintains a reference count.
9853     void f()
9854     {
9855         shared_ptr<Base> base = make_shared<Derived>();
9856         // use base locally, without copying it -- refcount never exceeds 1
9857     } // destroy base
9859 ##### Example
9861 This is more efficient:
9863     void f()
9864     {
9865         unique_ptr<Base> base = make_unique<Derived>();
9866         // use base locally
9867     } // destroy base
9869 ##### Enforcement
9871 (Simple) Warn if a function uses a `Shared_pointer` with an object allocated within the function, but never returns the `Shared_pointer` or passes it to a function requiring a `Shared_pointer&`. Suggest using `unique_ptr` instead.
9873 ### <a name="Rr-make_shared"></a>R.22: Use `make_shared()` to make `shared_ptr`s
9875 ##### Reason
9877 `make_shared` gives a more concise statement of the construction.
9878 It also gives an opportunity to eliminate a separate allocation for the reference counts, by placing the `shared_ptr`'s use counts next to its object.
9880 ##### Example
9882 Consider:
9884     shared_ptr<X> p1 { new X{2} }; // bad
9885     auto p = make_shared<X>(2);    // good
9887 The `make_shared()` version mentions `X` only once, so it is usually shorter (as well as faster) than the version with the explicit `new`.
9889 ##### Enforcement
9891 (Simple) Warn if a `shared_ptr` is constructed from the result of `new` rather than `make_shared`.
9893 ### <a name="Rr-make_unique"></a>R.23: Use `make_unique()` to make `unique_ptr`s
9895 ##### Reason
9897 `make_unique` gives a more concise statement of the construction.
9898 It also ensures exception safety in complex expressions.
9900 ##### Example
9902     unique_ptr<Foo> p {new Foo{7}};    // OK: but repetitive
9904     auto q = make_unique<Foo>(7);      // Better: no repetition of Foo
9906 ##### Enforcement
9908 (Simple) Warn if a `unique_ptr` is constructed from the result of `new` rather than `make_unique`.
9910 ### <a name="Rr-weak_ptr"></a>R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s
9912 ##### Reason
9914  `shared_ptr`'s rely on use counting and the use count for a cyclic structure never goes to zero, so we need a mechanism to
9915 be able to destroy a cyclic structure.
9917 ##### Example
9919     #include <memory>
9921     class bar;
9923     class foo {
9924     public:
9925       explicit foo(const std::shared_ptr<bar>& forward_reference)
9926         : forward_reference_(forward_reference)
9927       { }
9928     private:
9929       std::shared_ptr<bar> forward_reference_;
9930     };
9932     class bar {
9933     public:
9934       explicit bar(const std::weak_ptr<foo>& back_reference)
9935         : back_reference_(back_reference)
9936       { }
9937       void do_something()
9938       {
9939         if (auto shared_back_reference = back_reference_.lock()) {
9940           // Use *shared_back_reference
9941         }
9942       }
9943     private:
9944       std::weak_ptr<foo> back_reference_;
9945     };
9947 ##### Note
9949  ??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.)
9950 ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it.
9951 You could "temporarily share ownership" simply by using another `shared_ptr`.)
9953 ##### Enforcement
9955 ??? probably impossible. If we could statically detect cycles, we wouldn't need `weak_ptr`
9957 ### <a name="Rr-smartptrparam"></a>R.30: Take smart pointers as parameters only to explicitly express lifetime semantics
9959 See [F.7](#Rf-smart).
9961 ### <a name="Rr-smart"></a>R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`
9963 ##### Reason
9965 The rules in the following section also work for other kinds of third-party and custom smart pointers and are very useful for diagnosing common smart pointer errors that cause performance and correctness problems.
9966 You want the rules to work on all the smart pointers you use.
9968 Any type (including primary template or specialization) that overloads unary `*` and `->` is considered a smart pointer:
9970 * If it is copyable, it is recognized as a reference-counted `shared_ptr`.
9971 * If it is not copyable, it is recognized as a unique `unique_ptr`.
9973 ##### Example, bad
9975     // use Boost's intrusive_ptr
9976     #include <boost/intrusive_ptr.hpp>
9977     void f(boost::intrusive_ptr<widget> p)  // error under rule 'sharedptrparam'
9978     {
9979         p->foo();
9980     }
9982     // use Microsoft's CComPtr
9983     #include <atlbase.h>
9984     void f(CComPtr<widget> p)               // error under rule 'sharedptrparam'
9985     {
9986         p->foo();
9987     }
9989 Both cases are an error under the [`sharedptrparam` guideline](#Rr-smartptrparam):
9990 `p` is a `Shared_pointer`, but nothing about its sharedness is used here and passing it by value is a silent pessimization;
9991 these functions should accept a smart pointer only if they need to participate in the widget's lifetime management. Otherwise they should accept a `widget*`, if it can be `nullptr`. Otherwise, and ideally, the function should accept a `widget&`.
9992 These smart pointers match the `Shared_pointer` concept, so these guideline enforcement rules work on them out of the box and expose this common pessimization.
9994 ### <a name="Rr-uniqueptrparam"></a>R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`
9996 ##### Reason
9998 Using `unique_ptr` in this way both documents and enforces the function call's ownership transfer.
10000 ##### Example
10002     void sink(unique_ptr<widget>); // takes ownership of the widget
10004     void uses(widget*);            // just uses the widget
10006 ##### Example, bad
10008     void thinko(const unique_ptr<widget>&); // usually not what you want
10010 ##### Enforcement
10012 * (Simple) Warn if a function takes a `Unique_pointer<T>` parameter by lvalue reference and does not either assign to it or call `reset()` on it on at least one code path. Suggest taking a `T*` or `T&` instead.
10013 * (Simple) ((Foundation)) Warn if a function takes a `Unique_pointer<T>` parameter by reference to `const`. Suggest taking a `const T*` or `const T&` instead.
10015 ### <a name="Rr-reseat"></a>R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the `widget`
10017 ##### Reason
10019 Using `unique_ptr` in this way both documents and enforces the function call's reseating semantics.
10021 ##### Note
10023 "reseat" means "making a pointer or a smart pointer refer to a different object."
10025 ##### Example
10027     void reseat(unique_ptr<widget>&); // "will" or "might" reseat pointer
10029 ##### Example, bad
10031     void thinko(const unique_ptr<widget>&); // usually not what you want
10033 ##### Enforcement
10035 * (Simple) Warn if a function takes a `Unique_pointer<T>` parameter by lvalue reference and does not either assign to it or call `reset()` on it on at least one code path. Suggest taking a `T*` or `T&` instead.
10036 * (Simple) ((Foundation)) Warn if a function takes a `Unique_pointer<T>` parameter by reference to `const`. Suggest taking a `const T*` or `const T&` instead.
10038 ### <a name="Rr-sharedptrparam-owner"></a>R.34: Take a `shared_ptr<widget>` parameter to express shared ownership
10040 ##### Reason
10042 This makes the function's ownership sharing explicit.
10044 ##### Example, good
10046     class WidgetUser
10047     {
10048     public:
10049         // WidgetUser will share ownership of the widget
10050         explicit WidgetUser(std::shared_ptr<widget> w) noexcept:
10051             m_widget{std::move(w)} {}
10052         // ...
10053     private:
10054         std::shared_ptr<widget> m_widget;
10055     };
10057 ##### Enforcement
10059 * (Simple) Warn if a function takes a `Shared_pointer<T>` parameter by lvalue reference and does not either assign to it or call `reset()` on it on at least one code path. Suggest taking a `T*` or `T&` instead.
10060 * (Simple) ((Foundation)) Warn if a function takes a `Shared_pointer<T>` by value or by reference to `const` and does not copy or move it to another `Shared_pointer` on at least one code path. Suggest taking a `T*` or `T&` instead.
10061 * (Simple) ((Foundation)) Warn if a function takes a `Shared_pointer<T>` by rvalue reference. Suggesting taking it by value instead.
10063 ### <a name="Rr-sharedptrparam"></a>R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer
10065 ##### Reason
10067 This makes the function's reseating explicit.
10069 ##### Note
10071 "reseat" means "making a reference or a smart pointer refer to a different object."
10073 ##### Example, good
10075     void ChangeWidget(std::shared_ptr<widget>& w)
10076     {
10077         // This will change the callers widget
10078         w = std::make_shared<widget>(widget{});
10079     }
10081 ##### Enforcement
10083 * (Simple) Warn if a function takes a `Shared_pointer<T>` parameter by lvalue reference and does not either assign to it or call `reset()` on it on at least one code path. Suggest taking a `T*` or `T&` instead.
10084 * (Simple) ((Foundation)) Warn if a function takes a `Shared_pointer<T>` by value or by reference to `const` and does not copy or move it to another `Shared_pointer` on at least one code path. Suggest taking a `T*` or `T&` instead.
10085 * (Simple) ((Foundation)) Warn if a function takes a `Shared_pointer<T>` by rvalue reference. Suggesting taking it by value instead.
10087 ### <a name="Rr-sharedptrparam-const"></a>R.36: Take a `const shared_ptr<widget>&` parameter to express that it might retain a reference count to the object ???
10089 ##### Reason
10091 This makes the function's ??? explicit.
10093 ##### Example, good
10095     void share(shared_ptr<widget>);            // share -- "will" retain refcount
10097     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
10099     void may_share(const shared_ptr<widget>&); // "might" retain refcount
10101 ##### Enforcement
10103 * (Simple) Warn if a function takes a `Shared_pointer<T>` parameter by lvalue reference and does not either assign to it or call `reset()` on it on at least one code path. Suggest taking a `T*` or `T&` instead.
10104 * (Simple) ((Foundation)) Warn if a function takes a `Shared_pointer<T>` by value or by reference to `const` and does not copy or move it to another `Shared_pointer` on at least one code path. Suggest taking a `T*` or `T&` instead.
10105 * (Simple) ((Foundation)) Warn if a function takes a `Shared_pointer<T>` by rvalue reference. Suggesting taking it by value instead.
10107 ### <a name="Rr-smartptrget"></a>R.37: Do not pass a pointer or reference obtained from an aliased smart pointer
10109 ##### Reason
10111 Violating this rule is the number one cause of losing reference counts and finding yourself with a dangling pointer.
10112 Functions should prefer to pass raw pointers and references down call chains.
10113 At the top of the call tree where you obtain the raw pointer or reference from a smart pointer that keeps the object alive.
10114 You need to be sure that the smart pointer cannot inadvertently be reset or reassigned from within the call tree below.
10116 ##### Note
10118 To do this, sometimes you need to take a local copy of a smart pointer, which firmly keeps the object alive for the duration of the function and the call tree.
10120 ##### Example
10122 Consider this code:
10124     // global (static or heap), or aliased local ...
10125     shared_ptr<widget> g_p = ...;
10127     void f(widget& w)
10128     {
10129         g();
10130         use(w);  // A
10131     }
10133     void g()
10134     {
10135         g_p = ...; // oops, if this was the last shared_ptr to that widget, destroys the widget
10136     }
10138 The following should not pass code review:
10140     void my_code()
10141     {
10142         // BAD: passing pointer or reference obtained from a non-local smart pointer
10143         //      that could be inadvertently reset somewhere inside f or its callees
10144         f(*g_p);
10146         // BAD: same reason, just passing it as a "this" pointer
10147         g_p->func();
10148     }
10150 The fix is simple -- take a local copy of the pointer to "keep a ref count" for your call tree:
10152     void my_code()
10153     {
10154         // cheap: 1 increment covers this entire function and all the call trees below us
10155         auto pin = g_p;
10157         // GOOD: passing pointer or reference obtained from a local unaliased smart pointer
10158         f(*pin);
10160         // GOOD: same reason
10161         pin->func();
10162     }
10164 ##### Enforcement
10166 * (Simple) Warn if a pointer or reference obtained from a smart pointer variable (`Unique_pointer` or `Shared_pointer`) that is non-local, or that is local but potentially aliased, is used in a function call. If the smart pointer is a `Shared_pointer` then suggest taking a local copy of the smart pointer and obtain a pointer or reference from that instead.
10168 # <a name="S-expr"></a>ES: Expressions and statements
10170 Expressions and statements are the lowest and most direct way of expressing actions and computation. Declarations in local scopes are statements.
10172 For naming, commenting, and indentation rules, see [NL: Naming and layout](#S-naming).
10174 General rules:
10176 * [ES.1: Prefer the standard library to other libraries and to "handcrafted code"](#Res-lib)
10177 * [ES.2: Prefer suitable abstractions to direct use of language features](#Res-abstr)
10178 * [ES.3: Don't repeat yourself, avoid redundant code](#Res-DRY)
10180 Declaration rules:
10182 * [ES.5: Keep scopes small](#Res-scope)
10183 * [ES.6: Declare names in for-statement initializers and conditions to limit scope](#Res-cond)
10184 * [ES.7: Keep common and local names short, and keep uncommon and non-local names longer](#Res-name-length)
10185 * [ES.8: Avoid similar-looking names](#Res-name-similar)
10186 * [ES.9: Avoid `ALL_CAPS` names](#Res-not-CAPS)
10187 * [ES.10: Declare one name (only) per declaration](#Res-name-one)
10188 * [ES.11: Use `auto` to avoid redundant repetition of type names](#Res-auto)
10189 * [ES.12: Do not reuse names in nested scopes](#Res-reuse)
10190 * [ES.20: Always initialize an object](#Res-always)
10191 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
10192 * [ES.22: Don't declare a variable until you have a value to initialize it with](#Res-init)
10193 * [ES.23: Prefer the `{}`-initializer syntax](#Res-list)
10194 * [ES.24: Use a `unique_ptr<T>` to hold pointers](#Res-unique)
10195 * [ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on](#Res-const)
10196 * [ES.26: Don't use a variable for two unrelated purposes](#Res-recycle)
10197 * [ES.27: Use `std::array` or `stack_array` for arrays on the stack](#Res-stack)
10198 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
10199 * [ES.30: Don't use macros for program text manipulation](#Res-macros)
10200 * [ES.31: Don't use macros for constants or "functions"](#Res-macros2)
10201 * [ES.32: Use `ALL_CAPS` for all macro names](#Res-ALL_CAPS)
10202 * [ES.33: If you must use macros, give them unique names](#Res-MACROS)
10203 * [ES.34: Don't define a (C-style) variadic function](#Res-ellipses)
10205 Expression rules:
10207 * [ES.40: Avoid complicated expressions](#Res-complicated)
10208 * [ES.41: If in doubt about operator precedence, parenthesize](#Res-parens)
10209 * [ES.42: Keep use of pointers simple and straightforward](#Res-ptr)
10210 * [ES.43: Avoid expressions with undefined order of evaluation](#Res-order)
10211 * [ES.44: Don't depend on order of evaluation of function arguments](#Res-order-fct)
10212 * [ES.45: Avoid "magic constants"; use symbolic constants](#Res-magic)
10213 * [ES.46: Avoid narrowing conversions](#Res-narrowing)
10214 * [ES.47: Use `nullptr` rather than `0` or `NULL`](#Res-nullptr)
10215 * [ES.48: Avoid casts](#Res-casts)
10216 * [ES.49: If you must use a cast, use a named cast](#Res-casts-named)
10217 * [ES.50: Don't cast away `const`](#Res-casts-const)
10218 * [ES.55: Avoid the need for range checking](#Res-range-checking)
10219 * [ES.56: Write `std::move()` only when you need to explicitly move an object to another scope](#Res-move)
10220 * [ES.60: Avoid `new` and `delete` outside resource management functions](#Res-new)
10221 * [ES.61: Delete arrays using `delete[]` and non-arrays using `delete`](#Res-del)
10222 * [ES.62: Don't compare pointers into different arrays](#Res-arr2)
10223 * [ES.63: Don't slice](#Res-slice)
10224 * [ES.64: Use the `T{e}`notation for construction](#Res-construct)
10225 * [ES.65: Don't dereference an invalid pointer](#Res-deref)
10227 Statement rules:
10229 * [ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice](#Res-switch-if)
10230 * [ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice](#Res-for-range)
10231 * [ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable](#Res-for-while)
10232 * [ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable](#Res-while-for)
10233 * [ES.74: Prefer to declare a loop variable in the initializer part of a `for`-statement](#Res-for-init)
10234 * [ES.75: Avoid `do`-statements](#Res-do)
10235 * [ES.76: Avoid `goto`](#Res-goto)
10236 * [ES.77: Minimize the use of `break` and `continue` in loops](#Res-continue)
10237 * [ES.78: Don't rely on implicit fallthrough in `switch` statements](#Res-break)
10238 * [ES.79: Use `default` to handle common cases (only)](#Res-default)
10239 * [ES.84: Don't try to declare a local variable with no name](#Res-noname)
10240 * [ES.85: Make empty statements visible](#Res-empty)
10241 * [ES.86: Avoid modifying loop control variables inside the body of raw for-loops](#Res-loop-counter)
10242 * [ES.87: Don't add redundant `==` or `!=` to conditions](#Res-if)
10244 Arithmetic rules:
10246 * [ES.100: Don't mix signed and unsigned arithmetic](#Res-mix)
10247 * [ES.101: Use unsigned types for bit manipulation](#Res-unsigned)
10248 * [ES.102: Use signed types for arithmetic](#Res-signed)
10249 * [ES.103: Don't overflow](#Res-overflow)
10250 * [ES.104: Don't underflow](#Res-underflow)
10251 * [ES.105: Don't divide by integer zero](#Res-zero)
10252 * [ES.106: Don't try to avoid negative values by using `unsigned`](#Res-nonnegative)
10253 * [ES.107: Don't use `unsigned` for subscripts, prefer `gsl::index`](#Res-subscripts)
10255 ### <a name="Res-lib"></a>ES.1: Prefer the standard library to other libraries and to "handcrafted code"
10257 ##### Reason
10259 Code using a library can be much easier to write than code working directly with language features, much shorter, tend to be of a higher level of abstraction, and the library code is presumably already tested.
10260 The ISO C++ Standard Library is among the most widely known and best tested libraries.
10261 It is available as part of all C++ implementations.
10263 ##### Example
10265     auto sum = accumulate(begin(a), end(a), 0.0);   // good
10267 a range version of `accumulate` would be even better:
10269     auto sum = accumulate(v, 0.0); // better
10271 but don't hand-code a well-known algorithm:
10273     int max = v.size();   // bad: verbose, purpose unstated
10274     double sum = 0.0;
10275     for (int i = 0; i < max; ++i)
10276         sum = sum + v[i];
10278 ##### Exception
10280 Large parts of the standard library rely on dynamic allocation (free store). These parts, notably the containers but not the algorithms, are unsuitable for some hard-real-time and embedded applications. In such cases, consider providing/using similar facilities, e.g.,  a standard-library-style container implemented using a pool allocator.
10282 ##### Enforcement
10284 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of built-in types. Cyclomatic complexity?
10286 ### <a name="Res-abstr"></a>ES.2: Prefer suitable abstractions to direct use of language features
10288 ##### Reason
10290 A "suitable abstraction" (e.g., library or class) is closer to the application concepts than the bare language, leads to shorter and clearer code, and is likely to be better tested.
10292 ##### Example
10294     vector<string> read1(istream& is)   // good
10295     {
10296         vector<string> res;
10297         for (string s; is >> s;)
10298             res.push_back(s);
10299         return res;
10300     }
10302 The more traditional and lower-level near-equivalent is longer, messier, harder to get right, and most likely slower:
10304     char** read2(istream& is, int maxelem, int maxstring, int* nread)   // bad: verbose and incomplete
10305     {
10306         auto res = new char*[maxelem];
10307         int elemcount = 0;
10308         while (is && elemcount < maxelem) {
10309             auto s = new char[maxstring];
10310             is.read(s, maxstring);
10311             res[elemcount++] = s;
10312         }
10313         *nread = elemcount;
10314         return res;
10315     }
10317 Once the checking for overflow and error handling has been added that code gets quite messy, and there is the problem remembering to `delete` the returned pointer and the C-style strings that array contains.
10319 ##### Enforcement
10321 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of built-in types. Cyclomatic complexity?
10323 ### <a name="Res-DRY"></a>ES.3: Don't repeat yourself, avoid redundant code
10325 Duplicated or otherwise redundant code obscures intent, makes it harder to understand the logic, and makes maintenance harder, among other problems. It often arises from cut-and-paste programming.
10327 Use standard algorithms where appropriate, instead of writing some own implementation.
10329 **See also**: [SL.1](#Rsl-lib), [ES.11](#Res-auto)
10331 ##### Example
10333     void func(bool flag)    // Bad, duplicated code.
10334     {
10335         if (flag) {
10336             x();
10337             y();
10338         }
10339         else {
10340             x();
10341             z();
10342         }
10343     }
10345     void func(bool flag)    // Better, no duplicated code.
10346     {
10347         x();
10349         if (flag)
10350             y();
10351         else
10352             z();
10353     }
10356 ##### Enforcement
10358 * Use a static analyzer. It will catch at least some redundant constructs.
10359 * Code review
10361 ## ES.dcl: Declarations
10363 A declaration is a statement. A declaration introduces a name into a scope and might cause the construction of a named object.
10365 ### <a name="Res-scope"></a>ES.5: Keep scopes small
10367 ##### Reason
10369 Readability. Minimize resource retention. Avoid accidental misuse of value.
10371 **Alternative formulation**: Don't declare a name in an unnecessarily large scope.
10373 ##### Example
10375     void use()
10376     {
10377         int i;    // bad: i is needlessly accessible after loop
10378         for (i = 0; i < 20; ++i) { /* ... */ }
10379         // no intended use of i here
10380         for (int i = 0; i < 20; ++i) { /* ... */ }  // good: i is local to for-loop
10382         if (auto pc = dynamic_cast<Circle*>(ps)) {  // good: pc is local to if-statement
10383             // ... deal with Circle ...
10384         }
10385         else {
10386             // ... handle error ...
10387         }
10388     }
10390 ##### Example, bad
10392     void use(const string& name)
10393     {
10394         string fn = name + ".txt";
10395         ifstream is {fn};
10396         Record r;
10397         is >> r;
10398         // ... 200 lines of code without intended use of fn or is ...
10399     }
10401 This function is by most measures too long anyway, but the point is that the resources used by `fn` and the file handle held by `is`
10402 are retained for much longer than needed and that unanticipated use of `is` and `fn` could happen later in the function.
10403 In this case, it might be a good idea to factor out the read:
10405     Record load_record(const string& name)
10406     {
10407         string fn = name + ".txt";
10408         ifstream is {fn};
10409         Record r;
10410         is >> r;
10411         return r;
10412     }
10414     void use(const string& name)
10415     {
10416         Record r = load_record(name);
10417         // ... 200 lines of code ...
10418     }
10420 ##### Enforcement
10422 * Flag loop variable declared outside a loop and not used after the loop
10423 * Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N)
10425 ### <a name="Res-cond"></a>ES.6: Declare names in for-statement initializers and conditions to limit scope
10427 ##### Reason
10429 Readability.
10430 Limit the loop variable visibility to the scope of the loop.
10431 Avoid using the loop variable for other purposes after the loop.
10432 Minimize resource retention.
10434 ##### Example
10436     void use()
10437     {
10438         for (string s; cin >> s;)
10439             v.push_back(s);
10441         for (int i = 0; i < 20; ++i) {   // good: i is local to for-loop
10442             // ...
10443         }
10445         if (auto pc = dynamic_cast<Circle*>(ps)) {   // good: pc is local to if-statement
10446             // ... deal with Circle ...
10447         }
10448         else {
10449             // ... handle error ...
10450         }
10451     }
10453 ##### Example, don't
10455     int j;                            // BAD: j is visible outside the loop
10456     for (j = 0; j < 100; ++j) {
10457         // ...
10458     }
10459     // j is still visible here and isn't needed
10461 **See also**: [Don't use a variable for two unrelated purposes](#Res-recycle)
10463 ##### Enforcement
10465 * Warn when a variable modified inside the `for`-statement is declared outside the loop and not being used outside the loop.
10466 * (hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose.
10468 **Discussion**: Scoping the loop variable to the loop body also helps code optimizers greatly. Recognizing that the induction variable
10469 is only accessible in the loop body unblocks optimizations such as hoisting, strength reduction, loop-invariant code motion, etc.
10471 ##### C++17 and C++20 example
10473 Note: C++17 and C++20 also add `if`, `switch`, and range-`for` initializer statements. These require C++17 and C++20 support.
10475     map<int, string> mymap;
10477     if (auto result = mymap.insert(value); result.second) {
10478         // insert succeeded, and result is valid for this block
10479         use(result.first);  // ok
10480         // ...
10481     } // result is destroyed here
10483 ##### C++17 and C++20 enforcement (if using a C++17 or C++20 compiler)
10485 * Flag selection/loop variables declared before the body and not used after the body
10486 * (hard) Flag selection/loop variables declared before the body and used after the body for an unrelated purpose.
10488 ### <a name="Res-name-length"></a>ES.7: Keep common and local names short, and keep uncommon and non-local names longer
10490 ##### Reason
10492 Readability. Lowering the chance of clashes between unrelated non-local names.
10494 ##### Example
10496 Conventional short, local names increase readability:
10498     template<typename T>    // good
10499     void print(ostream& os, const vector<T>& v)
10500     {
10501         for (gsl::index i = 0; i < v.size(); ++i)
10502             os << v[i] << '\n';
10503     }
10505 An index is conventionally called `i` and there is no hint about the meaning of the vector in this generic function, so `v` is as good name as any. Compare
10507     template<typename Element_type>   // bad: verbose, hard to read
10508     void print(ostream& target_stream, const vector<Element_type>& current_vector)
10509     {
10510         for (gsl::index current_element_index = 0;
10511              current_element_index < current_vector.size();
10512              ++current_element_index
10513         )
10514         target_stream << current_vector[current_element_index] << '\n';
10515     }
10517 Yes, it is a caricature, but we have seen worse.
10519 ##### Example
10521 Unconventional and short non-local names obscure code:
10523     void use1(const string& s)
10524     {
10525         // ...
10526         tt(s);   // bad: what is tt()?
10527         // ...
10528     }
10530 Better, give non-local entities readable names:
10532     void use1(const string& s)
10533     {
10534         // ...
10535         trim_tail(s);   // better
10536         // ...
10537     }
10539 Here, there is a chance that the reader knows what `trim_tail` means and that the reader can remember it after looking it up.
10541 ##### Example, bad
10543 Argument names of large functions are de facto non-local and should be meaningful:
10545     void complicated_algorithm(vector<Record>& vr, const vector<int>& vi, map<string, int>& out)
10546     // read from events in vr (marking used Records) for the indices in
10547     // vi placing (name, index) pairs into out
10548     {
10549         // ... 500 lines of code using vr, vi, and out ...
10550     }
10552 We recommend keeping functions short, but that rule isn't universally adhered to and naming should reflect that.
10554 ##### Enforcement
10556 Check length of local and non-local names. Also take function length into account.
10558 ### <a name="Res-name-similar"></a>ES.8: Avoid similar-looking names
10560 ##### Reason
10562 Code clarity and readability. Too-similar names slow down comprehension and increase the likelihood of error.
10564 ##### Example, bad
10566     if (readable(i1 + l1 + ol + o1 + o0 + ol + o1 + I0 + l0)) surprise();
10568 ##### Example, bad
10570 Do not declare a non-type with the same name as a type in the same scope. This removes the need to disambiguate with a keyword such as `struct` or `enum`. It also removes a source of errors, as `struct X` can implicitly declare `X` if lookup fails.
10572     struct foo { int n; };
10573     struct foo foo();       // BAD, foo is a type already in scope
10574     struct foo x = foo();   // requires disambiguation
10576 ##### Exception
10578 Antique header files might declare non-types and types with the same name in the same scope.
10580 ##### Enforcement
10582 * Check names against a list of known confusing letter and digit combinations.
10583 * Flag a declaration of a variable, function, or enumerator that hides a class or enumeration declared in the same scope.
10585 ### <a name="Res-not-CAPS"></a>ES.9: Avoid `ALL_CAPS` names
10587 ##### Reason
10589 Such names are commonly used for macros. Thus, `ALL_CAPS` name are vulnerable to unintended macro substitution.
10591 ##### Example
10593     // somewhere in some header:
10594     #define NE !=
10596     // somewhere else in some other header:
10597     enum Coord { N, NE, NW, S, SE, SW, E, W };
10599     // somewhere third in some poor programmer's .cpp:
10600     switch (direction) {
10601     case N:
10602         // ...
10603     case NE:
10604         // ...
10605     // ...
10606     }
10608 ##### Note
10610 Do not use `ALL_CAPS` for constants just because constants used to be macros.
10612 ##### Enforcement
10614 Flag all uses of ALL CAPS. For older code, accept ALL CAPS for macro names and flag all non-ALL-CAPS macro names.
10616 ### <a name="Res-name-one"></a>ES.10: Declare one name (only) per declaration
10618 ##### Reason
10620 One declaration per line increases readability and avoids mistakes related to
10621 the C/C++ grammar. It also leaves room for a more descriptive end-of-line
10622 comment.
10624 ##### Example, bad
10626     char *p, c, a[7], *pp[7], **aa[10];   // yuck!
10628 ##### Exception
10630 A function declaration can contain several function argument declarations.
10632 ##### Exception
10634 A structured binding (C++17) is specifically designed to introduce several variables:
10636     auto [iter, inserted] = m.insert_or_assign(k, val);
10637     if (inserted) { /* new entry was inserted */ }
10639 ##### Example
10641     template<class InputIterator, class Predicate>
10642     bool any_of(InputIterator first, InputIterator last, Predicate pred);
10644 or better using concepts:
10646     bool any_of(input_iterator auto first, input_iterator auto last, predicate auto pred);
10648 ##### Example
10650     double scalbn(double x, int n);   // OK: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
10654     double scalbn(    // better: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
10655         double x,     // base value
10656         int n         // exponent
10657     );
10661     // better: base * pow(FLT_RADIX, exponent); FLT_RADIX is usually 2
10662     double scalbn(double base, int exponent);
10664 ##### Example
10666     int a = 10, b = 11, c = 12, d, e = 14, f = 15;
10668 In a long list of declarators it is easy to overlook an uninitialized variable.
10670 ##### Enforcement
10672 Flag variable and constant declarations with multiple declarators (e.g., `int* p, q;`)
10674 ### <a name="Res-auto"></a>ES.11: Use `auto` to avoid redundant repetition of type names
10676 ##### Reason
10678 * Simple repetition is tedious and error-prone.
10679 * When you use `auto`, the name of the declared entity is in a fixed position in the declaration, increasing readability.
10680 * In a function template declaration the return type can be a member type.
10682 ##### Example
10684 Consider:
10686     auto p = v.begin();      // vector<DataRecord>::iterator
10687     auto z1 = v[3];          // makes copy of DataRecord
10688     auto& z2 = v[3];         // avoids copy
10689     const auto& z3 = v[3];   // const and avoids copy
10690     auto h = t.future();
10691     auto q = make_unique<int[]>(s);
10692     auto f = [](int x) { return x + 10; };
10694 In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.
10696 ##### Example
10698     template<class T>
10699     auto Container<T>::first() -> Iterator;   // Container<T>::Iterator
10701 ##### Exception
10703 Avoid `auto` for initializer lists and in cases where you know exactly which type you want and where an initializer might require conversion.
10705 ##### Example
10707     auto lst = { 1, 2, 3 };   // lst is an initializer list
10708     auto x{1};   // x is an int (in C++17; initializer_list in C++11)
10710 ##### Note
10712 As of C++20, we can (and should) use concepts to be more specific about the type we are deducing:
10714     // ...
10715     forward_iterator auto p = algo(x, y, z);
10717 ##### Example (C++17)
10719     std::set<int> values;
10720     // ...
10721     auto [ position, newly_inserted ] = values.insert(5);   // break out the members of the std::pair
10723 ##### Enforcement
10725 Flag redundant repetition of type names in a declaration.
10727 ### <a name="Res-reuse"></a>ES.12: Do not reuse names in nested scopes
10729 ##### Reason
10731 It is easy to get confused about which variable is used.
10732 Can cause maintenance problems.
10734 ##### Example, bad
10736     int d = 0;
10737     // ...
10738     if (cond) {
10739         // ...
10740         d = 9;
10741         // ...
10742     }
10743     else {
10744         // ...
10745         int d = 7;
10746         // ...
10747         d = value_to_be_returned;
10748         // ...
10749     }
10751     return d;
10753 If this is a large `if`-statement, it is easy to overlook that a new `d` has been introduced in the inner scope.
10754 This is a known source of bugs.
10755 Sometimes such reuse of a name in an inner scope is called "shadowing".
10757 ##### Note
10759 Shadowing is primarily a problem when functions are too large and too complex.
10761 ##### Example
10763 Shadowing of function arguments in the outermost block is disallowed by the language:
10765     void f(int x)
10766     {
10767         int x = 4;  // error: reuse of function argument name
10769         if (x) {
10770             int x = 7;  // allowed, but bad
10771             // ...
10772         }
10773     }
10775 ##### Example, bad
10777 Reuse of a member name as a local variable can also be a problem:
10779     struct S {
10780         int m;
10781         void f(int x);
10782     };
10784     void S::f(int x)
10785     {
10786         m = 7;    // assign to member
10787         if (x) {
10788             int m = 9;
10789             // ...
10790             m = 99; // assign to local variable
10791             // ...
10792         }
10793     }
10795 ##### Exception
10797 We often reuse function names from a base class in a derived class:
10799     struct B {
10800         void f(int);
10801     };
10803     struct D : B {
10804         void f(double);
10805         using B::f;
10806     };
10808 This is error-prone.
10809 For example, had we forgotten the using declaration, a call `d.f(1)` would not have found the `int` version of `f`.
10811 ??? Do we need a specific rule about shadowing/hiding in class hierarchies?
10813 ##### Enforcement
10815 * Flag reuse of a name in nested local scopes
10816 * Flag reuse of a member name as a local variable in a member function
10817 * Flag reuse of a global name as a local variable or a member name
10818 * Flag reuse of a base class member name in a derived class (except for function names)
10820 ### <a name="Res-always"></a>ES.20: Always initialize an object
10822 ##### Reason
10824 Avoid used-before-set errors and their associated undefined behavior.
10825 Avoid problems with comprehension of complex initialization.
10826 Simplify refactoring.
10828 ##### Example
10830     void use(int arg)
10831     {
10832         int i;   // bad: uninitialized variable
10833         // ...
10834         i = 7;   // initialize i
10835     }
10837 No, `i = 7` does not initialize `i`; it assigns to it. Also, `i` can be read in the `...` part. Better:
10839     void use(int arg)   // OK
10840     {
10841         int i = 7;   // OK: initialized
10842         string s;    // OK: default initialized
10843         // ...
10844     }
10846 ##### Note
10848 The *always initialize* rule is deliberately stronger than the *an object must be set before used* language rule.
10849 The latter, more relaxed rule, catches the technical bugs, but:
10851 * It leads to less readable code
10852 * It encourages people to declare names in greater than necessary scopes
10853 * It leads to harder to read code
10854 * It leads to logic bugs by encouraging complex code
10855 * It hampers refactoring
10857 The *always initialize* rule is a style rule aimed to improve maintainability as well as a rule protecting against used-before-set errors.
10859 ##### Example
10861 Here is an example that is often considered to demonstrate the need for a more relaxed rule for initialization
10863     widget i;    // "widget" a type that's expensive to initialize, possibly a large trivial type
10864     widget j;
10866     if (cond) {  // bad: i and j are initialized "late"
10867         i = f1();
10868         j = f2();
10869     }
10870     else {
10871         i = f3();
10872         j = f4();
10873     }
10875 This cannot trivially be rewritten to initialize `i` and `j` with initializers.
10876 Note that for types with a default constructor, attempting to postpone initialization simply leads to a default initialization followed by an assignment.
10877 A popular reason for such examples is "efficiency", but a compiler that can detect whether we made a used-before-set error can also eliminate any redundant double initialization.
10879 Assuming that there is a logical connection between `i` and `j`, that connection should probably be expressed in code:
10881     pair<widget, widget> make_related_widgets(bool x)
10882     {
10883         return (x) ? {f1(), f2()} : {f3(), f4()};
10884     }
10886     auto [i, j] = make_related_widgets(cond);    // C++17
10888 If the `make_related_widgets` function is otherwise redundant,
10889 we can eliminate it by using a lambda [ES.28](#Res-lambda-init):
10891     auto [i, j] = [x] { return (x) ? pair{f1(), f2()} : pair{f3(), f4()} }();    // C++17
10893 Using a value representing "uninitialized" is a symptom of a problem and not a solution:
10895     widget i = uninit;  // bad
10896     widget j = uninit;
10898     // ...
10899     use(i);         // possibly used before set
10900     // ...
10902     if (cond) {     // bad: i and j are initialized "late"
10903         i = f1();
10904         j = f2();
10905     }
10906     else {
10907         i = f3();
10908         j = f4();
10909     }
10911 Now the compiler cannot even simply detect a used-before-set. Further, we've introduced complexity in the state space for widget: which operations are valid on an `uninit` widget and which are not?
10913 ##### Note
10915 Complex initialization has been popular with clever programmers for decades.
10916 It has also been a major source of errors and complexity.
10917 Many such errors are introduced during maintenance years after the initial implementation.
10919 ##### Example
10921 This rule covers member variables.
10923     class X {
10924     public:
10925         X(int i, int ci) : m2{i}, cm2{ci} {}
10926         // ...
10928     private:
10929         int m1 = 7;
10930         int m2;
10931         int m3;
10933         const int cm1 = 7;
10934         const int cm2;
10935         const int cm3;
10936     };
10938 The compiler will flag the uninitialized `cm3` because it is a `const`, but it will not catch the lack of initialization of `m3`.
10939 Usually, a rare spurious member initialization is worth the absence of errors from lack of initialization and often an optimizer
10940 can eliminate a redundant initialization (e.g., an initialization that occurs immediately before an assignment).
10942 ##### Exception
10944 If you are declaring an object that is just about to be initialized from input, initializing it would cause a double initialization.
10945 However, beware that this might leave uninitialized data beyond the input -- and that has been a fertile source of errors and security breaches:
10947     constexpr int max = 8 * 1024;
10948     int buf[max];         // OK, but suspicious: uninitialized
10949     f.read(buf, max);
10951 The cost of initializing that array could be significant in some situations.
10952 However, such examples do tend to leave uninitialized variables accessible, so they should be treated with suspicion.
10954     constexpr int max = 8 * 1024;
10955     int buf[max] = {};   // zero all elements; better in some situations
10956     f.read(buf, max);
10958 Because of the restrictive initialization rules for arrays and `std::array`, they offer the most compelling examples of the need for this exception.
10960 When feasible use a library function that is known not to overflow. For example:
10962     string s;   // s is default initialized to ""
10963     cin >> s;   // s expands to hold the string
10965 Don't consider simple variables that are targets for input operations exceptions to this rule:
10967     int i;   // bad
10968     // ...
10969     cin >> i;
10971 In the not uncommon case where the input target and the input operation get separated (as they should not) the possibility of used-before-set opens up.
10973     int i2 = 0;   // better, assuming that zero is an acceptable value for i2
10974     // ...
10975     cin >> i2;
10977 A good optimizer should know about input operations and eliminate the redundant operation.
10980 ##### Note
10982 Sometimes, a lambda can be used as an initializer to avoid an uninitialized variable:
10984     error_code ec;
10985     Value v = [&] {
10986         auto p = get_value();   // get_value() returns a pair<error_code, Value>
10987         ec = p.first;
10988         return p.second;
10989     }();
10991 or maybe:
10993     Value v = [] {
10994         auto p = get_value();   // get_value() returns a pair<error_code, Value>
10995         if (p.first) throw Bad_value{p.first};
10996         return p.second;
10997     }();
10999 **See also**: [ES.28](#Res-lambda-init)
11001 ##### Enforcement
11003 * Flag every uninitialized variable.
11004   Don't flag variables of user-defined types with default constructors.
11005 * Check that an uninitialized buffer is written into *immediately* after declaration.
11006   Passing an uninitialized variable as a reference to non-`const` argument can be assumed to be a write into the variable.
11008 ### <a name="Res-introduce"></a>ES.21: Don't introduce a variable (or constant) before you need to use it
11010 ##### Reason
11012 Readability. To limit the scope in which the variable can be used.
11014 ##### Example
11016     int x = 7;
11017     // ... no use of x here ...
11018     ++x;
11020 ##### Enforcement
11022 Flag declarations that are distant from their first use.
11024 ### <a name="Res-init"></a>ES.22: Don't declare a variable until you have a value to initialize it with
11026 ##### Reason
11028 Readability. Limit the scope in which a variable can be used. Don't risk used-before-set. Initialization is often more efficient than assignment.
11030 ##### Example, bad
11032     string s;
11033     // ... no use of s here ...
11034     s = "what a waste";
11036 ##### Example, bad
11038     SomeLargeType var;  // Hard-to-read CaMeLcAsEvArIaBlE
11040     if (cond)   // some non-trivial condition
11041         Set(&var);
11042     else if (cond2 || !cond3) {
11043         var = Set2(3.14);
11044     }
11045     else {
11046         var = 0;
11047         for (auto& e : something)
11048             var += e;
11049     }
11051     // use var; that this isn't done too early can be enforced statically with only control flow
11053 This would be fine if there was a default initialization for `SomeLargeType` that wasn't too expensive.
11054 Otherwise, a programmer might very well wonder if every possible path through the maze of conditions has been covered.
11055 If not, we have a "use before set" bug. This is a maintenance trap.
11057 For initializers of moderate complexity, including for `const` variables, consider using a lambda to express the initializer; see [ES.28](#Res-lambda-init).
11059 ##### Enforcement
11061 * Flag declarations with default initialization that are assigned to before they are first read.
11062 * Flag any complicated computation after an uninitialized variable and before its use.
11064 ### <a name="Res-list"></a>ES.23: Prefer the `{}`-initializer syntax
11066 ##### Reason
11068 Prefer `{}`. The rules for `{}` initialization are simpler, more general, less ambiguous, and safer than for other forms of initialization.
11070 Use `=` only when you are sure that there can be no narrowing conversions. For built-in arithmetic types, use `=` only with `auto`.
11072 Avoid `()` initialization, which allows parsing ambiguities.
11074 ##### Example
11076     int x {f(99)};
11077     int y = x;
11078     vector<int> v = {1, 2, 3, 4, 5, 6};
11080 ##### Exception
11082 For containers, there is a tradition for using `{...}` for a list of elements and `(...)` for sizes:
11084     vector<int> v1(10);    // vector of 10 elements with the default value 0
11085     vector<int> v2{10};    // vector of 1 element with the value 10
11087     vector<int> v3(1, 2);  // vector of 1 element with the value 2
11088     vector<int> v4{1, 2};  // vector of 2 elements with the values 1 and 2
11090 ##### Note
11092 `{}`-initializers do not allow narrowing conversions (and that is usually a good thing) and allow explicit constructors (which is fine, we're intentionally initializing a new variable).
11094 ##### Example
11096     int x {7.9};   // error: narrowing
11097     int y = 7.9;   // OK: y becomes 7. Hope for a compiler warning
11098     int z {gsl::narrow_cast<int>(7.9)};    // OK: you asked for it
11099     auto zz = gsl::narrow_cast<int>(7.9);  // OK: you asked for it
11101 ##### Note
11103 `{}` initialization can be used for nearly all initialization; other forms of initialization can't:
11105     auto p = new vector<int> {1, 2, 3, 4, 5};   // initialized vector
11106     D::D(int a, int b) :m{a, b} {   // member initializer (e.g., m might be a pair)
11107         // ...
11108     };
11109     X var {};   // initialize var to be empty
11110     struct S {
11111         int m {7};   // default initializer for a member
11112         // ...
11113     };
11115 For that reason, `{}`-initialization is often called "uniform initialization"
11116 (though there unfortunately are a few irregularities left).
11118 ##### Note
11120 Initialization of a variable declared using `auto` with a single value, e.g., `{v}`, had surprising results until C++17.
11121 The C++17 rules are somewhat less surprising:
11123     auto x1 {7};        // x1 is an int with the value 7
11124     auto x2 = {7};      // x2 is an initializer_list<int> with an element 7
11126     auto x11 {7, 8};    // error: two initializers
11127     auto x22 = {7, 8};  // x22 is an initializer_list<int> with elements 7 and 8
11129 Use `={...}` if you really want an `initializer_list<T>`
11131     auto fib10 = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};   // fib10 is a list
11133 ##### Note
11135 `={}` gives copy initialization whereas `{}` gives direct initialization.
11136 Like the distinction between copy-initialization and direct-initialization itself, this can lead to surprises.
11137 `{}` accepts `explicit` constructors; `={}` does not. For example:
11139     struct Z { explicit Z() {} };
11141     Z z1{};     // OK: direct initialization, so we use explicit constructor
11142     Z z2 = {};  // error: copy initialization, so we cannot use the explicit constructor
11144 Use plain `{}`-initialization unless you specifically want to disable explicit constructors.
11146 ##### Example
11148     template<typename T>
11149     void f()
11150     {
11151         T x1(1);    // T initialized with 1
11152         T x0();     // bad: function declaration (often a mistake)
11154         T y1 {1};   // T initialized with 1
11155         T y0 {};    // default initialized T
11156         // ...
11157     }
11159 **See also**: [Discussion](#???)
11161 ##### Enforcement
11163 * Flag uses of `=` to initialize arithmetic types where narrowing occurs.
11164 * Flag uses of `()` initialization syntax that are actually declarations. (Many compilers should warn on this already.)
11166 ### <a name="Res-unique"></a>ES.24: Use a `unique_ptr<T>` to hold pointers
11168 ##### Reason
11170 Using `std::unique_ptr` is the simplest way to avoid leaks. It is reliable, it
11171 makes the type system do much of the work to validate ownership safety, it
11172 increases readability, and it has zero or near zero run-time cost.
11174 ##### Example
11176     void use(bool leak)
11177     {
11178         auto p1 = make_unique<int>(7);   // OK
11179         int* p2 = new int{7};            // bad: might leak
11180         // ... no assignment to p2 ...
11181         if (leak) return;
11182         // ... no assignment to p2 ...
11183         vector<int> v(7);
11184         v.at(7) = 0;                    // exception thrown
11185         delete p2;                      // too late to prevent leaks
11186         // ...
11187     }
11189 If `leak == true` the object pointed to by `p2` is leaked and the object pointed to by `p1` is not.
11190 The same is the case when `at()` throws. In both cases, the `delete p2` statement is not reached.
11192 ##### Enforcement
11194 Look for raw pointers that are targets of `new`, `malloc()`, or functions that might return such pointers.
11196 ### <a name="Res-const"></a>ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on
11198 ##### Reason
11200 That way you can't change the value by mistake. That way might offer the compiler optimization opportunities.
11202 ##### Example
11204     void f(int n)
11205     {
11206         const int bufmax = 2 * n + 2;  // good: we can't change bufmax by accident
11207         int xmax = n;                  // suspicious: is xmax intended to change?
11208         // ...
11209     }
11211 ##### Enforcement
11213 Look to see if a variable is actually mutated, and flag it if
11214 not. Unfortunately, it might be impossible to detect when a non-`const` was not
11215 *intended* to vary (vs when it merely did not vary).
11217 ### <a name="Res-recycle"></a>ES.26: Don't use a variable for two unrelated purposes
11219 ##### Reason
11221 Readability and safety.
11223 ##### Example, bad
11225     void use()
11226     {
11227         int i;
11228         for (i = 0; i < 20; ++i) { /* ... */ }
11229         for (i = 0; i < 200; ++i) { /* ... */ } // bad: i recycled
11230     }
11232 ##### Note
11234 As an optimization, you might want to reuse a buffer as a scratch pad, but even then prefer to limit the variable's scope as much as possible and be careful not to cause bugs from data left in a recycled buffer as this is a common source of security bugs.
11236     void write_to_file()
11237     {
11238         std::string buffer;             // to avoid reallocations on every loop iteration
11239         for (auto& o : objects) {
11240             // First part of the work.
11241             generate_first_string(buffer, o);
11242             write_to_file(buffer);
11244             // Second part of the work.
11245             generate_second_string(buffer, o);
11246             write_to_file(buffer);
11248             // etc...
11249         }
11250     }
11252 ##### Enforcement
11254 Flag recycled variables.
11256 ### <a name="Res-stack"></a>ES.27: Use `std::array` or `stack_array` for arrays on the stack
11258 ##### Reason
11260 They are readable and don't implicitly convert to pointers.
11261 They are not confused with non-standard extensions of built-in arrays.
11263 ##### Example, bad
11265     const int n = 7;
11266     int m = 9;
11268     void f()
11269     {
11270         int a1[n];
11271         int a2[m];   // error: not ISO C++
11272         // ...
11273     }
11275 ##### Note
11277 The definition of `a1` is legal C++ and has always been.
11278 There is a lot of such code.
11279 It is error-prone, though, especially when the bound is non-local.
11280 Also, it is a "popular" source of errors (buffer overflow, pointers from array decay, etc.).
11281 The definition of `a2` is C but not C++ and is considered a security risk
11283 ##### Example
11285     const int n = 7;
11286     int m = 9;
11288     void f()
11289     {
11290         array<int, n> a1;
11291         stack_array<int> a2(m);
11292         // ...
11293     }
11295 ##### Enforcement
11297 * Flag arrays with non-constant bounds (C-style VLAs)
11298 * Flag arrays with non-local constant bounds
11300 ### <a name="Res-lambda-init"></a>ES.28: Use lambdas for complex initialization, especially of `const` variables
11302 ##### Reason
11304 It nicely encapsulates local initialization, including cleaning up scratch variables needed only for the initialization, without needing to create a needless non-local yet non-reusable function. It also works for variables that should be `const` but only after some initialization work.
11306 ##### Example, bad
11308     widget x;   // should be const, but:
11309     for (auto i = 2; i <= N; ++i) {          // this could be some
11310         x += some_obj.do_something_with(i);  // arbitrarily long code
11311     }                                        // needed to initialize x
11312     // from here, x should be const, but we can't say so in code in this style
11314 ##### Example, good
11316     const widget x = [&] {
11317         widget val;                                // assume that widget has a default constructor
11318         for (auto i = 2; i <= N; ++i) {            // this could be some
11319             val += some_obj.do_something_with(i);  // arbitrarily long code
11320         }                                          // needed to initialize x
11321         return val;
11322     }();
11324 If at all possible, reduce the conditions to a simple set of alternatives (e.g., an `enum`) and don't mix up selection and initialization.
11326 ##### Enforcement
11328 Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it.
11330 ### <a name="Res-macros"></a>ES.30: Don't use macros for program text manipulation
11332 ##### Reason
11334 Macros are a major source of bugs.
11335 Macros don't obey the usual scope and type rules.
11336 Macros ensure that the human reader sees something different from what the compiler sees.
11337 Macros complicate tool building.
11339 ##### Example, bad
11341     #define Case break; case   /* BAD */
11343 This innocuous-looking macro makes a single lower case `c` instead of a `C` into a bad flow-control bug.
11345 ##### Note
11347 This rule does not ban the use of macros for "configuration control" use in `#ifdef`s, etc.
11349 In the future, modules are likely to eliminate the need for macros in configuration control.
11351 ##### Note
11353 This rule is meant to also discourage use of `#` for stringification and `##` for concatenation.
11354 As usual for macros, there are uses that are "mostly harmless", but even these can create problems for tools,
11355 such as auto completers, static analyzers, and debuggers.
11356 Often the desire to use fancy macros is a sign of an overly complex design.
11357 Also, `#` and `##` encourages the definition and use of macros:
11359     #define CAT(a, b) a ## b
11360     #define STRINGIFY(a) #a
11362     void f(int x, int y)
11363     {
11364         string CAT(x, y) = "asdf";   // BAD: hard for tools to handle (and ugly)
11365         string sx2 = STRINGIFY(x);
11366         // ...
11367     }
11369 There are workarounds for low-level string manipulation using macros. For example:
11371     enum E { a, b };
11373     template<int x>
11374     constexpr const char* stringify()
11375     {
11376         switch (x) {
11377         case a: return "a";
11378         case b: return "b";
11379         }
11380     }
11382     void f()
11383     {
11384         string s1 = stringify<a>();
11385         string s2 = stringify<b>();
11386         // ...
11387     }
11389 This is not as convenient as a macro to define, but as easy to use, has zero overhead, and is typed and scoped.
11391 In the future, static reflection is likely to eliminate the last needs for the preprocessor for program text manipulation.
11393 ##### Enforcement
11395 Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`)
11397 ### <a name="Res-macros2"></a>ES.31: Don't use macros for constants or "functions"
11399 ##### Reason
11401 Macros are a major source of bugs.
11402 Macros don't obey the usual scope and type rules.
11403 Macros don't obey the usual rules for argument passing.
11404 Macros ensure that the human reader sees something different from what the compiler sees.
11405 Macros complicate tool building.
11407 ##### Example, bad
11409     #define PI 3.14
11410     #define SQUARE(a, b) (a * b)
11412 Even if we hadn't left a well-known bug in `SQUARE` there are much better behaved alternatives; for example:
11414     constexpr double pi = 3.14;
11415     template<typename T> T square(T a, T b) { return a * b; }
11417 ##### Enforcement
11419 Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`)
11421 ### <a name="Res-ALL_CAPS"></a>ES.32: Use `ALL_CAPS` for all macro names
11423 ##### Reason
11425 Convention. Readability. Distinguishing macros.
11427 ##### Example
11429     #define forever for (;;)   /* very BAD */
11431     #define FOREVER for (;;)   /* Still evil, but at least visible to humans */
11433 ##### Enforcement
11435 Scream when you see a lower case macro.
11437 ### <a name="Res-MACROS"></a>ES.33: If you must use macros, give them unique names
11439 ##### Reason
11441 Macros do not obey scope rules.
11443 ##### Example
11445     #define MYCHAR        /* BAD, will eventually clash with someone else's MYCHAR*/
11447     #define ZCORP_CHAR    /* Still evil, but less likely to clash */
11449 ##### Note
11451 Avoid macros if you can: [ES.30](#Res-macros), [ES.31](#Res-macros2), and [ES.32](#Res-ALL_CAPS).
11452 However, there are billions of lines of code littered with macros and a long tradition for using and overusing macros.
11453 If you are forced to use macros, use long names and supposedly unique prefixes (e.g., your organization's name) to lower the likelihood of a clash.
11455 ##### Enforcement
11457 Warn against short macro names.
11459 ### <a name="Res-ellipses"></a> ES.34: Don't define a (C-style) variadic function
11461 ##### Reason
11463 Not type safe.
11464 Requires messy cast-and-macro-laden code to get working right.
11466 ##### Example
11468     #include <cstdarg>
11470     // "severity" followed by a zero-terminated list of char*s; write the C-style strings to cerr
11471     void error(int severity ...)
11472     {
11473         va_list ap;             // a magic type for holding arguments
11474         va_start(ap, severity); // arg startup: "severity" is the first argument of error()
11476         for (;;) {
11477             // treat the next var as a char*; no checking: a cast in disguise
11478             char* p = va_arg(ap, char*);
11479             if (!p) break;
11480             cerr << p << ' ';
11481         }
11483         va_end(ap);             // arg cleanup (don't forget this)
11485         cerr << '\n';
11486         if (severity) exit(severity);
11487     }
11489     void use()
11490     {
11491         error(7, "this", "is", "an", "error", nullptr);
11492         error(7); // crash
11493         error(7, "this", "is", "an", "error");  // crash
11494         const char* is = "is";
11495         string an = "an";
11496         error(7, "this", is, an, "error"); // crash
11497     }
11499 **Alternative**: Overloading. Templates. Variadic templates.
11501     #include <iostream>
11503     void error(int severity)
11504     {
11505         std::cerr << '\n';
11506         std::exit(severity);
11507     }
11509     template<typename T, typename... Ts>
11510     constexpr void error(int severity, T head, Ts... tail)
11511     {
11512         std::cerr << head;
11513         error(severity, tail...);
11514     }
11516     void use()
11517     {
11518         error(7); // No crash!
11519         error(5, "this", "is", "not", "an", "error"); // No crash!
11521         std::string an = "an";
11522         error(7, "this", "is", "not", an, "error"); // No crash!
11524         error(5, "oh", "no", nullptr); // Compile error! No need for nullptr.
11525     }
11528 ##### Note
11530 This is basically the way `printf` is implemented.
11532 ##### Enforcement
11534 * Flag definitions of C-style variadic functions.
11535 * Flag `#include <cstdarg>` and `#include <stdarg.h>`
11538 ## ES.expr: Expressions
11540 Expressions manipulate values.
11542 ### <a name="Res-complicated"></a>ES.40: Avoid complicated expressions
11544 ##### Reason
11546 Complicated expressions are error-prone.
11548 ##### Example
11550     // bad: assignment hidden in subexpression
11551     while ((c = getc()) != -1)
11553     // bad: two non-local variables assigned in sub-expressions
11554     while ((cin >> c1, cin >> c2), c1 == c2)
11556     // better, but possibly still too complicated
11557     for (char c1, c2; cin >> c1 >> c2 && c1 == c2;)
11559     // OK: if i and j are not aliased
11560     int x = ++i + ++j;
11562     // OK: if i != j and i != k
11563     v[i] = v[j] + v[k];
11565     // bad: multiple assignments "hidden" in subexpressions
11566     x = a + (b = f()) + (c = g()) * 7;
11568     // bad: relies on commonly misunderstood precedence rules
11569     x = a & b + c * d && e ^ f == 7;
11571     // bad: undefined behavior
11572     x = x++ + x++ + ++x;
11574 Some of these expressions are unconditionally bad (e.g., they rely on undefined behavior). Others are simply so complicated and/or unusual that even good programmers could misunderstand them or overlook a problem when in a hurry.
11576 ##### Note
11578 C++17 tightens up the rules for the order of evaluation
11579 (left-to-right except right-to-left in assignments, and the order of evaluation of function arguments is unspecified; [see ES.43](#Res-order)),
11580 but that doesn't change the fact that complicated expressions are potentially confusing.
11582 ##### Note
11584 A programmer should know and use the basic rules for expressions.
11586 ##### Example
11588     x = k * y + z;             // OK
11590     auto t1 = k * y;           // bad: unnecessarily verbose
11591     x = t1 + z;
11593     if (0 <= x && x < max)   // OK
11595     auto t1 = 0 <= x;        // bad: unnecessarily verbose
11596     auto t2 = x < max;
11597     if (t1 && t2)            // ...
11599 ##### Enforcement
11601 Tricky. How complicated must an expression be to be considered complicated? Writing computations as statements with one operation each is also confusing. Things to consider:
11603 * side effects: side effects on multiple non-local variables (for some definition of non-local) can be suspect, especially if the side effects are in separate subexpressions
11604 * writes to aliased variables
11605 * more than N operators (and what should N be?)
11606 * reliance of subtle precedence rules
11607 * uses undefined behavior (can we catch all undefined behavior?)
11608 * implementation defined behavior?
11609 * ???
11611 ### <a name="Res-parens"></a>ES.41: If in doubt about operator precedence, parenthesize
11613 ##### Reason
11615 Avoid errors. Readability. Not everyone has the operator table memorized.
11617 ##### Example
11619     const unsigned int flag = 2;
11620     unsigned int a = flag;
11622     if (a & flag != 0)  // bad: means a&(flag != 0)
11624 Note: We recommend that programmers know their precedence table for the arithmetic operations, the logical operations, but consider mixing bitwise logical operations with other operators in need of parentheses.
11626     if ((a & flag) != 0)  // OK: works as intended
11628 ##### Note
11630 You should know enough not to need parentheses for:
11632     if (a < 0 || a <= max) {
11633         // ...
11634     }
11636 ##### Enforcement
11638 * Flag combinations of bitwise-logical operators and other operators.
11639 * Flag assignment operators not as the leftmost operator.
11640 * ???
11642 ### <a name="Res-ptr"></a>ES.42: Keep use of pointers simple and straightforward
11644 ##### Reason
11646 Complicated pointer manipulation is a major source of errors.
11648 ##### Note
11650 Use `gsl::span` instead.
11651 Pointers should [only refer to single objects](#Ri-array).
11652 Pointer arithmetic is fragile and easy to get wrong, the source of many, many bad bugs and security violations.
11653 `span` is a bounds-checked, safe type for accessing arrays of data.
11654 Access into an array with known bounds using a constant as a subscript can be validated by the compiler.
11656 ##### Example, bad
11658     void f(int* p, int count)
11659     {
11660         if (count < 2) return;
11662         int* q = p + 1;    // BAD
11664         ptrdiff_t d;
11665         int n;
11666         d = (p - &n);      // OK
11667         d = (q - p);       // OK
11669         int n = *p++;      // BAD
11671         if (count < 6) return;
11673         p[4] = 1;          // BAD
11675         p[count - 1] = 2;  // BAD
11677         use(&p[0], 3);     // BAD
11678     }
11680 ##### Example, good
11682     void f(span<int> a) // BETTER: use span in the function declaration
11683     {
11684         if (a.size() < 2) return;
11686         int n = a[0];      // OK
11688         span<int> q = a.subspan(1); // OK
11690         if (a.size() < 6) return;
11692         a[4] = 1;          // OK
11694         a[a.size() - 1] = 2;  // OK
11696         use(a.data(), 3);  // OK
11697     }
11699 ##### Note
11701 Subscripting with a variable is difficult for both tools and humans to validate as safe.
11702 `span` is a run-time bounds-checked, safe type for accessing arrays of data.
11703 `at()` is another alternative that ensures single accesses are bounds-checked.
11704 If iterators are needed to access an array, use the iterators from a `span` constructed over the array.
11706 ##### Example, bad
11708     void f(array<int, 10> a, int pos)
11709     {
11710         a[pos / 2] = 1; // BAD
11711         a[pos - 1] = 2; // BAD
11712         a[-1] = 3;    // BAD (but easily caught by tools) -- no replacement, just don't do this
11713         a[10] = 4;    // BAD (but easily caught by tools) -- no replacement, just don't do this
11714     }
11716 ##### Example, good
11718 Use a `span`:
11720     void f1(span<int, 10> a, int pos) // A1: Change parameter type to use span
11721     {
11722         a[pos / 2] = 1; // OK
11723         a[pos - 1] = 2; // OK
11724     }
11726     void f2(array<int, 10> arr, int pos) // A2: Add local span and use that
11727     {
11728         span<int> a = {arr.data(), pos};
11729         a[pos / 2] = 1; // OK
11730         a[pos - 1] = 2; // OK
11731     }
11733 Use `at()`:
11735     void f3(array<int, 10> a, int pos) // ALTERNATIVE B: Use at() for access
11736     {
11737         at(a, pos / 2) = 1; // OK
11738         at(a, pos - 1) = 2; // OK
11739     }
11741 ##### Example, bad
11743     void f()
11744     {
11745         int arr[COUNT];
11746         for (int i = 0; i < COUNT; ++i)
11747             arr[i] = i; // BAD, cannot use non-constant indexer
11748     }
11750 ##### Example, good
11752 Use a `span`:
11754     void f1()
11755     {
11756         int arr[COUNT];
11757         span<int> av = arr;
11758         for (int i = 0; i < COUNT; ++i)
11759             av[i] = i;
11760     }
11762 Use a `span` and range-`for`:
11764     void f1a()
11765     {
11766          int arr[COUNT];
11767          span<int, COUNT> av = arr;
11768          int i = 0;
11769          for (auto& e : av)
11770              e = i++;
11771     }
11773 Use `at()` for access:
11775     void f2()
11776     {
11777         int arr[COUNT];
11778         for (int i = 0; i < COUNT; ++i)
11779             at(arr, i) = i;
11780     }
11782 Use a range-`for`:
11784     void f3()
11785     {
11786         int arr[COUNT];
11787         int i = 0;
11788         for (auto& e : arr)
11789              e = i++;
11790     }
11792 ##### Note
11794 Tooling can offer rewrites of array accesses that involve dynamic index expressions to use `at()` instead:
11796     static int a[10];
11798     void f(int i, int j)
11799     {
11800         a[i + j] = 12;      // BAD, could be rewritten as ...
11801         at(a, i + j) = 12;  // OK -- bounds-checked
11802     }
11804 ##### Example
11806 Turning an array into a pointer (as the language does essentially always) removes opportunities for checking, so avoid it
11808     void g(int* p);
11810     void f()
11811     {
11812         int a[5];
11813         g(a);        // BAD: are we trying to pass an array?
11814         g(&a[0]);    // OK: passing one object
11815     }
11817 If you want to pass an array, say so:
11819     void g(int* p, size_t length);  // old (dangerous) code
11821     void g1(span<int> av); // BETTER: get g() changed.
11823     void f2()
11824     {
11825         int a[5];
11826         span<int> av = a;
11828         g(av.data(), av.size());   // OK, if you have no choice
11829         g1(a);                     // OK -- no decay here, instead use implicit span ctor
11830     }
11832 ##### Enforcement
11834 * Flag any arithmetic operation on an expression of pointer type that results in a value of pointer type.
11835 * Flag any indexing expression on an expression or variable of array type (either static array or `std::array`) where the indexer is not a compile-time constant expression with a value between `0` and the upper bound of the array.
11836 * Flag any expression that would rely on implicit conversion of an array type to a pointer type.
11838 This rule is part of the [bounds-safety profile](#SS-bounds).
11841 ### <a name="Res-order"></a>ES.43: Avoid expressions with undefined order of evaluation
11843 ##### Reason
11845 You have no idea what such code does. Portability.
11846 Even if it does something sensible for you, it might do something different on another compiler (e.g., the next release of your compiler) or with a different optimizer setting.
11848 ##### Note
11850 C++17 tightens up the rules for the order of evaluation:
11851 left-to-right except right-to-left in assignments, and the order of evaluation of function arguments is unspecified.
11853 However, remember that your code might be compiled with a pre-C++17 compiler (e.g., through cut-and-paste) so don't be too clever.
11855 ##### Example
11857     v[i] = ++i;   //  the result is undefined
11859 A good rule of thumb is that you should not read a value twice in an expression where you write to it.
11861 ##### Enforcement
11863 Can be detected by a good analyzer.
11865 ### <a name="Res-order-fct"></a>ES.44: Don't depend on order of evaluation of function arguments
11867 ##### Reason
11869 Because that order is unspecified.
11871 ##### Note
11873 C++17 tightens up the rules for the order of evaluation, but the order of evaluation of function arguments is still unspecified.
11875 ##### Example
11877     int i = 0;
11878     f(++i, ++i);
11880 Before C++17, the behavior is undefined, so the behavior could be anything (e.g., `f(2, 2)`).
11881 Since C++17, this code does not have undefined behavior, but it is still not specified which argument is evaluated first. The call will be `f(1, 2)` or `f(2, 1)`, but you don't know which.
11883 ##### Example
11885 Overloaded operators can lead to order of evaluation problems:
11887     f1()->m(f2());          // m(f1(), f2())
11888     cout << f1() << f2();   // operator<<(operator<<(cout, f1()), f2())
11890 In C++17, these examples work as expected (left to right) and assignments are evaluated right to left (just as ='s binding is right-to-left)
11892     f1() = f2();    // undefined behavior in C++14; in C++17, f2() is evaluated before f1()
11894 ##### Enforcement
11896 Can be detected by a good analyzer.
11898 ### <a name="Res-magic"></a>ES.45: Avoid "magic constants"; use symbolic constants
11900 ##### Reason
11902 Unnamed constants embedded in expressions are easily overlooked and often hard to understand:
11904 ##### Example
11906     for (int m = 1; m <= 12; ++m)   // don't: magic constant 12
11907         cout << month[m] << '\n';
11909 No, we don't all know that there are 12 months, numbered 1..12, in a year. Better:
11911     // months are indexed 1..12
11912     constexpr int first_month = 1;
11913     constexpr int last_month = 12;
11915     for (int m = first_month; m <= last_month; ++m)   // better
11916         cout << month[m] << '\n';
11918 Better still, don't expose constants:
11920     for (auto m : month)
11921         cout << m << '\n';
11923 ##### Enforcement
11925 Flag literals in code. Give a pass to `0`, `1`, `nullptr`, `\n`, `""`, and others on a positive list.
11927 ### <a name="Res-narrowing"></a>ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions
11929 ##### Reason
11931 A narrowing conversion destroys information, often unexpectedly so.
11933 ##### Example, bad
11935 A key example is basic narrowing:
11937     double d = 7.9;
11938     int i = d;    // bad: narrowing: i becomes 7
11939     i = (int) d;  // bad: we're going to claim this is still not explicit enough
11941     void f(int x, long y, double d)
11942     {
11943         char c1 = x;   // bad: narrowing
11944         char c2 = y;   // bad: narrowing
11945         char c3 = d;   // bad: narrowing
11946     }
11948 ##### Note
11950 The guidelines support library offers a `narrow_cast` operation for specifying that narrowing is acceptable and a `narrow` ("narrow if") that throws an exception if a narrowing would throw away legal values:
11952     i = gsl::narrow_cast<int>(d);   // OK (you asked for it): narrowing: i becomes 7
11953     i = gsl::narrow<int>(d);        // OK: throws narrowing_error
11955 We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type:
11957     double d = -7.9;
11958     unsigned u = 0;
11960     u = d;                               // bad: narrowing
11961     u = gsl::narrow_cast<unsigned>(d);   // OK (you asked for it): u becomes 4294967289
11962     u = gsl::narrow<unsigned>(d);        // OK: throws narrowing_error
11964 ##### Note
11966 This rule does not apply to [contextual conversions to bool](https://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions):
11968     if (ptr) do_something(*ptr);   // OK: ptr is used as a condition
11969     bool b = ptr;                  // bad: narrowing
11971 ##### Enforcement
11973 A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions:
11975 * Flag all floating-point to integer conversions (maybe only `float`->`char` and `double`->`int`. Here be dragons! we need data).
11976 * Flag all `long`->`char` (I suspect `int`->`char` is very common. Here be dragons! we need data).
11977 * Consider narrowing conversions for function arguments especially suspect.
11979 ### <a name="Res-nullptr"></a>ES.47: Use `nullptr` rather than `0` or `NULL`
11981 ##### Reason
11983 Readability. Minimize surprises: `nullptr` cannot be confused with an
11984 `int`. `nullptr` also has a well-specified (very restrictive) type, and thus
11985 works in more scenarios where type deduction might do the wrong thing on `NULL`
11986 or `0`.
11988 ##### Example
11990 Consider:
11992     void f(int);
11993     void f(char*);
11994     f(0);         // call f(int)
11995     f(nullptr);   // call f(char*)
11997 ##### Enforcement
11999 Flag uses of `0` and `NULL` for pointers. The transformation might be helped by simple program transformation.
12001 ### <a name="Res-casts"></a>ES.48: Avoid casts
12003 ##### Reason
12005 Casts are a well-known source of errors and make some optimizations unreliable.
12007 ##### Example, bad
12009     double d = 2;
12010     auto p = (long*)&d;
12011     auto q = (long long*)&d;
12012     cout << d << ' ' << *p << ' ' << *q << '\n';
12014 What would you think this fragment prints? The result is at best implementation defined. I got
12016     2 0 4611686018427387904
12018 Adding
12020     *q = 666;
12021     cout << d << ' ' << *p << ' ' << *q << '\n';
12023 I got
12025     3.29048e-321 666 666
12027 Surprised? I'm just glad I didn't crash the program.
12029 ##### Note
12031 Programmers who write casts typically assume that they know what they are doing,
12032 or that writing a cast makes the program "easier to read".
12033 In fact, they often disable the general rules for using values.
12034 Overload resolution and template instantiation usually pick the right function if there is a right function to pick.
12035 If there is not, maybe there ought to be, rather than applying a local fix (cast).
12037 ##### Notes
12039 Casts are necessary in a systems programming language.  For example, how else
12040 would we get the address of a device register into a pointer?  However, casts
12041 are seriously overused as well as a major source of errors.
12043 If you feel the need for a lot of casts, there might be a fundamental design problem.
12045 The [type profile](#Pro-type-reinterpretcast) bans `reinterpret_cast` and C-style casts.
12047 Never cast to `(void)` to ignore a `[[nodiscard]]`return value.
12048 If you deliberately want to discard such a result, first think hard about whether that is really a good idea (there is usually a good reason the author of the function or of the return type used `[[nodiscard]]` in the first place).
12049 If you still think it's appropriate and your code reviewer agrees, use `std::ignore =` to turn off the warning which is simple, portable, and easy to grep.
12051 ##### Alternatives
12053 Casts are widely (mis)used. Modern C++ has rules and constructs that eliminate the need for casts in many contexts, such as
12055 * Use templates
12056 * Use `std::variant`
12057 * Rely on the well-defined, safe, implicit conversions between pointer types
12058 * Use `std::ignore =` to ignore `[[nodiscard]]` values.
12060 ##### Enforcement
12062 * Flag all C-style casts, including to `void`.
12063 * Flag functional style casts using `Type(value)`. Use `Type{value}` instead which is not narrowing. (See [ES.64](#Res-construct).)
12064 * Flag [identity casts](#Pro-type-identitycast) between pointer types, where the source and target types are the same (#Pro-type-identitycast).
12065 * Flag an explicit pointer cast that could be [implicit](#Pro-type-implicitpointercast).
12067 ### <a name="Res-casts-named"></a>ES.49: If you must use a cast, use a named cast
12069 ##### Reason
12071 Readability. Error avoidance.
12072 Named casts are more specific than a C-style or functional cast, allowing the compiler to catch some errors.
12074 The named casts are:
12076 * `static_cast`
12077 * `const_cast`
12078 * `reinterpret_cast`
12079 * `dynamic_cast`
12080 * `std::move`         // `move(x)` is an rvalue reference to `x`
12081 * `std::forward`      // `forward<T>(x)` is an rvalue or an lvalue reference to `x` depending on `T`
12082 * `gsl::narrow_cast`  // `narrow_cast<T>(x)` is `static_cast<T>(x)`
12083 * `gsl::narrow`       // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
12085 ##### Example
12087     class B { /* ... */ };
12088     class D { /* ... */ };
12090     template<typename D> D* upcast(B* pb)
12091     {
12092         D* pd0 = pb;                        // error: no implicit conversion from B* to D*
12093         D* pd1 = (D*)pb;                    // legal, but what is done?
12094         D* pd2 = static_cast<D*>(pb);       // error: D is not derived from B
12095         D* pd3 = reinterpret_cast<D*>(pb);  // OK: on your head be it!
12096         D* pd4 = dynamic_cast<D*>(pb);      // OK: return nullptr
12097         // ...
12098     }
12100 The example was synthesized from real-world bugs where `D` used to be derived from `B`, but someone refactored the hierarchy.
12101 The C-style cast is dangerous because it can do any kind of conversion, depriving us of any protection from mistakes (now or in the future).
12103 ##### Note
12105 When converting between types with no information loss (e.g. from `float` to
12106 `double` or from `int32` to `int64`), brace initialization might be used instead.
12108     double d {some_float};
12109     int64_t i {some_int32};
12111 This makes it clear that the type conversion was intended and also prevents
12112 conversions between types that might result in loss of precision. (It is a
12113 compilation error to try to initialize a `float` from a `double` in this fashion,
12114 for example.)
12116 ##### Note
12118 `reinterpret_cast` can be essential, but the essential uses (e.g., turning a machine address into pointer) are not type safe:
12120     auto p = reinterpret_cast<Device_register>(0x800);  // inherently dangerous
12123 ##### Enforcement
12125 * Flag all C-style casts, including to `void`.
12126 * Flag functional style casts using `Type(value)`. Use `Type{value}` instead which is not narrowing. (See [ES.64](#Res-construct).)
12127 * The [type profile](#Pro-type-reinterpretcast) bans `reinterpret_cast`.
12128 * The [type profile](#Pro-type-arithmeticcast) warns when using `static_cast` between arithmetic types.
12130 ### <a name="Res-casts-const"></a>ES.50: Don't cast away `const`
12132 ##### Reason
12134 It makes a lie out of `const`.
12135 If the variable is actually declared `const`, modifying it results in undefined behavior.
12137 ##### Example, bad
12139     void f(const int& x)
12140     {
12141         const_cast<int&>(x) = 42;   // BAD
12142     }
12144     static int i = 0;
12145     static const int j = 0;
12147     f(i); // silent side effect
12148     f(j); // undefined behavior
12150 ##### Example
12152 Sometimes, you might be tempted to resort to `const_cast` to avoid code duplication, such as when two accessor functions that differ only in `const`-ness have similar implementations. For example:
12154     class Bar;
12156     class Foo {
12157     public:
12158         // BAD, duplicates logic
12159         Bar& get_bar()
12160         {
12161             /* complex logic around getting a non-const reference to my_bar */
12162         }
12164         const Bar& get_bar() const
12165         {
12166             /* same complex logic around getting a const reference to my_bar */
12167         }
12168     private:
12169         Bar my_bar;
12170     };
12172 Instead, prefer to share implementations. Normally, you can just have the non-`const` function call the `const` function. However, when there is complex logic this can lead to the following pattern that still resorts to a `const_cast`:
12174     class Foo {
12175     public:
12176         // not great, non-const calls const version but resorts to const_cast
12177         Bar& get_bar()
12178         {
12179             return const_cast<Bar&>(static_cast<const Foo&>(*this).get_bar());
12180         }
12181         const Bar& get_bar() const
12182         {
12183             /* the complex logic around getting a const reference to my_bar */
12184         }
12185     private:
12186         Bar my_bar;
12187     };
12189 Although this pattern is safe when applied correctly, because the caller must have had a non-`const` object to begin with, it's not ideal because the safety is hard to enforce automatically as a checker rule.
12191 Instead, prefer to put the common code in a common helper function -- and make it a template so that it deduces `const`. This doesn't use any `const_cast` at all:
12193     class Foo {
12194     public:                         // good
12195               Bar& get_bar()       { return get_bar_impl(*this); }
12196         const Bar& get_bar() const { return get_bar_impl(*this); }
12197     private:
12198         Bar my_bar;
12200         template<class T>           // good, deduces whether T is const or non-const
12201         static auto& get_bar_impl(T& t)
12202             { /* the complex logic around getting a possibly-const reference to my_bar */ }
12203     };
12205 Note: Don't do large non-dependent work inside a template, which leads to code bloat. For example, a further improvement would be if all or part of `get_bar_impl` can be non-dependent and factored out into a common non-template function, for a potentially big reduction in code size.
12207 ##### Exception
12209 You might need to cast away `const` when calling `const`-incorrect functions.
12210 Prefer to wrap such functions in inline `const`-correct wrappers to encapsulate the cast in one place.
12212 ##### Example
12214 Sometimes, "cast away `const`" is to allow the updating of some transient information of an otherwise immutable object.
12215 Examples are caching, memoization, and precomputation.
12216 Such examples are often handled as well or better using `mutable` or an indirection than with a `const_cast`.
12218 Consider keeping previously computed results around for a costly operation:
12220     int compute(int x); // compute a value for x; assume this to be costly
12222     class Cache {   // some type implementing a cache for an int->int operation
12223     public:
12224         pair<bool, int> find(int x) const;   // is there a value for x?
12225         void set(int x, int v);             // make y the value for x
12226         // ...
12227     private:
12228         // ...
12229     };
12231     class X {
12232     public:
12233         int get_val(int x)
12234         {
12235             auto p = cache.find(x);
12236             if (p.first) return p.second;
12237             int val = compute(x);
12238             cache.set(x, val); // insert value for x
12239             return val;
12240         }
12241         // ...
12242     private:
12243         Cache cache;
12244     };
12246 Here, `get_val()` is logically constant, so we would like to make it a `const` member.
12247 To do this we still need to mutate `cache`, so people sometimes resort to a `const_cast`:
12249     class X {   // Suspicious solution based on casting
12250     public:
12251         int get_val(int x) const
12252         {
12253             auto p = cache.find(x);
12254             if (p.first) return p.second;
12255             int val = compute(x);
12256             const_cast<Cache&>(cache).set(x, val);   // ugly
12257             return val;
12258         }
12259         // ...
12260     private:
12261         Cache cache;
12262     };
12264 Fortunately, there is a better solution:
12265 State that `cache` is mutable even for a `const` object:
12267     class X {   // better solution
12268     public:
12269         int get_val(int x) const
12270         {
12271             auto p = cache.find(x);
12272             if (p.first) return p.second;
12273             int val = compute(x);
12274             cache.set(x, val);
12275             return val;
12276         }
12277         // ...
12278     private:
12279         mutable Cache cache;
12280     };
12282 An alternative solution would be to store a pointer to the `cache`:
12284     class X {   // OK, but slightly messier solution
12285     public:
12286         int get_val(int x) const
12287         {
12288             auto p = cache->find(x);
12289             if (p.first) return p.second;
12290             int val = compute(x);
12291             cache->set(x, val);
12292             return val;
12293         }
12294         // ...
12295     private:
12296         unique_ptr<Cache> cache;
12297     };
12299 That solution is the most flexible, but requires explicit construction and destruction of `*cache`
12300 (most likely in the constructor and destructor of `X`).
12302 In any variant, we must guard against data races on the `cache` in multi-threaded code, possibly using a `std::mutex`.
12304 ##### Enforcement
12306 * Flag `const_cast`s.
12307 * This rule is part of the [type-safety profile](#Pro-type-constcast) for the related Profile.
12309 ### <a name="Res-range-checking"></a>ES.55: Avoid the need for range checking
12311 ##### Reason
12313 Constructs that cannot overflow do not overflow (and usually run faster):
12315 ##### Example
12317     for (auto& x : v)      // print all elements of v
12318         cout << x << '\n';
12320     auto p = find(v, x);   // find x in v
12322 ##### Enforcement
12324 Look for explicit range checks and heuristically suggest alternatives.
12326 ### <a name="Res-move"></a>ES.56: Write `std::move()` only when you need to explicitly move an object to another scope
12328 ##### Reason
12330 We move, rather than copy, to avoid duplication and for improved performance.
12332 A move typically leaves behind an empty object ([C.64](#Rc-move-semantic)), which can be surprising or even dangerous, so we try to avoid moving from lvalues (they might be accessed later).
12334 ##### Notes
12336 Moving is done implicitly when the source is an rvalue (e.g., value in a `return` treatment or a function result), so don't pointlessly complicate code in those cases by writing `move` explicitly. Instead, write short functions that return values, and both the function's return and the caller's accepting of the return will be optimized naturally.
12338 In general, following the guidelines in this document (including not making variables' scopes needlessly large, writing short functions that return values, returning local variables) help eliminate most need for explicit `std::move`.
12340 Explicit `move` is needed to explicitly move an object to another scope, notably to pass it to a "sink" function and in the implementations of the move operations themselves (move constructor, move assignment operator) and swap operations.
12342 ##### Example, bad
12344     void sink(X&& x);   // sink takes ownership of x
12346     void user()
12347     {
12348         X x;
12349         // error: cannot bind an lvalue to a rvalue reference
12350         sink(x);
12351         // OK: sink takes the contents of x, x must now be assumed to be empty
12352         sink(std::move(x));
12354         // ...
12356         // probably a mistake
12357         use(x);
12358     }
12360 Usually, a `std::move()` is used as an argument to a `&&` parameter.
12361 And after you do that, assume the object has been moved from (see [C.64](#Rc-move-semantic)) and don't read its state again until you first set it to a new value.
12363     void f()
12364     {
12365         string s1 = "supercalifragilisticexpialidocious";
12367         string s2 = s1;             // ok, takes a copy
12368         assert(s1 == "supercalifragilisticexpialidocious");  // ok
12370         // bad, if you want to keep using s1's value
12371         string s3 = move(s1);
12373         // bad, assert will likely fail, s1 likely changed
12374         assert(s1 == "supercalifragilisticexpialidocious");
12375     }
12377 ##### Example
12379     void sink(unique_ptr<widget> p);  // pass ownership of p to sink()
12381     void f()
12382     {
12383         auto w = make_unique<widget>();
12384         // ...
12385         sink(std::move(w));               // ok, give to sink()
12386         // ...
12387         sink(w);    // Error: unique_ptr is carefully designed so that you cannot copy it
12388     }
12390 ##### Notes
12392 `std::move()` is a cast to `&&` in disguise; it doesn't itself move anything, but marks a named object as a candidate that can be moved from.
12393 The language already knows the common cases where objects can be moved from, especially when returning values from functions, so don't complicate code with redundant `std::move()`'s.
12395 Never write `std::move()` just because you've heard "it's more efficient."
12396 In general, don't believe claims of "efficiency" without data (???).
12397 In general, don't complicate your code without reason (??).
12398 Never write `std::move()` on a const object, it is silently transformed into a copy (see Item 23 in [Meyers15](#Meyers15))
12400 ##### Example, bad
12402     vector<int> make_vector()
12403     {
12404         vector<int> result;
12405         // ... load result with data
12406         return std::move(result);       // bad; just write "return result;"
12407     }
12409 Never write `return move(local_variable);`, because the language already knows the variable is a move candidate.
12410 Writing `move` in this code won't help, and can actually be detrimental because on some compilers it interferes with RVO (the return value optimization) by creating an additional reference alias to the local variable.
12413 ##### Example, bad
12415     vector<int> v = std::move(make_vector());   // bad; the std::move is entirely redundant
12417 Never write `move` on a returned value such as `x = move(f());` where `f` returns by value.
12418 The language already knows that a returned value is a temporary object that can be moved from.
12420 ##### Example
12422     void mover(X&& x)
12423     {
12424         call_something(std::move(x));         // ok
12425         call_something(std::forward<X>(x));   // bad, don't std::forward an rvalue reference
12426         call_something(x);                    // suspicious, why not std::move?
12427     }
12429     template<class T>
12430     void forwarder(T&& t)
12431     {
12432         call_something(std::move(t));         // bad, don't std::move a forwarding reference
12433         call_something(std::forward<T>(t));   // ok
12434         call_something(t);                    // suspicious, why not std::forward?
12435     }
12437 ##### Enforcement
12439 * Flag use of `std::move(x)` where `x` is an rvalue or the language will already treat it as an rvalue, including `return std::move(local_variable);` and `std::move(f())` on a function that returns by value.
12440 * Flag functions taking an `S&&` parameter if there is no `const S&` overload to take care of lvalues.
12441 * Flag a `std::move`d argument passed to a parameter, except when the parameter type is an `X&&` rvalue reference or the type is move-only and the parameter is passed by value.
12442 * Flag when `std::move` is applied to a forwarding reference (`T&&` where `T` is a template parameter type). Use `std::forward` instead.
12443 * Flag when `std::move` is applied to other than an rvalue reference to non-const. (More general case of the previous rule to cover the non-forwarding cases.)
12444 * Flag when `std::forward` is applied to an rvalue reference (`X&&` where `X` is a non-template parameter type). Use `std::move` instead.
12445 * Flag when `std::forward` is applied to other than a forwarding reference. (More general case of the previous rule to cover the non-moving cases.)
12446 * Flag when an object is potentially moved from and the next operation is a `const` operation; there should first be an intervening non-`const` operation, ideally assignment, to first reset the object's value.
12448 ### <a name="Res-new"></a>ES.60: Avoid `new` and `delete` outside resource management functions
12450 ##### Reason
12452 Direct resource management in application code is error-prone and tedious.
12454 ##### Note
12456 This is also known as the rule of "No naked `new`!"
12458 ##### Example, bad
12460     void f(int n)
12461     {
12462         auto p = new X[n];   // n default constructed Xs
12463         // ...
12464         delete[] p;
12465     }
12467 There can be code in the `...` part that causes the `delete` never to happen.
12469 **See also**: [R: Resource management](#S-resource)
12471 ##### Enforcement
12473 Flag naked `new`s and naked `delete`s.
12475 ### <a name="Res-del"></a>ES.61: Delete arrays using `delete[]` and non-arrays using `delete`
12477 ##### Reason
12479 That's what the language requires, and mismatches can lead to resource release errors and/or memory corruption.
12481 ##### Example, bad
12483     void f(int n)
12484     {
12485         auto p = new X[n];   // n default constructed Xs
12486         // ...
12487         delete p;   // error: just delete the object p, rather than delete the array p[]
12488     }
12490 ##### Note
12492 This example not only violates the [no naked `new` rule](#Res-new) as in the previous example, it has many more problems.
12494 ##### Enforcement
12496 * Flag mismatched `new` and `delete` if they are in the same scope.
12497 * Flag mismatched `new` and `delete` if they are in a constructor/destructor pair.
12499 ### <a name="Res-arr2"></a>ES.62: Don't compare pointers into different arrays
12501 ##### Reason
12503 The result of doing so is undefined.
12505 ##### Example, bad
12507     void f()
12508     {
12509         int a1[7];
12510         int a2[9];
12511         if (&a1[5] < &a2[7]) {}       // bad: undefined
12512         if (0 < &a1[5] - &a2[7]) {}   // bad: undefined
12513     }
12515 ##### Note
12517 This example has many more problems.
12519 ##### Enforcement
12523 ### <a name="Res-slice"></a>ES.63: Don't slice
12525 ##### Reason
12527 Slicing -- that is, copying only part of an object using assignment or initialization -- most often leads to errors because
12528 the object was meant to be considered as a whole.
12529 In the rare cases where the slicing was deliberate the code can be surprising.
12531 ##### Example
12533     class Shape { /* ... */ };
12534     class Circle : public Shape { /* ... */ Point c; int r; };
12536     Circle c {{0, 0}, 42};
12537     Shape s {c};    // copy construct only the Shape part of Circle
12538     s = c;          // or copy assign only the Shape part of Circle
12540     void assign(const Shape& src, Shape& dest)
12541     {
12542         dest = src;
12543     }
12544     Circle c2 {{1, 1}, 43};
12545     assign(c, c2);   // oops, not the whole state is transferred
12546     assert(c == c2); // if we supply copying, we should also provide comparison,
12547                      // but this will likely return false
12549 The result will be meaningless because the center and radius will not be copied from `c` into `s`.
12550 The first defense against this is to [define the base class `Shape` not to allow this](#Rc-copy-virtual).
12552 ##### Alternative
12554 If you mean to slice, define an explicit operation to do so.
12555 This saves readers from confusion.
12556 For example:
12558     class Smiley : public Circle {
12559         public:
12560         Circle copy_circle();
12561         // ...
12562     };
12564     Smiley sm { /* ... */ };
12565     Circle c1 {sm};  // ideally prevented by the definition of Circle
12566     Circle c2 {sm.copy_circle()};
12568 ##### Enforcement
12570 Warn against slicing.
12572 ### <a name="Res-construct"></a>ES.64: Use the `T{e}`notation for construction
12574 ##### Reason
12576 The `T{e}` construction syntax makes it explicit that construction is desired.
12577 The `T{e}` construction syntax doesn't allow narrowing.
12578 `T{e}` is the only safe and general expression for constructing a value of type `T` from an expression `e`.
12579 The casts notations `T(e)` and `(T)e` are neither safe nor general.
12581 ##### Example
12583 For built-in types, the construction notation protects against narrowing and reinterpretation
12585     void use(char ch, int i, double d, char* p, long long lng)
12586     {
12587         int x1 = int{ch};     // OK, but redundant
12588         int x2 = int{d};      // error: double->int narrowing; use a cast if you need to
12589         int x3 = int{p};      // error: pointer to->int; use a reinterpret_cast if you really need to
12590         int x4 = int{lng};    // error: long long->int narrowing; use a cast if you need to
12592         int y1 = int(ch);     // OK, but redundant
12593         int y2 = int(d);      // bad: double->int narrowing; use a cast if you need to
12594         int y3 = int(p);      // bad: pointer to->int; use a reinterpret_cast if you really need to
12595         int y4 = int(lng);    // bad: long long->int narrowing; use a cast if you need to
12597         int z1 = (int)ch;     // OK, but redundant
12598         int z2 = (int)d;      // bad: double->int narrowing; use a cast if you need to
12599         int z3 = (int)p;      // bad: pointer to->int; use a reinterpret_cast if you really need to
12600         int z4 = (int)lng;    // bad: long long->int narrowing; use a cast if you need to
12601     }
12603 The integer to/from pointer conversions are implementation defined when using the `T(e)` or `(T)e` notations, and non-portable
12604 between platforms with different integer and pointer sizes.
12606 ##### Note
12608 [Avoid casts](#Res-casts) (explicit type conversion) and if you must [prefer named casts](#Res-casts-named).
12610 ##### Note
12612 When unambiguous, the `T` can be left out of `T{e}`.
12614     complex<double> f(complex<double>);
12616     auto z = f({2*pi, 1});
12618 ##### Note
12620 The construction notation is the most general [initializer notation](#Res-list).
12622 ##### Exception
12624 `std::vector` and other containers were defined before we had `{}` as a notation for construction.
12625 Consider:
12627     vector<string> vs {10};                           // ten empty strings
12628     vector<int> vi1 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  // ten elements 1..10
12629     vector<int> vi2 {10};                             // one element with the value 10
12631 How do we get a `vector` of 10 default initialized `int`s?
12633     vector<int> v3(10); // ten elements with value 0
12635 The use of `()` rather than `{}` for number of elements is conventional (going back to the early 1980s), hard to change, but still
12636 a design error: for a container where the element type can be confused with the number of elements, we have an ambiguity that
12637 must be resolved.
12638 The conventional resolution is to interpret `{10}` as a list of one element and use `(10)` to distinguish a size.
12640 This mistake need not be repeated in new code.
12641 We can define a type to represent the number of elements:
12643     struct Count { int n; };
12645     template<typename T>
12646     class Vector {
12647     public:
12648         Vector(Count n);                     // n default-initialized elements
12649         Vector(initializer_list<T> init);    // init.size() elements
12650         // ...
12651     };
12653     Vector<int> v1{10};
12654     Vector<int> v2{Count{10}};
12655     Vector<Count> v3{Count{10}};    // yes, there is still a very minor problem
12657 The main problem left is to find a suitable name for `Count`.
12659 ##### Enforcement
12661 Flag the C-style `(T)e` and functional-style `T(e)` casts.
12664 ### <a name="Res-deref"></a>ES.65: Don't dereference an invalid pointer
12666 ##### Reason
12668 Dereferencing an invalid pointer, such as `nullptr`, is undefined behavior, typically leading to immediate crashes,
12669 wrong results, or memory corruption.
12671 ##### Note
12673 This rule is an obvious and well-known language rule, but can be hard to follow.
12674 It takes good coding style, library support, and static analysis to eliminate violations without major overhead.
12675 This is a major part of the discussion of [C++'s model for type- and resource-safety](#Stroustrup15).
12677 **See also**:
12679 * Use [RAII](#Rr-raii) to avoid lifetime problems.
12680 * Use [unique_ptr](#Rf-unique_ptr) to avoid lifetime problems.
12681 * Use [shared_ptr](#Rf-shared_ptr) to avoid lifetime problems.
12682 * Use [references](#Rf-ptr-ref) when `nullptr` isn't a possibility.
12683 * Use [not_null](#Rf-nullptr) to catch unexpected `nullptr` early.
12684 * Use the [bounds profile](#SS-bounds) to avoid range errors.
12687 ##### Example
12689     void f()
12690     {
12691         int x = 0;
12692         int* p = &x;
12694         if (condition()) {
12695             int y = 0;
12696             p = &y;
12697         } // invalidates p
12699         *p = 42;            // BAD, p might be invalid if the branch was taken
12700     }
12702 To resolve the problem, either extend the lifetime of the object the pointer is intended to refer to, or shorten the lifetime of the pointer (move the dereference to before the pointed-to object's lifetime ends).
12704     void f1()
12705     {
12706         int x = 0;
12707         int* p = &x;
12709         int y = 0;
12710         if (condition()) {
12711             p = &y;
12712         }
12714         *p = 42;            // OK, p points to x or y and both are still in scope
12715     }
12717 Unfortunately, most invalid pointer problems are harder to spot and harder to fix.
12719 ##### Example
12721     void f(int* p)
12722     {
12723         int x = *p; // BAD: how do we know that p is valid?
12724     }
12726 There is a huge amount of such code.
12727 Most works -- after lots of testing -- but in isolation it is impossible to tell whether `p` could be the `nullptr`.
12728 Consequently, this is also a major source of errors.
12729 There are many approaches to dealing with this potential problem:
12731     void f1(int* p) // deal with nullptr
12732     {
12733         if (!p) {
12734             // deal with nullptr (allocate, return, throw, make p point to something, whatever
12735         }
12736         int x = *p;
12737     }
12739 There are two potential problems with testing for `nullptr`:
12741 * it is not always obvious what to do if we find `nullptr`
12742 * the test can be redundant and/or relatively expensive
12743 * it is not obvious if the test is to protect against a violation or part of the required logic.
12745 <!-- comment needed for code block after list -->
12746     void f2(int* p) // state that p is not supposed to be nullptr
12747     {
12748         assert(p);
12749         int x = *p;
12750     }
12752 This would carry a cost only when the assertion checking was enabled and would give a compiler/analyzer useful information.
12753 This would work even better if/when C++ gets direct support for contracts:
12755     void f3(int* p) // state that p is not supposed to be nullptr
12756         [[expects: p]]
12757     {
12758         int x = *p;
12759     }
12761 Alternatively, we could use `gsl::not_null` to ensure that `p` is not the `nullptr`.
12763     void f(not_null<int*> p)
12764     {
12765         int x = *p;
12766     }
12768 These remedies take care of `nullptr` only.
12769 Remember that there are other ways of getting an invalid pointer.
12771 ##### Example
12773     void f(int* p)  // old code, doesn't use owner
12774     {
12775         delete p;
12776     }
12778     void g()        // old code: uses naked new
12779     {
12780         auto q = new int{7};
12781         f(q);
12782         int x = *q; // BAD: dereferences invalid pointer
12783     }
12785 ##### Example
12787     void f()
12788     {
12789         vector<int> v(10);
12790         int* p = &v[5];
12791         v.push_back(99); // could reallocate v's elements
12792         int x = *p; // BAD: dereferences potentially invalid pointer
12793     }
12795 ##### Enforcement
12797 This rule is part of the [lifetime safety profile](#SS-lifetime)
12799 * Flag a dereference of a pointer that points to an object that has gone out of scope
12800 * Flag a dereference of a pointer that might have been invalidated by assigning a `nullptr`
12801 * Flag a dereference of a pointer that might have been invalidated by a `delete`
12802 * Flag a dereference to a pointer to a container element that might have been invalidated by dereference
12805 ## ES.stmt: Statements
12807 Statements control the flow of control (except for function calls and exception throws, which are expressions).
12809 ### <a name="Res-switch-if"></a>ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice
12811 ##### Reason
12813 * Readability.
12814 * Efficiency: A `switch` compares against constants and is usually better optimized than a series of tests in an `if`-`then`-`else` chain.
12815 * A `switch` enables some heuristic consistency checking. For example, have all values of an `enum` been covered? If not, is there a `default`?
12817 ##### Example
12819     void use(int n)
12820     {
12821         switch (n) {   // good
12822         case 0:
12823             // ...
12824             break;
12825         case 7:
12826             // ...
12827             break;
12828         default:
12829             // ...
12830             break;
12831         }
12832     }
12834 rather than:
12836     void use2(int n)
12837     {
12838         if (n == 0)   // bad: if-then-else chain comparing against a set of constants
12839             // ...
12840         else if (n == 7)
12841             // ...
12842     }
12844 ##### Enforcement
12846 Flag `if`-`then`-`else` chains that check against constants (only).
12848 ### <a name="Res-for-range"></a>ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice
12850 ##### Reason
12852 Readability. Error prevention. Efficiency.
12854 ##### Example
12856     for (gsl::index i = 0; i < v.size(); ++i)   // bad
12857         cout << v[i] << '\n';
12859     for (auto p = v.begin(); p != v.end(); ++p)   // bad
12860         cout << *p << '\n';
12862     for (auto& x : v)    // OK
12863         cout << x << '\n';
12865     for (gsl::index i = 1; i < v.size(); ++i) // touches two elements: can't be a range-for
12866         cout << v[i] + v[i - 1] << '\n';
12868     for (gsl::index i = 0; i < v.size(); ++i) // possible side effect: can't be a range-for
12869         cout << f(v, &v[i]) << '\n';
12871     for (gsl::index i = 0; i < v.size(); ++i) { // body messes with loop variable: can't be a range-for
12872         if (i % 2 != 0)
12873             cout << v[i] << '\n'; // output odd elements
12874     }
12876 A human or a good static analyzer might determine that there really isn't a side effect on `v` in `f(v, &v[i])` so that the loop can be rewritten.
12878 "Messing with the loop variable" in the body of a loop is typically best avoided.
12880 ##### Note
12882 Don't use expensive copies of the loop variable of a range-`for` loop:
12884     for (string s : vs) // ...
12886 This will copy each element of `vs` into `s`. Better:
12888     for (string& s : vs) // ...
12890 Better still, if the loop variable isn't modified or copied:
12892     for (const string& s : vs) // ...
12894 ##### Enforcement
12896 Look at loops, if a traditional loop just looks at each element of a sequence, and there are no side effects on what it does with the elements, rewrite the loop to a ranged-`for` loop.
12898 ### <a name="Res-for-while"></a>ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable
12900 ##### Reason
12902 Readability: the complete logic of the loop is visible "up front". The scope of the loop variable can be limited.
12904 ##### Example
12906     for (gsl::index i = 0; i < vec.size(); i++) {
12907         // do work
12908     }
12910 ##### Example, bad
12912     int i = 0;
12913     while (i < vec.size()) {
12914         // do work
12915         i++;
12916     }
12918 ##### Enforcement
12922 ### <a name="Res-while-for"></a>ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable
12924 ##### Reason
12926 Readability.
12928 ##### Example
12930     int events = 0;
12931     for (; wait_for_event(); ++events) {  // bad, confusing
12932         // ...
12933     }
12935 The "event loop" is misleading because the `events` counter has nothing to do with the loop condition (`wait_for_event()`).
12936 Better
12938     int events = 0;
12939     while (wait_for_event()) {      // better
12940         ++events;
12941         // ...
12942     }
12944 ##### Enforcement
12946 Flag actions in `for`-initializers and `for`-increments that do not relate to the `for`-condition.
12948 ### <a name="Res-for-init"></a>ES.74: Prefer to declare a loop variable in the initializer part of a `for`-statement
12950 See [ES.6](#Res-cond)
12952 ### <a name="Res-do"></a>ES.75: Avoid `do`-statements
12954 ##### Reason
12956 Readability, avoidance of errors.
12957 The termination condition is at the end (where it can be overlooked) and the condition is not checked the first time through.
12959 ##### Example
12961     int x;
12962     do {
12963         cin >> x;
12964         // ...
12965     } while (x < 0);
12967 ##### Note
12969 Yes, there are genuine examples where a `do`-statement is a clear statement of a solution, but also many bugs.
12971 ##### Enforcement
12973 Flag `do`-statements.
12975 ### <a name="Res-goto"></a>ES.76: Avoid `goto`
12977 ##### Reason
12979 Readability, avoidance of errors. There are better control structures for humans; `goto` is for machine generated code.
12981 ##### Exception
12983 Breaking out of a nested loop.
12984 In that case, always jump forwards.
12986     for (int i = 0; i < imax; ++i)
12987         for (int j = 0; j < jmax; ++j) {
12988             if (a[i][j] > elem_max) goto finished;
12989             // ...
12990         }
12991     finished:
12992     // ...
12994 ##### Example, bad
12996 There is a fair amount of use of the C goto-exit idiom:
12998     void f()
12999     {
13000         // ...
13001             goto exit;
13002         // ...
13003             goto exit;
13004         // ...
13005     exit:
13006         // ... common cleanup code ...
13007     }
13009 This is an ad-hoc simulation of destructors.
13010 Declare your resources with handles with destructors that clean up.
13011 If for some reason you cannot handle all cleanup with destructors for the variables used,
13012 consider `gsl::finally()` as a cleaner and more reliable alternative to `goto exit`
13014 ##### Enforcement
13016 * Flag `goto`. Better still flag all `goto`s that do not jump from a nested loop to the statement immediately after a nest of loops.
13018 ### <a name="Res-continue"></a>ES.77: Minimize the use of `break` and `continue` in loops
13020 ##### Reason
13022  In a non-trivial loop body, it is easy to overlook a `break` or a `continue`.
13024  A `break` in a loop has a dramatically different meaning than a `break` in a `switch`-statement
13025  (and you can have `switch`-statement in a loop and a loop in a `switch`-case).
13027 ##### Example
13029     switch(x) {
13030     case 1 :
13031         while (/* some condition */) {
13032             // ...
13033         break;
13034         } // Oops! break switch or break while intended?
13035     case 2 :
13036         // ...
13037         break;
13038     }
13040 ##### Alternative
13042 Often, a loop that requires a `break` is a good candidate for a function (algorithm), in which case the `break` becomes a `return`.
13044     //Original code: break inside loop
13045     void use1()
13046     {
13047         std::vector<T> vec = {/* initialized with some values */};
13048         T value;
13049         for (const T item : vec) {
13050             if (/* some condition*/) {
13051                 value = item;
13052                 break;
13053             }
13054         }
13055         /* then do something with value */
13056     }
13058     //BETTER: create a function and return inside loop
13059     T search(const std::vector<T> &vec)
13060     {
13061         for (const T &item : vec) {
13062             if (/* some condition*/) return item;
13063         }
13064         return T(); //default value
13065     }
13067     void use2()
13068     {
13069         std::vector<T> vec = {/* initialized with some values */};
13070         T value = search(vec);
13071         /* then do something with value */
13072     }
13074 Often, a loop that uses `continue` can equivalently and as clearly be expressed by an `if`-statement.
13076     for (int item : vec) {  // BAD
13077         if (item%2 == 0) continue;
13078         if (item == 5) continue;
13079         if (item > 10) continue;
13080         /* do something with item */
13081     }
13083     for (int item : vec) {  // GOOD
13084         if (item%2 != 0 && item != 5 && item <= 10) {
13085             /* do something with item */
13086         }
13087     }
13089 ##### Note
13091 If you really need to break out a loop, a `break` is typically better than alternatives such as [modifying the loop variable](#Res-loop-counter) or a [`goto`](#Res-goto):
13094 ##### Enforcement
13098 ### <a name="Res-break"></a>ES.78: Don't rely on implicit fallthrough in `switch` statements
13100 ##### Reason
13102 Always end a non-empty `case` with a `break`. Accidentally leaving out a `break` is a fairly common bug.
13103 A deliberate fallthrough can be a maintenance hazard and should be rare and explicit.
13105 ##### Example
13107     switch (eventType) {
13108     case Information:
13109         update_status_bar();
13110         break;
13111     case Warning:
13112         write_event_log();
13113         // Bad - implicit fallthrough
13114     case Error:
13115         display_error_window();
13116         break;
13117     }
13119 Multiple case labels of a single statement is OK:
13121     switch (x) {
13122     case 'a':
13123     case 'b':
13124     case 'f':
13125         do_something(x);
13126         break;
13127     }
13129 Return statements in a case label are also OK:
13131     switch (x) {
13132     case 'a':
13133         return 1;
13134     case 'b':
13135         return 2;
13136     case 'c':
13137         return 3;
13138     }
13140 ##### Exceptions
13142 In rare cases if fallthrough is deemed appropriate, be explicit and use the `[[fallthrough]]` annotation:
13144     switch (eventType) {
13145     case Information:
13146         update_status_bar();
13147         break;
13148     case Warning:
13149         write_event_log();
13150         [[fallthrough]];
13151     case Error:
13152         display_error_window();
13153         break;
13154     }
13156 ##### Note
13158 ##### Enforcement
13160 Flag all implicit fallthroughs from non-empty `case`s.
13163 ### <a name="Res-default"></a>ES.79: Use `default` to handle common cases (only)
13165 ##### Reason
13167  Code clarity.
13168  Improved opportunities for error detection.
13170 ##### Example
13172     enum E { a, b, c, d };
13174     void f1(E x)
13175     {
13176         switch (x) {
13177         case a:
13178             do_something();
13179             break;
13180         case b:
13181             do_something_else();
13182             break;
13183         default:
13184             take_the_default_action();
13185             break;
13186         }
13187     }
13189 Here it is clear that there is a default action and that cases `a` and `b` are special.
13191 ##### Example
13193 But what if there is no default action and you mean to handle only specific cases?
13194 In that case, have an empty default or else it is impossible to know if you meant to handle all cases:
13196     void f2(E x)
13197     {
13198         switch (x) {
13199         case a:
13200             do_something();
13201             break;
13202         case b:
13203             do_something_else();
13204             break;
13205         default:
13206             // do nothing for the rest of the cases
13207             break;
13208         }
13209     }
13211 If you leave out the `default`, a maintainer and/or a compiler might reasonably assume that you intended to handle all cases:
13213     void f2(E x)
13214     {
13215         switch (x) {
13216         case a:
13217             do_something();
13218             break;
13219         case b:
13220         case c:
13221             do_something_else();
13222             break;
13223         }
13224     }
13226 Did you forget case `d` or deliberately leave it out?
13227 Forgetting a case typically happens when a case is added to an enumeration and the person doing so fails to add it to every
13228 switch over the enumerators.
13230 ##### Enforcement
13232 Flag `switch`-statements over an enumeration that don't handle all enumerators and do not have a `default`.
13233 This might yield too many false positives in some code bases; if so, flag only `switch`es that handle most but not all cases
13234 (that was the strategy of the very first C++ compiler).
13236 ### <a name="Res-noname"></a>ES.84: Don't try to declare a local variable with no name
13238 ##### Reason
13240 There is no such thing.
13241 What looks to a human like a variable without a name is to the compiler a statement consisting of a temporary that immediately goes out of scope.
13243 ##### Example, bad
13245     void f()
13246     {
13247         lock_guard<mutex>{mx};   // Bad
13248         // ...
13249     }
13251 This declares an unnamed `lock_guard` object that immediately goes out of scope at the point of the semicolon.
13252 This is not an uncommon mistake.
13253 In particular, this particular example can lead to hard-to find race conditions.
13255 ##### Note
13257 Unnamed function arguments are fine.
13259 ##### Enforcement
13261 Flag statements that are just a temporary.
13263 ### <a name="Res-empty"></a>ES.85: Make empty statements visible
13265 ##### Reason
13267 Readability.
13269 ##### Example
13271     for (i = 0; i < max; ++i);   // BAD: the empty statement is easily overlooked
13272     v[i] = f(v[i]);
13274     for (auto x : v) {           // better
13275         // nothing
13276     }
13277     v[i] = f(v[i]);
13279 ##### Enforcement
13281 Flag empty statements that are not blocks and don't contain comments.
13283 ### <a name="Res-loop-counter"></a>ES.86: Avoid modifying loop control variables inside the body of raw for-loops
13285 ##### Reason
13287 The loop control up front should enable correct reasoning about what is happening inside the loop. Modifying loop counters in both the iteration-expression and inside the body of the loop is a perennial source of surprises and bugs.
13289 ##### Example
13291     for (int i = 0; i < 10; ++i) {
13292         // no updates to i -- ok
13293     }
13295     for (int i = 0; i < 10; ++i) {
13296         //
13297         if (/* something */) ++i; // BAD
13298         //
13299     }
13301     bool skip = false;
13302     for (int i = 0; i < 10; ++i) {
13303         if (skip) { skip = false; continue; }
13304         //
13305         if (/* something */) skip = true;  // Better: using two variables for two concepts.
13306         //
13307     }
13309 ##### Enforcement
13311 Flag variables that are potentially updated (have a non-`const` use) in both the loop control iteration-expression and the loop body.
13314 ### <a name="Res-if"></a>ES.87: Don't add redundant `==` or `!=` to conditions
13316 ##### Reason
13318 Doing so avoids verbosity and eliminates some opportunities for mistakes.
13319 Helps make style consistent and conventional.
13321 ##### Example
13323 By definition, a condition in an `if`-statement, `while`-statement, or a `for`-statement selects between `true` and `false`.
13324 A numeric value is compared to `0` and a pointer value to `nullptr`.
13326     // These all mean "if p is not nullptr"
13327     if (p) { ... }            // good
13328     if (p != 0) { ... }       // redundant !=0, bad: don't use 0 for pointers
13329     if (p != nullptr) { ... } // redundant !=nullptr, not recommended
13331 Often, `if (p)` is read as "if `p` is valid" which is a direct expression of the programmers intent,
13332 whereas `if (p != nullptr)` would be a long-winded workaround.
13334 ##### Example
13336 This rule is especially useful when a declaration is used as a condition
13338     if (auto pc = dynamic_cast<Circle*>(ps)) { ... } // execute if ps points to a kind of Circle, good
13340     if (auto pc = dynamic_cast<Circle*>(ps); pc != nullptr) { ... } // not recommended
13342 ##### Example
13344 Note that implicit conversions to bool are applied in conditions.
13345 For example:
13347     for (string s; cin >> s; ) v.push_back(s);
13349 This invokes `istream`'s `operator bool()`.
13351 ##### Note
13353 Explicit comparison of an integer to `0` is in general not redundant.
13354 The reason is that (as opposed to pointers and Booleans) an integer often has more than two reasonable values.
13355 Furthermore `0` (zero) is often used to indicate success.
13356 Consequently, it is best to be specific about the comparison.
13358     void f(int i)
13359     {
13360         if (i)            // suspect
13361         // ...
13362         if (i == success) // possibly better
13363         // ...
13364     }
13366 Always remember that an integer can have more than two values.
13368 ##### Example, bad
13370 It has been noted that
13372     if(strcmp(p1, p2)) { ... }   // are the two C-style strings equal? (mistake!)
13374 is a common beginners error.
13375 If you use C-style strings, you must know the `<cstring>` functions well.
13376 Being verbose and writing
13378     if(strcmp(p1, p2) != 0) { ... }   // are the two C-style strings equal? (mistake!)
13380 would not in itself save you.
13382 ##### Note
13384 The opposite condition is most easily expressed using a negation:
13386     // These all mean "if p is nullptr"
13387     if (!p) { ... }           // good
13388     if (p == 0) { ... }       // redundant == 0, bad: don't use 0 for pointers
13389     if (p == nullptr) { ... } // redundant == nullptr, not recommended
13391 ##### Enforcement
13393 Easy, just check for redundant use of `!=` and `==` in conditions.
13397 ## <a name="SS-numbers"></a>Arithmetic
13399 ### <a name="Res-mix"></a>ES.100: Don't mix signed and unsigned arithmetic
13401 ##### Reason
13403 Avoid wrong results.
13405 ##### Example
13407     int x = -3;
13408     unsigned int y = 7;
13410     cout << x - y << '\n';  // unsigned result, possibly 4294967286
13411     cout << x + y << '\n';  // unsigned result: 4
13412     cout << x * y << '\n';  // unsigned result, possibly 4294967275
13414 It is harder to spot the problem in more realistic examples.
13416 ##### Note
13418 Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts.
13419 This precludes consistency. Use `gsl::index` for subscripts; [see ES.107](#Res-subscripts).
13421 ##### Enforcement
13423 * Compilers already know and sometimes warn.
13424 * (To avoid noise) Do not flag on a mixed signed/unsigned comparison where one of the arguments is `sizeof` or a call to container `.size()` and the other is `ptrdiff_t`.
13427 ### <a name="Res-unsigned"></a>ES.101: Use unsigned types for bit manipulation
13429 ##### Reason
13431 Unsigned types support bit manipulation without surprises from sign bits.
13433 ##### Example
13435     unsigned char x = 0b1010'1010;
13436     unsigned char y = ~x;   // y == 0b0101'0101;
13438 ##### Note
13440 Unsigned types can also be useful for modular arithmetic.
13441 However, if you want modular arithmetic add
13442 comments as necessary noting the reliance on wraparound behavior, as such code
13443 can be surprising for many programmers.
13445 ##### Enforcement
13447 * Just about impossible in general because of the use of unsigned subscripts in the standard library
13448 * ???
13450 ### <a name="Res-signed"></a>ES.102: Use signed types for arithmetic
13452 ##### Reason
13454 Because most arithmetic is assumed to be signed;
13455 `x - y` yields a negative number when `y > x` except in the rare cases where you really want modular arithmetic.
13457 ##### Example
13459 Unsigned arithmetic can yield surprising results if you are not expecting it.
13460 This is even more true for mixed signed and unsigned arithmetic.
13462     template<typename T, typename T2>
13463     T subtract(T x, T2 y)
13464     {
13465         return x - y;
13466     }
13468     void test()
13469     {
13470         int s = 5;
13471         unsigned int us = 5;
13472         cout << subtract(s, 7) << '\n';       // -2
13473         cout << subtract(us, 7u) << '\n';     // 4294967294
13474         cout << subtract(s, 7u) << '\n';      // -2
13475         cout << subtract(us, 7) << '\n';      // 4294967294
13476         cout << subtract(s, us + 2) << '\n';  // -2
13477         cout << subtract(us, s + 2) << '\n';  // 4294967294
13478     }
13480 Here we have been very explicit about what's happening,
13481 but if you had seen `us - (s + 2)` or `s += 2; ...; us - s`, would you reliably have suspected that the result would print as `4294967294`?
13483 ##### Exception
13485 Use unsigned types if you really want modular arithmetic - add
13486 comments as necessary noting the reliance on overflow behavior, as such code
13487 is going to be surprising for many programmers.
13489 ##### Example
13491 The standard library uses unsigned types for subscripts.
13492 The built-in array uses signed types for subscripts.
13493 This makes surprises (and bugs) inevitable.
13495     int a[10];
13496     for (int i = 0; i < 10; ++i) a[i] = i;
13497     vector<int> v(10);
13498     // compares signed to unsigned; some compilers warn, but we should not
13499     for (gsl::index i = 0; i < v.size(); ++i) v[i] = i;
13501     int a2[-2];         // error: negative size
13503     // OK, but the number of ints (4294967294) is so large that we should get an exception
13504     vector<int> v2(-2);
13506  Use `gsl::index` for subscripts; [see ES.107](#Res-subscripts).
13508 ##### Enforcement
13510 * Flag mixed signed and unsigned arithmetic
13511 * Flag results of unsigned arithmetic assigned to or printed as signed.
13512 * Flag negative literals (e.g. `-2`) used as container subscripts.
13513 * (To avoid noise) Do not flag on a mixed signed/unsigned comparison where one of the arguments is `sizeof` or a call to container `.size()` and the other is `ptrdiff_t`.
13516 ### <a name="Res-overflow"></a>ES.103: Don't overflow
13518 ##### Reason
13520 Overflow usually makes your numeric algorithm meaningless.
13521 Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.
13523 ##### Example, bad
13525     int a[10];
13526     a[10] = 7;   // bad, array bounds overflow
13528     for (int n = 0; n <= 10; ++n)
13529         a[n] = 9;   // bad, array bounds overflow
13531 ##### Example, bad
13533     int n = numeric_limits<int>::max();
13534     int m = n + 1;   // bad, numeric overflow
13536 ##### Example, bad
13538     int area(int h, int w) { return h * w; }
13540     auto a = area(10'000'000, 100'000'000);   // bad, numeric overflow
13542 ##### Exception
13544 Use unsigned types if you really want modular arithmetic.
13546 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
13548 ##### Enforcement
13552 ### <a name="Res-underflow"></a>ES.104: Don't underflow
13554 ##### Reason
13556 Decrementing a value beyond a minimum value can lead to memory corruption and undefined behavior.
13558 ##### Example, bad
13560     int a[10];
13561     a[-2] = 7;   // bad
13563     int n = 101;
13564     while (n--)
13565         a[n - 1] = 9;   // bad (twice)
13567 ##### Exception
13569 Use unsigned types if you really want modular arithmetic.
13571 ##### Enforcement
13575 ### <a name="Res-zero"></a>ES.105: Don't divide by integer zero
13577 ##### Reason
13579 The result is undefined and probably a crash.
13581 ##### Note
13583 This also applies to `%`.
13585 ##### Example, bad
13587     int divide(int a, int b)
13588     {
13589         // BAD, should be checked (e.g., in a precondition)
13590         return a / b;
13591     }
13593 ##### Example, good
13595     int divide(int a, int b)
13596     {
13597         // good, address via precondition (and replace with contracts once C++ gets them)
13598         Expects(b != 0);
13599         return a / b;
13600     }
13602     double divide(double a, double b)
13603     {
13604         // good, address via using double instead
13605         return a / b;
13606     }
13608 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
13610 ##### Enforcement
13612 * Flag division by an integral value that could be zero
13615 ### <a name="Res-nonnegative"></a>ES.106: Don't try to avoid negative values by using `unsigned`
13617 ##### Reason
13619 Choosing `unsigned` implies many changes to the usual behavior of integers, including modular arithmetic,
13620 can suppress warnings related to overflow,
13621 and opens the door for errors related to signed/unsigned mixes.
13622 Using `unsigned` doesn't actually eliminate the possibility of negative values.
13624 ##### Example
13626     unsigned int u1 = -2;   // Valid: the value of u1 is 4294967294
13627     int i1 = -2;
13628     unsigned int u2 = i1;   // Valid: the value of u2 is 4294967294
13629     int i2 = u2;            // Valid: the value of i2 is -2
13631 These problems with such (perfectly legal) constructs are hard to spot in real code and are the source of many real-world errors.
13632 Consider:
13634     unsigned area(unsigned height, unsigned width) { return height*width; } // [see also](#Ri-expects)
13635     // ...
13636     int height;
13637     cin >> height;
13638     auto a = area(height, 2);   // if the input is -2 a becomes 4294967292
13640 Remember that `-1` when assigned to an `unsigned int` becomes the largest `unsigned int`.
13641 Also, since unsigned arithmetic is modular arithmetic the multiplication didn't overflow, it wrapped around.
13643 ##### Example
13645     unsigned max = 100000;    // "accidental typo", I mean to say 10'000
13646     unsigned short x = 100;
13647     while (x < max) x += 100; // infinite loop
13649 Had `x` been a signed `short`, we could have warned about the undefined behavior upon overflow.
13651 ##### Alternatives
13653 * use signed integers and check for `x >= 0`
13654 * use a positive integer type
13655 * use an integer subrange type
13656 * `Assert(-1 < x)`
13658 For example
13660     struct Positive {
13661         int val;
13662         Positive(int x) :val{x} { Assert(0 < x); }
13663         operator int() { return val; }
13664     };
13666     int f(Positive arg) { return arg; }
13668     int r1 = f(2);
13669     int r2 = f(-2);  // throws
13671 ##### Note
13675 ##### Enforcement
13677 See ES.100 Enforcements.
13680 ### <a name="Res-subscripts"></a>ES.107: Don't use `unsigned` for subscripts, prefer `gsl::index`
13682 ##### Reason
13684 To avoid signed/unsigned confusion.
13685 To enable better optimization.
13686 To enable better error detection.
13687 To avoid the pitfalls with `auto` and `int`.
13689 ##### Example, bad
13691     vector<int> vec = /*...*/;
13693     for (int i = 0; i < vec.size(); i += 2)                    // might not be big enough
13694         cout << vec[i] << '\n';
13695     for (unsigned i = 0; i < vec.size(); i += 2)               // risk wraparound
13696         cout << vec[i] << '\n';
13697     for (auto i = 0; i < vec.size(); i += 2)                   // might not be big enough
13698         cout << vec[i] << '\n';
13699     for (vector<int>::size_type i = 0; i < vec.size(); i += 2) // verbose
13700         cout << vec[i] << '\n';
13701     for (auto i = vec.size()-1; i >= 0; i -= 2)                // bug
13702         cout << vec[i] << '\n';
13703     for (int i = vec.size()-1; i >= 0; i -= 2)                 // might not be big enough
13704         cout << vec[i] << '\n';
13706 ##### Example, good
13708     vector<int> vec = /*...*/;
13710     for (gsl::index i = 0; i < vec.size(); i += 2)             // ok
13711         cout << vec[i] << '\n';
13712     for (gsl::index i = vec.size()-1; i >= 0; i -= 2)          // ok
13713         cout << vec[i] << '\n';
13715 ##### Note
13717 The built-in array allows signed subscripts.
13718 The standard-library containers use unsigned subscripts.
13719 Thus, no perfect and fully compatible solution is possible (unless and until the standard-library containers change to use signed subscripts someday in the future).
13720 Given the known problems with unsigned and signed/unsigned mixtures, better stick to (signed) integers of a sufficient size, which is guaranteed by `gsl::index`.
13722 ##### Example
13724     template<typename T>
13725     struct My_container {
13726     public:
13727         // ...
13728         T& operator[](gsl::index i);    // not unsigned
13729         // ...
13730     };
13732 ##### Example
13734     ??? demonstrate improved code generation and potential for error detection ???
13736 ##### Alternatives
13738 Alternatives for users
13740 * use algorithms
13741 * use range-for
13742 * use iterators/pointers
13744 ##### Enforcement
13746 * Very tricky as long as the standard-library containers get it wrong.
13747 * (To avoid noise) Do not flag on a mixed signed/unsigned comparison where one of the arguments is `sizeof` or a call to container `.size()` and the other is `ptrdiff_t`.
13752 # <a name="S-performance"></a>Per: Performance
13754 ??? should this section be in the main guide???
13756 This section contains rules for people who need high performance or low-latency.
13757 That is, these are rules that relate to how to use as little time and as few resources as possible to achieve a task in a predictably short time.
13758 The rules in this section are more restrictive and intrusive than what is needed for many (most) applications.
13759 Do not naïvely try to follow them in general code: achieving the goals of low latency requires extra work.
13761 Performance rule summary:
13763 * [Per.1: Don't optimize without reason](#Rper-reason)
13764 * [Per.2: Don't optimize prematurely](#Rper-Knuth)
13765 * [Per.3: Don't optimize something that's not performance critical](#Rper-critical)
13766 * [Per.4: Don't assume that complicated code is necessarily faster than simple code](#Rper-simple)
13767 * [Per.5: Don't assume that low-level code is necessarily faster than high-level code](#Rper-low)
13768 * [Per.6: Don't make claims about performance without measurements](#Rper-measure)
13769 * [Per.7: Design to enable optimization](#Rper-efficiency)
13770 * [Per.10: Rely on the static type system](#Rper-type)
13771 * [Per.11: Move computation from run time to compile time](#Rper-Comp)
13772 * [Per.12: Eliminate redundant aliases](#Rper-alias)
13773 * [Per.13: Eliminate redundant indirections](#Rper-indirect)
13774 * [Per.14: Minimize the number of allocations and deallocations](#Rper-alloc)
13775 * [Per.15: Do not allocate on a critical branch](#Rper-alloc0)
13776 * [Per.16: Use compact data structures](#Rper-compact)
13777 * [Per.17: Declare the most used member of a time-critical struct first](#Rper-struct)
13778 * [Per.18: Space is time](#Rper-space)
13779 * [Per.19: Access memory predictably](#Rper-access)
13780 * [Per.30: Avoid context switches on the critical path](#Rper-context)
13782 ### <a name="Rper-reason"></a>Per.1: Don't optimize without reason
13784 ##### Reason
13786 If there is no need for optimization, the main result of the effort will be more errors and higher maintenance costs.
13788 ##### Note
13790 Some people optimize out of habit or because it's fun.
13794 ### <a name="Rper-Knuth"></a>Per.2: Don't optimize prematurely
13796 ##### Reason
13798 Elaborately optimized code is usually larger and harder to change than unoptimized code.
13802 ### <a name="Rper-critical"></a>Per.3: Don't optimize something that's not performance critical
13804 ##### Reason
13806 Optimizing a non-performance-critical part of a program has no effect on system performance.
13808 ##### Note
13810 If your program spends most of its time waiting for the web or for a human, optimization of in-memory computation is probably useless.
13812 Put another way: If your program spends 4% of its processing time doing
13813 computation A and 40% of its time doing computation B, a 50% improvement on A is
13814 only as impactful as a 5% improvement on B. (If you don't even know how much
13815 time is spent on A or B, see <a href="#Rper-reason">Per.1</a> and <a
13816 href="#Rper-Knuth">Per.2</a>.)
13818 ### <a name="Rper-simple"></a>Per.4: Don't assume that complicated code is necessarily faster than simple code
13820 ##### Reason
13822 Simple code can be very fast. Optimizers sometimes do marvels with simple code
13824 ##### Example, good
13826     // clear expression of intent, fast execution
13828     vector<uint8_t> v(100000);
13830     for (auto& c : v)
13831         c = ~c;
13833 ##### Example, bad
13835     // intended to be faster, but is often slower
13837     vector<uint8_t> v(100000);
13839     for (size_t i = 0; i < v.size(); i += sizeof(uint64_t)) {
13840         uint64_t& quad_word = *reinterpret_cast<uint64_t*>(&v[i]);
13841         quad_word = ~quad_word;
13842     }
13844 ##### Note
13850 ### <a name="Rper-low"></a>Per.5: Don't assume that low-level code is necessarily faster than high-level code
13852 ##### Reason
13854 Low-level code sometimes inhibits optimizations. Optimizers sometimes do marvels with high-level code.
13856 ##### Note
13862 ### <a name="Rper-measure"></a>Per.6: Don't make claims about performance without measurements
13864 ##### Reason
13866 The field of performance is littered with myth and bogus folklore.
13867 Modern hardware and optimizers defy naive assumptions; even experts are regularly surprised.
13869 ##### Note
13871 Getting good performance measurements can be hard and require specialized tools.
13873 ##### Note
13875 A few simple microbenchmarks using Unix `time` or the standard-library `<chrono>` can help dispel the most obvious myths.
13876 If you can't measure your complete system accurately, at least try to measure a few of your key operations and algorithms.
13877 A profiler can help tell you which parts of your system are performance critical.
13878 Often, you will be surprised.
13882 ### <a name="Rper-efficiency"></a>Per.7: Design to enable optimization
13884 ##### Reason
13886 Because we often need to optimize the initial design.
13887 Because a design that ignores the possibility of later improvement is hard to change.
13889 ##### Example
13891 From the C (and C++) standard:
13893     void qsort (void* base, size_t num, size_t size, int (*compar)(const void*, const void*));
13895 When did you even want to sort memory?
13896 Really, we sort sequences of elements, typically stored in containers.
13897 A call to `qsort` throws away much useful information (e.g., the element type), forces the user to repeat information
13898 already known (e.g., the element size), and forces the user to write extra code (e.g., a function to compare `double`s).
13899 This implies added work for the programmer, is error-prone, and deprives the compiler of information needed for optimization.
13901     double data[100];
13902     // ... fill a ...
13904     // 100 chunks of memory of sizeof(double) starting at
13905     // address data using the order defined by compare_doubles
13906     qsort(data, 100, sizeof(double), compare_doubles);
13908 From the point of view of interface design, `qsort` throws away useful information.
13910 We can do better (in C++98)
13912     template<typename Iter>
13913         void sort(Iter b, Iter e);  // sort [b:e)
13915     sort(data, data + 100);
13917 Here, we use the compiler's knowledge about the size of the array, the type of elements, and how to compare `double`s.
13919 With C++20, we can do better still
13921     // sortable specifies that c must be a
13922     // random-access sequence of elements comparable with <
13923     void sort(sortable auto& c);
13925     sort(c);
13927 The key is to pass sufficient information for a good implementation to be chosen.
13928 In this, the `sort` interfaces shown here still have a weakness:
13929 They implicitly rely on the element type having less-than (`<`) defined.
13930 To complete the interface, we need a second version that accepts a comparison criterion:
13932     // compare elements of c using r
13933     template<random_access_range R, class C> requires sortable<R, C>
13934     void sort(R&& r, C c);
13936 The standard-library specification of `sort` offers those two versions, and more.
13938 ##### Note
13940 Premature optimization is said to be [the root of all evil](#Rper-Knuth), but that's not a reason to despise performance.
13941 It is never premature to consider what makes a design amenable to improvement, and improved performance is a commonly desired improvement.
13942 Aim to build a set of habits that by default results in efficient, maintainable, and optimizable code.
13943 In particular, when you write a function that is not a one-off implementation detail, consider
13945 * Information passing:
13946 Prefer clean [interfaces](#S-interfaces) carrying sufficient information for later improvement of implementation.
13947 Note that information flows into and out of an implementation through the interfaces we provide.
13948 * Compact data: By default, [use compact data](#Rper-compact), such as `std::vector` and [access it in a systematic fashion](#Rper-access).
13949 If you think you need a linked structure, try to craft the interface so that this structure isn't seen by users.
13950 * Function argument passing and return:
13951 Distinguish between mutable and non-mutable data.
13952 Don't impose a resource management burden on your users.
13953 Don't impose spurious run-time indirections on your users.
13954 Use [conventional ways](#Rf-conventional) of passing information through an interface;
13955 unconventional and/or "optimized" ways of passing data can seriously complicate later reimplementation.
13956 * Abstraction:
13957 Don't overgeneralize; a design that tries to cater for every possible use (and misuse) and defers every design decision for later
13958 (using compile-time or run-time indirections) is usually a complicated, bloated, hard-to-understand mess.
13959 Generalize from concrete examples, preserving performance as we generalize.
13960 Do not generalize based on mere speculation about future needs.
13961 The ideal is zero-overhead generalization.
13962 * Libraries:
13963 Use libraries with good interfaces.
13964 If no library is available build one yourself and imitate the interface style from a good library.
13965 The [standard library](#sl-the-standard-library) is a good first place to look for inspiration.
13966 * Isolation:
13967 Isolate your code from messy and/or old-style code by providing an interface of your choosing to it.
13968 This is sometimes called "providing a wrapper" for the useful/necessary but messy code.
13969 Don't let bad designs "bleed into" your code.
13971 ##### Example
13973 Consider:
13975     template<class ForwardIterator, class T>
13976     bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
13978 `binary_search(begin(c), end(c), 7)` will tell you whether `7` is in `c` or not.
13979 However, it will not tell you where that `7` is or whether there are more than one `7`.
13981 Sometimes, just passing the minimal amount of information back (here, `true` or `false`) is sufficient, but a good interface passes
13982 needed information back to the caller. Therefore, the standard library also offers
13984     template<class ForwardIterator, class T>
13985     ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val);
13987 `lower_bound` returns an iterator to the first match if any, otherwise to the first element greater than `val`, or `last` if no such element is found.
13989 However, `lower_bound` still doesn't return enough information for all uses, so the standard library also offers
13991     template<class ForwardIterator, class T>
13992     pair<ForwardIterator, ForwardIterator>
13993     equal_range(ForwardIterator first, ForwardIterator last, const T& val);
13995 `equal_range` returns a `pair` of iterators specifying the first and one beyond last match.
13997     auto r = equal_range(begin(c), end(c), 7);
13998     for (auto p = r.first; p != r.second; ++p)
13999         cout << *p << '\n';
14001 Obviously, these three interfaces are implemented by the same basic code.
14002 They are simply three ways of presenting the basic binary search algorithm to users,
14003 ranging from the simplest ("make simple things simple!")
14004 to returning complete, but not always needed, information ("don't hide useful information").
14005 Naturally, crafting such a set of interfaces requires experience and domain knowledge.
14007 ##### Note
14009 Do not simply craft the interface to match the first implementation and the first use case you think of.
14010 Once your first initial implementation is complete, review it; once you deploy it, mistakes will be hard to remedy.
14012 ##### Note
14014 A need for efficiency does not imply a need for [low-level code](#Rper-low).
14015 High-level code isn't necessarily slow or bloated.
14017 ##### Note
14019 Things have costs.
14020 Don't be paranoid about costs (modern computers really are very fast),
14021 but have a rough idea of the order of magnitude of cost of what you use.
14022 For example, have a rough idea of the cost of
14023 a memory access,
14024 a function call,
14025 a string comparison,
14026 a system call,
14027 a disk access,
14028 and a message through a network.
14030 ##### Note
14032 If you can only think of one implementation, you probably don't have something for which you can devise a stable interface.
14033 Maybe, it is just an implementation detail - not every piece of code needs a stable interface - but pause and consider.
14034 One question that can be useful is
14035 "what interface would be needed if this operation should be implemented using multiple threads? be vectorized?"
14037 ##### Note
14039 This rule does not contradict the [Don't optimize prematurely](#Rper-Knuth) rule.
14040 It complements it, encouraging developers to enable later - appropriate and non-premature - optimization, if and where needed.
14042 ##### Enforcement
14044 Tricky.
14045 Maybe looking for `void*` function arguments will find examples of interfaces that hinder later optimization.
14047 ### <a name="Rper-type"></a>Per.10: Rely on the static type system
14049 ##### Reason
14051 Type violations, weak types (e.g. `void*`s), and low-level code (e.g., manipulation of sequences as individual bytes) make the job of the optimizer much harder. Simple code often optimizes better than hand-crafted complex code.
14055 ### <a name="Rper-Comp"></a>Per.11: Move computation from run time to compile time
14057 ##### Reason
14059 To decrease code size and run time.
14060 To avoid data races by using constants.
14061 To catch errors at compile time (and thus eliminate the need for error-handling code).
14063 ##### Example
14065     double square(double d) { return d*d; }
14066     static double s2 = square(2);    // old-style: dynamic initialization
14068     constexpr double ntimes(double d, int n)   // assume 0 <= n
14069     {
14070             double m = 1;
14071             while (n--) m *= d;
14072             return m;
14073     }
14074     constexpr double s3 {ntimes(2, 3)};  // modern-style: compile-time initialization
14076 Code like the initialization of `s2` isn't uncommon, especially for initialization that's a bit more complicated than `square()`.
14077 However, compared to the initialization of `s3` there are two problems:
14079 * we suffer the overhead of a function call at run time
14080 * `s2` just might be accessed by another thread before the initialization happens.
14082 Note: you can't have a data race on a constant.
14084 ##### Example
14086 Consider a popular technique for providing a handle for storing small objects in the handle itself and larger ones on the heap.
14088     constexpr int on_stack_max = 20;
14090     template<typename T>
14091     struct Scoped {     // store a T in Scoped
14092             // ...
14093         T obj;
14094     };
14096     template<typename T>
14097     struct On_heap {    // store a T on the free store
14098             // ...
14099             T* objp;
14100     };
14102     template<typename T>
14103     using Handle = typename std::conditional<(sizeof(T) <= on_stack_max),
14104                         Scoped<T>,      // first alternative
14105                         On_heap<T>      // second alternative
14106                    >::type;
14108     void f()
14109     {
14110         Handle<double> v1;                   // the double goes on the stack
14111         Handle<std::array<double, 200>> v2;  // the array goes on the free store
14112         // ...
14113     }
14115 Assume that `Scoped` and `On_heap` provide compatible user interfaces.
14116 Here we compute the optimal type to use at compile time.
14117 There are similar techniques for selecting the optimal function to call.
14119 ##### Note
14121 The ideal is *not* to try to execute everything at compile time.
14122 Obviously, most computations depend on inputs, so they can't be moved to compile time,
14123 but beyond that logical constraint is the fact that complex compile-time computation can seriously increase compile times
14124 and complicate debugging.
14125 It is even possible to slow down code by compile-time computation.
14126 This is admittedly rare, but by factoring out a general computation into separate optimal sub-calculations, it is possible to render the instruction cache less effective.
14128 ##### Enforcement
14130 * Look for simple functions that might be constexpr (but are not).
14131 * Look for functions called with all constant-expression arguments.
14132 * Look for macros that could be constexpr.
14134 ### <a name="Rper-alias"></a>Per.12: Eliminate redundant aliases
14138 ### <a name="Rper-indirect"></a>Per.13: Eliminate redundant indirections
14142 ### <a name="Rper-alloc"></a>Per.14: Minimize the number of allocations and deallocations
14146 ### <a name="Rper-alloc0"></a>Per.15: Do not allocate on a critical branch
14150 ### <a name="Rper-compact"></a>Per.16: Use compact data structures
14152 ##### Reason
14154 Performance is typically dominated by memory access times.
14158 ### <a name="Rper-struct"></a>Per.17: Declare the most used member of a time-critical struct first
14162 ### <a name="Rper-space"></a>Per.18: Space is time
14164 ##### Reason
14166 Performance is typically dominated by memory access times.
14170 ### <a name="Rper-access"></a>Per.19: Access memory predictably
14172 ##### Reason
14174 Performance is very sensitive to cache performance, and cache algorithms favor simple (usually linear) access to adjacent data.
14176 ##### Example
14178     int matrix[rows][cols];
14180     // bad
14181     for (int c = 0; c < cols; ++c)
14182         for (int r = 0; r < rows; ++r)
14183             sum += matrix[r][c];
14185     // good
14186     for (int r = 0; r < rows; ++r)
14187         for (int c = 0; c < cols; ++c)
14188             sum += matrix[r][c];
14190 ### <a name="Rper-context"></a>Per.30: Avoid context switches on the critical path
14194 # <a name="S-concurrency"></a>CP: Concurrency and parallelism
14196 We often want our computers to do many tasks at the same time (or at least appear to do them at the same time).
14197 The reasons for doing so vary (e.g., waiting for many events using only a single processor, processing many data streams simultaneously, or utilizing many hardware facilities)
14198 and so do the basic facilities for expressing concurrency and parallelism.
14199 Here, we articulate principles and rules for using the ISO standard C++ facilities for expressing basic concurrency and parallelism.
14201 Threads are the machine-level foundation for concurrent and parallel programming.
14202 Threads allow running multiple sections of a program independently, while sharing
14203 the same memory. Concurrent programming is tricky,
14204 because protecting shared data between threads is easier said than done.
14205 Making existing single-threaded code execute concurrently can be
14206 as trivial as adding `std::async` or `std::thread` strategically, or it can
14207 necessitate a full rewrite, depending on whether the original code was written
14208 in a thread-friendly way.
14210 The concurrency/parallelism rules in this document are designed with three goals
14211 in mind:
14213 * To help in writing code that is amenable to being used in a threaded
14214   environment
14215 * To show clean, safe ways to use the threading primitives offered by the
14216   standard library
14217 * To offer guidance on what to do when concurrency and parallelism aren't giving
14218   the performance gains needed
14220 It is also important to note that concurrency in C++ is an unfinished
14221 story. C++11 introduced many core concurrency primitives, C++14 and C++17 improved on
14222 them, and there is much interest in making the writing of
14223 concurrent programs in C++ even easier. We expect some of the library-related
14224 guidance here to change significantly over time.
14226 This section needs a lot of work (obviously).
14227 Please note that we start with rules for relative non-experts.
14228 Real experts must wait a bit;
14229 contributions are welcome,
14230 but please think about the majority of programmers who are struggling to get their concurrent programs correct and performant.
14232 Concurrency and parallelism rule summary:
14234 * [CP.1: Assume that your code will run as part of a multi-threaded program](#Rconc-multi)
14235 * [CP.2: Avoid data races](#Rconc-races)
14236 * [CP.3: Minimize explicit sharing of writable data](#Rconc-data)
14237 * [CP.4: Think in terms of tasks, rather than threads](#Rconc-task)
14238 * [CP.8: Don't try to use `volatile` for synchronization](#Rconc-volatile)
14239 * [CP.9: Whenever feasible use tools to validate your concurrent code](#Rconc-tools)
14241 **See also**:
14243 * [CP.con: Concurrency](#SScp-con)
14244 * [CP.coro: Coroutines](#SScp-coro)
14245 * [CP.par: Parallelism](#SScp-par)
14246 * [CP.mess: Message passing](#SScp-mess)
14247 * [CP.vec: Vectorization](#SScp-vec)
14248 * [CP.free: Lock-free programming](#SScp-free)
14249 * [CP.etc: Etc. concurrency rules](#SScp-etc)
14251 ### <a name="Rconc-multi"></a>CP.1: Assume that your code will run as part of a multi-threaded program
14253 ##### Reason
14255 It's hard to be certain that concurrency isn't used now or won't be used sometime in the future.
14256 Code gets reused.
14257 Libraries not using threads might be used from some other part of a program that does use threads.
14258 Note that this rule applies most urgently to library code and least urgently to stand-alone applications.
14259 However, over time, code fragments can turn up in unexpected places.
14261 ##### Example, bad
14263     double cached_computation(int x)
14264     {
14265         // bad: these statics cause data races in multi-threaded usage
14266         static int cached_x = 0.0;
14267         static double cached_result = COMPUTATION_OF_ZERO;
14269         if (cached_x != x) {
14270             cached_x = x;
14271             cached_result = computation(x);
14272         }
14273         return cached_result;
14274     }
14276 Although `cached_computation` works perfectly in a single-threaded environment, in a multi-threaded environment the two `static` variables result in data races and thus undefined behavior.
14278 ##### Example, good
14280     struct ComputationCache {
14281         int cached_x = 0;
14282         double cached_result = COMPUTATION_OF_ZERO;
14284         double compute(int x) {
14285             if (cached_x != x) {
14286                 cached_x = x;
14287                 cached_result = computation(x);
14288             }
14289             return cached_result;
14290         }
14291     };
14293 Here the cache is stored as member data of a `ComputationCache` object, rather than as shared static state.
14294 This refactoring essentially delegates the concern upward to the caller: a single-threaded program
14295 might still choose to have one global `ComputationCache`, while a multi-threaded program might
14296 have one `ComputationCache` instance per thread, or one per "context" for any definition of "context."
14297 The refactored function no longer attempts to manage the allocation of `cached_x`. In that sense,
14298 this is an application of the Single Responsibility Principle.
14300 In this specific example, refactoring for thread-safety also improved reusability in single-threaded
14301 programs. It's not hard to imagine that a single-threaded program might want two `ComputationCache` instances
14302 for use in different parts of the program, without having them overwrite each other's cached data.
14304 There are several other ways one might add thread-safety to code written for a standard multi-threaded environment
14305 (that is, one where the only form of concurrency is `std::thread`):
14307 * Mark the state variables as `thread_local` instead of `static`.
14308 * Implement concurrency control, for example, protecting access to the two `static` variables with a `static std::mutex`.
14309 * Refuse to build and/or run in a multi-threaded environment.
14310 * Provide two implementations: one for single-threaded environments and another for multi-threaded environments.
14312 ##### Exception
14314 Code that is never run in a multi-threaded environment.
14316 Be careful: there are many examples where code that was "known" to never run in a multi-threaded program
14317 was run as part of a multi-threaded program, often years later.
14318 Typically, such programs lead to a painful effort to remove data races.
14319 Therefore, code that is never intended to run in a multi-threaded environment should be clearly labeled as such and ideally come with compile or run-time enforcement mechanisms to catch those usage bugs early.
14321 ### <a name="Rconc-races"></a>CP.2: Avoid data races
14323 ##### Reason
14325 Unless you do, nothing is guaranteed to work and subtle errors will persist.
14327 ##### Note
14329 In a nutshell, if two threads can access the same object concurrently (without synchronization), and at least one is a writer (performing a non-`const` operation), you have a data race.
14330 For further information of how to use synchronization well to eliminate data races, please consult a good book about concurrency (See [Carefully study the literature](#Rconc-literature)).
14332 ##### Example, bad
14334 There are many examples of data races that exist, some of which are running in
14335 production software at this very moment. One very simple example:
14337     int get_id()
14338     {
14339       static int id = 1;
14340       return id++;
14341     }
14343 The increment here is an example of a data race. This can go wrong in many ways,
14344 including:
14346 * Thread A loads the value of `id`, the OS context switches A out for some
14347   period, during which other threads create hundreds of IDs. Thread A is then
14348   allowed to run again, and `id` is written back to that location as A's read of
14349   `id` plus one.
14350 * Thread A and B load `id` and increment it simultaneously.  They both get the
14351   same ID.
14353 Local static variables are a common source of data races.
14355 ##### Example, bad:
14357     void f(fstream& fs, regex pattern)
14358     {
14359         array<double, max> buf;
14360         int sz = read_vec(fs, buf, max);            // read from fs into buf
14361         gsl::span<double> s {buf};
14362         // ...
14363         auto h1 = async([&] { sort(std::execution::par, s); });     // spawn a task to sort
14364         // ...
14365         auto h2 = async([&] { return find_all(buf, sz, pattern); });   // spawn a task to find matches
14366         // ...
14367     }
14369 Here, we have a (nasty) data race on the elements of `buf` (`sort` will both read and write).
14370 All data races are nasty.
14371 Here, we managed to get a data race on data on the stack.
14372 Not all data races are as easy to spot as this one.
14374 ##### Example, bad:
14376     // code not controlled by a lock
14378     unsigned val;
14380     if (val < 5) {
14381         // ... other thread can change val here ...
14382         switch (val) {
14383         case 0: // ...
14384         case 1: // ...
14385         case 2: // ...
14386         case 3: // ...
14387         case 4: // ...
14388         }
14389     }
14391 Now, a compiler that does not know that `val` can change will  most likely implement that `switch` using a jump table with five entries.
14392 Then, a `val` outside the `[0..4]` range will cause a jump to an address that could be anywhere in the program, and execution would proceed there.
14393 Really, "all bets are off" if you get a data race.
14394 Actually, it can be worse still: by looking at the generated code you might be able to determine where the stray jump will go for a given value;
14395 this can be a security risk.
14397 ##### Enforcement
14399 Some is possible, do at least something.
14400 There are commercial and open-source tools that try to address this problem,
14401 but be aware that solutions have costs and blind spots.
14402 Static tools often have many false positives and run-time tools often have a significant cost.
14403 We hope for better tools.
14404 Using multiple tools can catch more problems than a single one.
14406 There are other ways you can mitigate the chance of data races:
14408 * Avoid global data
14409 * Avoid `static` variables
14410 * More use of concrete types on the stack (and don't pass pointers around too much)
14411 * More use of immutable data (literals, `constexpr`, and `const`)
14413 ### <a name="Rconc-data"></a>CP.3: Minimize explicit sharing of writable data
14415 ##### Reason
14417 If you don't share writable data, you can't have a data race.
14418 The less sharing you do, the less chance you have to forget to synchronize access (and get data races).
14419 The less sharing you do, the less chance you have to wait on a lock (so performance can improve).
14421 ##### Example
14423     bool validate(const vector<Reading>&);
14424     Graph<Temp_node> temperature_gradients(const vector<Reading>&);
14425     Image altitude_map(const vector<Reading>&);
14426     // ...
14428     void process_readings(const vector<Reading>& surface_readings)
14429     {
14430         auto h1 = async([&] { if (!validate(surface_readings)) throw Invalid_data{}; });
14431         auto h2 = async([&] { return temperature_gradients(surface_readings); });
14432         auto h3 = async([&] { return altitude_map(surface_readings); });
14433         // ...
14434         h1.get();
14435         auto v2 = h2.get();
14436         auto v3 = h3.get();
14437         // ...
14438     }
14440 Without those `const`s, we would have to review every asynchronously invoked function for potential data races on `surface_readings`.
14441 Making `surface_readings` be `const` (with respect to this function) allow reasoning using only the function body.
14443 ##### Note
14445 Immutable data can be safely and efficiently shared.
14446 No locking is needed: You can't have a data race on a constant.
14447 See also [CP.mess: Message Passing](#SScp-mess) and [CP.31: prefer pass by value](#Rconc-data-by-value).
14449 ##### Enforcement
14454 ### <a name="Rconc-task"></a>CP.4: Think in terms of tasks, rather than threads
14456 ##### Reason
14458 A `thread` is an implementation concept, a way of thinking about the machine.
14459 A task is an application notion, something you'd like to do, preferably concurrently with other tasks.
14460 Application concepts are easier to reason about.
14462 ##### Example
14464     void some_fun(const std::string& msg)
14465     {
14466         std::thread publisher([=] { std::cout << msg; });      // bad: less expressive
14467                                                                //      and more error-prone
14468         auto pubtask = std::async([=] { std::cout << msg; });  // OK
14469         // ...
14470         publisher.join();
14471     }
14473 ##### Note
14475 With the exception of `async()`, the standard-library facilities are low-level, machine-oriented, threads-and-lock level.
14476 This is a necessary foundation, but we have to try to raise the level of abstraction: for productivity, for reliability, and for performance.
14477 This is a potent argument for using higher level, more applications-oriented libraries (if possible, built on top of standard-library facilities).
14479 ##### Enforcement
14483 ### <a name="Rconc-volatile"></a>CP.8: Don't try to use `volatile` for synchronization
14485 ##### Reason
14487 In C++, unlike some other languages, `volatile` does not provide atomicity, does not synchronize between threads,
14488 and does not prevent instruction reordering (neither compiler nor hardware).
14489 It simply has nothing to do with concurrency.
14491 ##### Example, bad:
14493     int free_slots = max_slots; // current source of memory for objects
14495     Pool* use()
14496     {
14497         if (int n = free_slots--) return &pool[n];
14498     }
14500 Here we have a problem:
14501 This is perfectly good code in a single-threaded program, but have two threads execute this and
14502 there is a race condition on `free_slots` so that two threads might get the same value and `free_slots`.
14503 That's (obviously) a bad data race, so people trained in other languages might try to fix it like this:
14505     volatile int free_slots = max_slots; // current source of memory for objects
14507     Pool* use()
14508     {
14509         if (int n = free_slots--) return &pool[n];
14510     }
14512 This has no effect on synchronization: The data race is still there!
14514 The C++ mechanism for this is `atomic` types:
14516     atomic<int> free_slots = max_slots; // current source of memory for objects
14518     Pool* use()
14519     {
14520         if (int n = free_slots--) return &pool[n];
14521     }
14523 Now the `--` operation is atomic,
14524 rather than a read-increment-write sequence where another thread might get in-between the individual operations.
14526 ##### Alternative
14528 Use `atomic` types where you might have used `volatile` in some other language.
14529 Use a `mutex` for more complicated examples.
14531 ##### See also
14533 [(rare) proper uses of `volatile`](#Rconc-volatile2)
14535 ### <a name="Rconc-tools"></a>CP.9: Whenever feasible use tools to validate your concurrent code
14537 Experience shows that concurrent code is exceptionally hard to get right
14538 and that compile-time checking, run-time checks, and testing are less effective at finding concurrency errors
14539 than they are at finding errors in sequential code.
14540 Subtle concurrency errors can have dramatically bad effects, including memory corruption, deadlocks, and security vulnerabilities.
14542 ##### Example
14544     ???
14546 ##### Note
14548 Thread safety is challenging, often getting the better of experienced programmers: tooling is an important strategy to mitigate those risks.
14549 There are many tools "out there", both commercial and open-source tools, both research and production tools.
14550 Unfortunately people's needs and constraints differ so dramatically that we cannot make specific recommendations,
14551 but we can mention:
14553 * Static enforcement tools: both [clang](http://clang.llvm.org/docs/ThreadSafetyAnalysis.html)
14554 and some older versions of [GCC](https://gcc.gnu.org/wiki/ThreadSafetyAnnotation)
14555 have some support for static annotation of thread safety properties.
14556 Consistent use of this technique turns many classes of thread-safety errors into compile-time errors.
14557 The annotations are generally local (marking a particular member variable as guarded by a particular mutex),
14558 and are usually easy to learn. However, as with many static tools, it can often present false negatives;
14559 cases that should have been caught but were allowed.
14561 * dynamic enforcement tools: Clang's [Thread Sanitizer](http://clang.llvm.org/docs/ThreadSanitizer.html) (aka TSAN)
14562 is a powerful example of dynamic tools: it changes the build and execution of your program to add bookkeeping on memory access,
14563 absolutely identifying data races in a given execution of your binary.
14564 The cost for this is both memory (5-10x in most cases) and CPU slowdown (2-20x).
14565 Dynamic tools like this are best when applied to integration tests, canary pushes, or unit tests that operate on multiple threads.
14566 Workload matters: When TSAN identifies a problem, it is effectively always an actual data race,
14567 but it can only identify races seen in a given execution.
14569 ##### Enforcement
14571 It is up to an application builder to choose which support tools are valuable for a particular application.
14573 ## <a name="SScp-con"></a>CP.con: Concurrency
14575 This section focuses on relatively ad-hoc uses of multiple threads communicating through shared data.
14577 * For parallel algorithms, see [parallelism](#SScp-par)
14578 * For inter-task communication without explicit sharing, see [messaging](#SScp-mess)
14579 * For vector parallel code, see [vectorization](#SScp-vec)
14580 * For lock-free programming, see [lock free](#SScp-free)
14582 Concurrency rule summary:
14584 * [CP.20: Use RAII, never plain `lock()`/`unlock()`](#Rconc-raii)
14585 * [CP.21: Use `std::lock()` or `std::scoped_lock` to acquire multiple `mutex`es](#Rconc-lock)
14586 * [CP.22: Never call unknown code while holding a lock (e.g., a callback)](#Rconc-unknown)
14587 * [CP.23: Think of a joining `thread` as a scoped container](#Rconc-join)
14588 * [CP.24: Think of a `thread` as a global container](#Rconc-detach)
14589 * [CP.25: Prefer `gsl::joining_thread` over `std::thread`](#Rconc-joining_thread)
14590 * [CP.26: Don't `detach()` a thread](#Rconc-detached_thread)
14591 * [CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer](#Rconc-data-by-value)
14592 * [CP.32: To share ownership between unrelated `thread`s use `shared_ptr`](#Rconc-shared)
14593 * [CP.40: Minimize context switching](#Rconc-switch)
14594 * [CP.41: Minimize thread creation and destruction](#Rconc-create)
14595 * [CP.42: Don't `wait` without a condition](#Rconc-wait)
14596 * [CP.43: Minimize time spent in a critical section](#Rconc-time)
14597 * [CP.44: Remember to name your `lock_guard`s and `unique_lock`s](#Rconc-name)
14598 * [CP.50: Define a `mutex` together with the data it guards. Use `synchronized_value<T>` where possible](#Rconc-mutex)
14599 * ??? when to use a spinlock
14600 * ??? when to use `try_lock()`
14601 * ??? when to prefer `lock_guard` over `unique_lock`
14602 * ??? Time multiplexing
14603 * ??? when/how to use `new thread`
14605 ### <a name="Rconc-raii"></a>CP.20: Use RAII, never plain `lock()`/`unlock()`
14607 ##### Reason
14609 Avoids nasty errors from unreleased locks.
14611 ##### Example, bad
14613     mutex mtx;
14615     void do_stuff()
14616     {
14617         mtx.lock();
14618         // ... do stuff ...
14619         mtx.unlock();
14620     }
14622 Sooner or later, someone will forget the `mtx.unlock()`, place a `return` in the `... do stuff ...`, throw an exception, or something.
14624     mutex mtx;
14626     void do_stuff()
14627     {
14628         unique_lock<mutex> lck {mtx};
14629         // ... do stuff ...
14630     }
14632 ##### Enforcement
14634 Flag calls of member `lock()` and `unlock()`.  ???
14637 ### <a name="Rconc-lock"></a>CP.21: Use `std::lock()` or `std::scoped_lock` to acquire multiple `mutex`es
14639 ##### Reason
14641 To avoid deadlocks on multiple `mutex`es.
14643 ##### Example
14645 This is asking for deadlock:
14647     // thread 1
14648     lock_guard<mutex> lck1(m1);
14649     lock_guard<mutex> lck2(m2);
14651     // thread 2
14652     lock_guard<mutex> lck2(m2);
14653     lock_guard<mutex> lck1(m1);
14655 Instead, use `lock()`:
14657     // thread 1
14658     lock(m1, m2);
14659     lock_guard<mutex> lck1(m1, adopt_lock);
14660     lock_guard<mutex> lck2(m2, adopt_lock);
14662     // thread 2
14663     lock(m2, m1);
14664     lock_guard<mutex> lck2(m2, adopt_lock);
14665     lock_guard<mutex> lck1(m1, adopt_lock);
14667 or (better, but C++17 only):
14669     // thread 1
14670     scoped_lock<mutex, mutex> lck1(m1, m2);
14672     // thread 2
14673     scoped_lock<mutex, mutex> lck2(m2, m1);
14675 Here, the writers of `thread1` and `thread2` are still not agreeing on the order of the `mutex`es, but order no longer matters.
14677 ##### Note
14679 In real code, `mutex`es are rarely named to conveniently remind the programmer of an intended relation and intended order of acquisition.
14680 In real code, `mutex`es are not always conveniently acquired on consecutive lines.
14682 ##### Note
14684 In C++17 it's possible to write plain
14686     lock_guard lck1(m1, adopt_lock);
14688 and have the `mutex` type deduced.
14690 ##### Enforcement
14692 Detect the acquisition of multiple `mutex`es.
14693 This is undecidable in general, but catching common simple examples (like the one above) is easy.
14696 ### <a name="Rconc-unknown"></a>CP.22: Never call unknown code while holding a lock (e.g., a callback)
14698 ##### Reason
14700 If you don't know what a piece of code does, you are risking deadlock.
14702 ##### Example
14704     void do_this(Foo* p)
14705     {
14706         lock_guard<mutex> lck {my_mutex};
14707         // ... do something ...
14708         p->act(my_data);
14709         // ...
14710     }
14712 If you don't know what `Foo::act` does (maybe it is a virtual function invoking a derived class member of a class not yet written),
14713 it might call `do_this` (recursively) and cause a deadlock on `my_mutex`.
14714 Maybe it will lock on a different mutex and not return in a reasonable time, causing delays to any code calling `do_this`.
14716 ##### Example
14718 A common example of the "calling unknown code" problem is a call to a function that tries to gain locked access to the same object.
14719 Such problem can often be solved by using a `recursive_mutex`. For example:
14721     recursive_mutex my_mutex;
14723     template<typename Action>
14724     void do_something(Action f)
14725     {
14726         unique_lock<recursive_mutex> lck {my_mutex};
14727         // ... do something ...
14728         f(this);    // f will do something to *this
14729         // ...
14730     }
14732 If, as it is likely, `f()` invokes operations on `*this`, we must make sure that the object's invariant holds before the call.
14734 ##### Enforcement
14736 * Flag calling a virtual function with a non-recursive `mutex` held
14737 * Flag calling a callback with a non-recursive `mutex` held
14740 ### <a name="Rconc-join"></a>CP.23: Think of a joining `thread` as a scoped container
14742 ##### Reason
14744 To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a `thread`.
14745 If a `thread` joins, we can safely pass pointers to objects in the scope of the `thread` and its enclosing scopes.
14747 ##### Example
14749     void f(int* p)
14750     {
14751         // ...
14752         *p = 99;
14753         // ...
14754     }
14755     int glob = 33;
14757     void some_fct(int* p)
14758     {
14759         int x = 77;
14760         joining_thread t0(f, &x);           // OK
14761         joining_thread t1(f, p);            // OK
14762         joining_thread t2(f, &glob);        // OK
14763         auto q = make_unique<int>(99);
14764         joining_thread t3(f, q.get());      // OK
14765         // ...
14766     }
14768 A `gsl::joining_thread` is a `std::thread` with a destructor that joins and that cannot be `detached()`.
14769 By "OK" we mean that the object will be in scope ("live") for as long as a `thread` can use the pointer to it.
14770 The fact that `thread`s run concurrently doesn't affect the lifetime or ownership issues here;
14771 these `thread`s can be seen as just a function object called from `some_fct`.
14773 ##### Enforcement
14775 Ensure that `joining_thread`s don't `detach()`.
14776 After that, the usual lifetime and ownership (for local objects) enforcement applies.
14778 ### <a name="Rconc-detach"></a>CP.24: Think of a `thread` as a global container
14780 ##### Reason
14782 To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a `thread`.
14783 If a `thread` is detached, we can safely pass pointers to static and free store objects (only).
14785 ##### Example
14787     void f(int* p)
14788     {
14789         // ...
14790         *p = 99;
14791         // ...
14792     }
14794     int glob = 33;
14796     void some_fct(int* p)
14797     {
14798         int x = 77;
14799         std::thread t0(f, &x);           // bad
14800         std::thread t1(f, p);            // bad
14801         std::thread t2(f, &glob);        // OK
14802         auto q = make_unique<int>(99);
14803         std::thread t3(f, q.get());      // bad
14804         // ...
14805         t0.detach();
14806         t1.detach();
14807         t2.detach();
14808         t3.detach();
14809         // ...
14810     }
14812 By "OK" we mean that the object will be in scope ("live") for as long as a `thread` can use the pointers to it.
14813 By "bad" we mean that a `thread` might use a pointer after the pointed-to object is destroyed.
14814 The fact that `thread`s run concurrently doesn't affect the lifetime or ownership issues here;
14815 these `thread`s can be seen as just a function object called from `some_fct`.
14817 ##### Note
14819 Even objects with static storage duration can be problematic if used from detached threads: if the
14820 thread continues until the end of the program, it might be running concurrently with the destruction
14821 of objects with static storage duration, and thus accesses to such objects might race.
14823 ##### Note
14825 This rule is redundant if you [don't `detach()`](#Rconc-detached_thread) and [use `gsl::joining_thread`](#Rconc-joining_thread).
14826 However, converting code to follow those guidelines could be difficult and even impossible for third-party libraries.
14827 In such cases, the rule becomes essential for lifetime safety and type safety.
14830 In general, it is undecidable whether a `detach()` is executed for a `thread`, but simple common cases are easily detected.
14831 If we cannot prove that a `thread` does not `detach()`, we must assume that it does and that it outlives the scope in which it was constructed;
14832 After that, the usual lifetime and ownership (for global objects) enforcement applies.
14834 ##### Enforcement
14836 Flag attempts to pass local variables to a thread that might `detach()`.
14838 ### <a name="Rconc-joining_thread"></a>CP.25: Prefer `gsl::joining_thread` over `std::thread`
14840 ##### Reason
14842 A `joining_thread` is a thread that joins at the end of its scope.
14843 Detached threads are hard to monitor.
14844 It is harder to ensure absence of errors in detached threads (and potentially detached threads).
14846 ##### Example, bad
14848     void f() { std::cout << "Hello "; }
14850     struct F {
14851         void operator()() const { std::cout << "parallel world "; }
14852     };
14854     int main()
14855     {
14856         std::thread t1{f};      // f() executes in separate thread
14857         std::thread t2{F()};    // F()() executes in separate thread
14858     }  // spot the bugs
14860 ##### Example
14862     void f() { std::cout << "Hello "; }
14864     struct F {
14865         void operator()() const { std::cout << "parallel world "; }
14866     };
14868     int main()
14869     {
14870         std::thread t1{f};      // f() executes in separate thread
14871         std::thread t2{F()};    // F()() executes in separate thread
14873         t1.join();
14874         t2.join();
14875     }  // one bad bug left
14877 ##### Note
14879 Make "immortal threads" globals, put them in an enclosing scope, or put them on the free store rather than `detach()`.
14880 [Don't `detach`](#Rconc-detached_thread).
14882 ##### Note
14884 Because of old code and third party libraries using `std::thread`, this rule can be hard to introduce.
14886 ##### Enforcement
14888 Flag uses of `std::thread`:
14890 * Suggest use of `gsl::joining_thread` or C++20 `std::jthread`.
14891 * Suggest ["exporting ownership"](#Rconc-detached_thread) to an enclosing scope if it detaches.
14892 * Warn if it is not obvious whether a thread joins or detaches.
14894 ### <a name="Rconc-detached_thread"></a>CP.26: Don't `detach()` a thread
14896 ##### Reason
14898 Often, the need to outlive the scope of its creation is inherent in the `thread`s task,
14899 but implementing that idea by `detach` makes it harder to monitor and communicate with the detached thread.
14900 In particular, it is harder (though not impossible) to ensure that the thread completed as expected or lives for as long as expected.
14902 ##### Example
14904     void heartbeat();
14906     void use()
14907     {
14908         std::thread t(heartbeat);             // don't join; heartbeat is meant to run forever
14909         t.detach();
14910         // ...
14911     }
14913 This is a reasonable use of a thread, for which `detach()` is commonly used.
14914 There are problems, though.
14915 How do we monitor the detached thread to see if it is alive?
14916 Something might go wrong with the heartbeat, and losing a heartbeat can be very serious in a system for which it is needed.
14917 So, we need to communicate with the heartbeat thread
14918 (e.g., through a stream of messages or notification events using a `condition_variable`).
14920 An alternative, and usually superior solution is to control its lifetime by placing it in a scope outside its point of creation (or activation).
14921 For example:
14923     void heartbeat();
14925     gsl::joining_thread t(heartbeat);             // heartbeat is meant to run "forever"
14927 This heartbeat will (barring error, hardware problems, etc.) run for as long as the program does.
14929 Sometimes, we need to separate the point of creation from the point of ownership:
14931     void heartbeat();
14933     unique_ptr<gsl::joining_thread> tick_tock {nullptr};
14935     void use()
14936     {
14937         // heartbeat is meant to run as long as tick_tock lives
14938         tick_tock = make_unique<gsl::joining_thread>(heartbeat);
14939         // ...
14940     }
14942 #### Enforcement
14944 Flag `detach()`.
14947 ### <a name="Rconc-data-by-value"></a>CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer
14949 ##### Reason
14951 A small amount of data is cheaper to copy and access than to share it using some locking mechanism.
14952 Copying naturally gives unique ownership (simplifies code) and eliminates the possibility of data races.
14954 ##### Note
14956 Defining "small amount" precisely is impossible.
14958 ##### Example
14960     string modify1(string);
14961     void modify2(string&);
14963     void fct(string& s)
14964     {
14965         auto res = async(modify1, s);
14966         async(modify2, s);
14967     }
14969 The call of `modify1` involves copying two `string` values; the call of `modify2` does not.
14970 On the other hand, the implementation of `modify1` is exactly as we would have written it for single-threaded code,
14971 whereas the implementation of `modify2` will need some form of locking to avoid data races.
14972 If the string is short (say 10 characters), the call of `modify1` can be surprisingly fast;
14973 essentially all the cost is in the `thread` switch. If the string is long (say 1,000,000 characters), copying it twice
14974 is probably not a good idea.
14976 Note that this argument has nothing to do with `async` as such. It applies equally to considerations about whether to use
14977 message passing or shared memory.
14979 ##### Enforcement
14984 ### <a name="Rconc-shared"></a>CP.32: To share ownership between unrelated `thread`s use `shared_ptr`
14986 ##### Reason
14988 If threads are unrelated (that is, not known to be in the same scope or one within the lifetime of the other)
14989 and they need to share free store memory that needs to be deleted, a `shared_ptr` (or equivalent) is the only
14990 safe way to ensure proper deletion.
14992 ##### Example
14994     ???
14996 ##### Note
14998 * A static object (e.g. a global) can be shared because it is not owned in the sense that some thread is responsible for its deletion.
14999 * An object on free store that is never to be deleted can be shared.
15000 * An object owned by one thread can be safely shared with another as long as that second thread doesn't outlive the owner.
15002 ##### Enforcement
15007 ### <a name="Rconc-switch"></a>CP.40: Minimize context switching
15009 ##### Reason
15011 Context switches are expensive.
15013 ##### Example
15015     ???
15017 ##### Enforcement
15022 ### <a name="Rconc-create"></a>CP.41: Minimize thread creation and destruction
15024 ##### Reason
15026 Thread creation is expensive.
15028 ##### Example
15030     void worker(Message m)
15031     {
15032         // process
15033     }
15035     void dispatcher(istream& is)
15036     {
15037         for (Message m; is >> m; )
15038             run_list.push_back(new thread(worker, m));
15039     }
15041 This spawns a `thread` per message, and the `run_list` is presumably managed to destroy those tasks once they are finished.
15043 Instead, we could have a set of pre-created worker threads processing the messages
15045     Sync_queue<Message> work;
15047     void dispatcher(istream& is)
15048     {
15049         for (Message m; is >> m; )
15050             work.put(m);
15051     }
15053     void worker()
15054     {
15055         for (Message m; m = work.get(); ) {
15056             // process
15057         }
15058     }
15060     void workers()  // set up worker threads (specifically 4 worker threads)
15061     {
15062         joining_thread w1 {worker};
15063         joining_thread w2 {worker};
15064         joining_thread w3 {worker};
15065         joining_thread w4 {worker};
15066     }
15068 ##### Note
15070 If your system has a good thread pool, use it.
15071 If your system has a good message queue, use it.
15073 ##### Enforcement
15078 ### <a name="Rconc-wait"></a>CP.42: Don't `wait` without a condition
15080 ##### Reason
15082 A `wait` without a condition can miss a wakeup or wake up simply to find that there is no work to do.
15084 ##### Example, bad
15086     std::condition_variable cv;
15087     std::mutex mx;
15089     void thread1()
15090     {
15091         while (true) {
15092             // do some work ...
15093             std::unique_lock<std::mutex> lock(mx);
15094             cv.notify_one();    // wake other thread
15095         }
15096     }
15098     void thread2()
15099     {
15100         while (true) {
15101             std::unique_lock<std::mutex> lock(mx);
15102             cv.wait(lock);    // might block forever
15103             // do work ...
15104         }
15105     }
15107 Here, if some other `thread` consumes `thread1`'s notification, `thread2` can wait forever.
15109 ##### Example
15111     template<typename T>
15112     class Sync_queue {
15113     public:
15114         void put(const T& val);
15115         void put(T&& val);
15116         void get(T& val);
15117     private:
15118         mutex mtx;
15119         condition_variable cond;    // this controls access
15120         list<T> q;
15121     };
15123     template<typename T>
15124     void Sync_queue<T>::put(const T& val)
15125     {
15126         lock_guard<mutex> lck(mtx);
15127         q.push_back(val);
15128         cond.notify_one();
15129     }
15131     template<typename T>
15132     void Sync_queue<T>::get(T& val)
15133     {
15134         unique_lock<mutex> lck(mtx);
15135         cond.wait(lck, [this] { return !q.empty(); });    // prevent spurious wakeup
15136         val = q.front();
15137         q.pop_front();
15138     }
15140 Now if the queue is empty when a thread executing `get()` wakes up (e.g., because another thread has gotten to `get()` before it),
15141 it will immediately go back to sleep, waiting.
15143 ##### Enforcement
15145 Flag all `wait`s without conditions.
15148 ### <a name="Rconc-time"></a>CP.43: Minimize time spent in a critical section
15150 ##### Reason
15152 The less time is spent with a `mutex` taken, the less chance that another `thread` has to wait,
15153 and `thread` suspension and resumption are expensive.
15155 ##### Example
15157     void do_something() // bad
15158     {
15159         unique_lock<mutex> lck(my_lock);
15160         do0();  // preparation: does not need lock
15161         do1();  // transaction: needs locking
15162         do2();  // cleanup: does not need locking
15163     }
15165 Here, we are holding the lock for longer than necessary:
15166 We should not have taken the lock before we needed it and should have released it again before starting the cleanup.
15167 We could rewrite this to
15169     void do_something() // bad
15170     {
15171         do0();  // preparation: does not need lock
15172         my_lock.lock();
15173         do1();  // transaction: needs locking
15174         my_lock.unlock();
15175         do2();  // cleanup: does not need locking
15176     }
15178 But that compromises safety and violates the [use RAII](#Rconc-raii) rule.
15179 Instead, add a block for the critical section:
15181     void do_something() // OK
15182     {
15183         do0();  // preparation: does not need lock
15184         {
15185             unique_lock<mutex> lck(my_lock);
15186             do1();  // transaction: needs locking
15187         }
15188         do2();  // cleanup: does not need locking
15189     }
15191 ##### Enforcement
15193 Impossible in general.
15194 Flag "naked" `lock()` and `unlock()`.
15197 ### <a name="Rconc-name"></a>CP.44: Remember to name your `lock_guard`s and `unique_lock`s
15199 ##### Reason
15201 An unnamed local object is a temporary that immediately goes out of scope.
15203 ##### Example
15205     // global mutexes
15206     mutex m1;
15207     mutex m2;
15209     void f()
15210     {
15211         unique_lock<mutex>(m1); // (A)
15212         lock_guard<mutex> {m2}; // (B)
15213         // do work in critical section ...
15214     }
15216 This looks innocent enough, but it isn't. At (A), `m1` is a default-constructed
15217 local `unique_lock`, which shadows the global `::m1` (and does not lock it).
15218 At (B) an unnamed temporary `lock_guard` is constructed and locks `::m2`,
15219 but immediately goes out of scope and unlocks `::m2` again.
15220 For the rest of the function `f()` neither mutex is locked.
15222 ##### Enforcement
15224 Flag all unnamed `lock_guard`s and `unique_lock`s.
15228 ### <a name="Rconc-mutex"></a>CP.50: Define a `mutex` together with the data it guards. Use `synchronized_value<T>` where possible
15230 ##### Reason
15232 It should be obvious to a reader that the data is to be guarded and how. This decreases the chance of the wrong mutex being locked, or the mutex not being locked.
15234 Using a `synchronized_value<T>` ensures that the data has a mutex, and the right mutex is locked when the data is accessed.
15235 See the [WG21 proposal](http://wg21.link/p0290) to add `synchronized_value` to a future TS or revision of the C++ standard.
15237 ##### Example
15239     struct Record {
15240         std::mutex m;   // take this mutex before accessing other members
15241         // ...
15242     };
15244     class MyClass {
15245         struct DataRecord {
15246            // ...
15247         };
15248         synchronized_value<DataRecord> data; // Protect the data with a mutex
15249     };
15251 ##### Enforcement
15253 ??? Possible?
15256 ## <a name="SScp-coro"></a>CP.coro: Coroutines
15258 This section focuses on uses of coroutines.
15260 Coroutine rule summary:
15262 * [CP.51: Do not use capturing lambdas that are coroutines](#Rcoro-capture)
15263 * [CP.52: Do not hold locks or other synchronization primitives across suspension points](#Rcoro-locks)
15264 * [CP.53: Parameters to coroutines should not be passed by reference](#Rcoro-reference-parameters)
15266 ### <a name="Rcoro-capture"></a>CP.51: Do not use capturing lambdas that are coroutines
15268 ##### Reason
15270 Usage patterns that are correct with normal lambdas are hazardous with coroutine lambdas. The obvious pattern of capturing variables will result in accessing freed memory after the first suspension point, even for refcounted smart pointers and copyable types.
15272 A lambda results in a closure object with storage, often on the stack, that will go out of scope at some point.  When the closure object goes out of scope the captures will also go out of scope.  Normal lambdas will have finished executing by this time so it is not a problem.  Coroutine lambdas may resume from suspension after the closure object has destructed and at that point all captures will be use-after-free memory access.
15274 ##### Example, Bad
15276     int value = get_value();
15277     std::shared_ptr<Foo> sharedFoo = get_foo();
15278     {
15279       const auto lambda = [value, sharedFoo]() -> std::future<void>
15280       {
15281         co_await something();
15282         // "sharedFoo" and "value" have already been destroyed
15283         // the "shared" pointer didn't accomplish anything
15284       };
15285       lambda();
15286     } // the lambda closure object has now gone out of scope
15288 ##### Example, Better
15290     int value = get_value();
15291     std::shared_ptr<Foo> sharedFoo = get_foo();
15292     {
15293       // take as by-value parameter instead of as a capture
15294       const auto lambda = [](auto sharedFoo, auto value) -> std::future<void>
15295       {
15296         co_await something();
15297         // sharedFoo and value are still valid at this point
15298       };
15299       lambda(sharedFoo, value);
15300     } // the lambda closure object has now gone out of scope
15302 ##### Example, Best
15304 Use a function for coroutines.
15306     std::future<void> Class::do_something(int value, std::shared_ptr<Foo> sharedFoo)
15307     {
15308       co_await something();
15309       // sharedFoo and value are still valid at this point
15310     }
15312     void SomeOtherFunction()
15313     {
15314       int value = get_value();
15315       std::shared_ptr<Foo> sharedFoo = get_foo();
15316       do_something(value, sharedFoo);
15317     }
15319 ##### Enforcement
15321 Flag a lambda that is a coroutine and has a non-empty capture list.
15324 ### <a name="Rcoro-locks"></a>CP.52: Do not hold locks or other synchronization primitives across suspension points
15326 ##### Reason
15328 This pattern creates a significant risk of deadlocks.  Some types of waits will allow the current thread to perform additional work until the asynchronous operation has completed. If the thread holding the lock performs work that requires the same lock then it will deadlock because it is trying to acquire a lock that it is already holding.
15330 If the coroutine completes on a different thread from the thread that acquired the lock then that is undefined behavior.  Even with an explicit return to the original thread an exception might be thrown before coroutine resumes and the result will be that the lock guard is not destructed.
15332 ##### Example, Bad
15334     std::mutex g_lock;
15336     std::future<void> Class::do_something()
15337     {
15338         std::lock_guard<std::mutex> guard(g_lock);
15339         co_await something(); // DANGER: coroutine has suspended execution while holding a lock
15340         co_await somethingElse();
15341     }
15343 ##### Example, Good
15345     std::mutex g_lock;
15347     std::future<void> Class::do_something()
15348     {
15349         {
15350             std::lock_guard<std::mutex> guard(g_lock);
15351             // modify data protected by lock
15352         }
15353         co_await something(); // OK: lock has been released before coroutine suspends
15354         co_await somethingElse();
15355     }
15358 ##### Note
15360 This pattern is also bad for performance. When a suspension point is reached, such as co_await, execution of the current function stops and other code begins to run. It may be a long period of time before the coroutine resumes. For that entire duration the lock will be held and cannot be acquired by other threads to perform work.
15362 ##### Enforcement
15364 Flag all lock guards that are not destructed before a coroutine suspends.
15366 ### <a name="Rcoro-reference-parameters"></a>CP.53: Parameters to coroutines should not be passed by reference
15368 ##### Reason
15370 Once a coroutine reaches the first suspension point, such as a co_await, the synchronous portion returns. After that point any parameters passed by reference are dangling. Any usage beyond that is undefined behavior which may include writing to freed memory.
15372 ##### Example, Bad
15374     std::future<int> Class::do_something(const std::shared_ptr<int>& input)
15375     {
15376         co_await something();
15378         // DANGER: the reference to input may no longer be valid and may be freed memory
15379         co_return *input + 1;
15380     }
15382 ##### Example, Good
15384     std::future<int> Class::do_something(std::shared_ptr<int> input)
15385     {
15386         co_await something();
15387         co_return *input + 1; // input is a copy that is still valid here
15388     }
15390 ##### Note
15392 This problem does not apply to reference parameters that are only accessed before the first suspension point. Subsequent changes to the function may add or move suspension points which would reintroduce this class of bug. Some types of coroutines have the suspension point before the first line of code in the coroutine executes, in which case reference parameters are always unsafe.  It is safer to always pass by value because the copied parameter will live in the coroutine frame that is safe to access throughout the coroutine.
15394 ##### Note
15396 The same danger applies to output parameters.  [F.20: For "out" output values, prefer return values to output parameters](#Rf-out) discourages output parameters.  Coroutines should avoid them entirely.
15398 ##### Enforcement
15400 Flag all reference parameters to a coroutine.
15402 ## <a name="SScp-par"></a>CP.par: Parallelism
15404 By "parallelism" we refer to performing a task (more or less) simultaneously ("in parallel with") on many data items.
15406 Parallelism rule summary:
15408 * ???
15409 * ???
15410 * Where appropriate, prefer the standard-library parallel algorithms
15411 * Use algorithms that are designed for parallelism, not algorithms with unnecessary dependency on linear evaluation
15415 ## <a name="SScp-mess"></a>CP.mess: Message passing
15417 The standard-library facilities are quite low-level, focused on the needs of close-to the hardware critical programming using `thread`s, `mutex`es, `atomic` types, etc.
15418 Most people shouldn't work at this level: it's error-prone and development is slow.
15419 If possible, use a higher level facility: messaging libraries, parallel algorithms, and vectorization.
15420 This section looks at passing messages so that a programmer doesn't have to do explicit synchronization.
15422 Message passing rules summary:
15424 * [CP.60: Use a `future` to return a value from a concurrent task](#Rconc-future)
15425 * [CP.61: Use `async()` to spawn concurrent tasks](#Rconc-async)
15426 * message queues
15427 * messaging libraries
15429 ???? should there be a "use X rather than `std::async`" where X is something that would use a better specified thread pool?
15431 ??? Is `std::async` worth using in light of future (and even existing, as libraries) parallelism facilities? What should the guidelines recommend if someone wants to parallelize, e.g., `std::accumulate` (with the additional precondition of commutativity), or merge sort?
15434 ### <a name="Rconc-future"></a>CP.60: Use a `future` to return a value from a concurrent task
15436 ##### Reason
15438 A `future` preserves the usual function call return semantics for asynchronous tasks.
15439 There is no explicit locking and both correct (value) return and error (exception) return are handled simply.
15441 ##### Example
15443     ???
15445 ##### Note
15449 ##### Enforcement
15453 ### <a name="Rconc-async"></a>CP.61: Use `async()` to spawn concurrent tasks
15455 ##### Reason
15457 Similar to [R.12](#Rr-immediate-alloc), which tells you to avoid raw owning pointers, you should
15458 also avoid raw threads and raw promises where possible. Use a factory function such as `std::async`,
15459 which handles spawning or reusing a thread without exposing raw threads to your own code.
15461 ##### Example
15463     int read_value(const std::string& filename)
15464     {
15465         std::ifstream in(filename);
15466         in.exceptions(std::ifstream::failbit);
15467         int value;
15468         in >> value;
15469         return value;
15470     }
15472     void async_example()
15473     {
15474         try {
15475             std::future<int> f1 = std::async(read_value, "v1.txt");
15476             std::future<int> f2 = std::async(read_value, "v2.txt");
15477             std::cout << f1.get() + f2.get() << '\n';
15478         } catch (const std::ios_base::failure& fail) {
15479             // handle exception here
15480         }
15481     }
15483 ##### Note
15485 Unfortunately, `std::async` is not perfect. For example, it doesn't use a thread pool,
15486 which means that it might fail due to resource exhaustion, rather than queuing up your tasks
15487 to be executed later. However, even if you cannot use `std::async`, you should prefer to
15488 write your own `future`-returning factory function, rather than using raw promises.
15490 ##### Example (bad)
15492 This example shows two different ways to succeed at using `std::future`, but to fail
15493 at avoiding raw `std::thread` management.
15495     void async_example()
15496     {
15497         std::promise<int> p1;
15498         std::future<int> f1 = p1.get_future();
15499         std::thread t1([p1 = std::move(p1)]() mutable {
15500             p1.set_value(read_value("v1.txt"));
15501         });
15502         t1.detach(); // evil
15504         std::packaged_task<int()> pt2(read_value, "v2.txt");
15505         std::future<int> f2 = pt2.get_future();
15506         std::thread(std::move(pt2)).detach();
15508         std::cout << f1.get() + f2.get() << '\n';
15509     }
15511 ##### Example (good)
15513 This example shows one way you could follow the general pattern set by
15514 `std::async`, in a context where `std::async` itself was unacceptable for
15515 use in production.
15517     void async_example(WorkQueue& wq)
15518     {
15519         std::future<int> f1 = wq.enqueue([]() {
15520             return read_value("v1.txt");
15521         });
15522         std::future<int> f2 = wq.enqueue([]() {
15523             return read_value("v2.txt");
15524         });
15525         std::cout << f1.get() + f2.get() << '\n';
15526     }
15528 Any threads spawned to execute the code of `read_value` are hidden behind
15529 the call to `WorkQueue::enqueue`. The user code deals only with `future`
15530 objects, never with raw `thread`, `promise`, or `packaged_task` objects.
15532 ##### Enforcement
15537 ## <a name="SScp-vec"></a>CP.vec: Vectorization
15539 Vectorization is a technique for executing a number of tasks concurrently without introducing explicit synchronization.
15540 An operation is simply applied to elements of a data structure (a vector, an array, etc.) in parallel.
15541 Vectorization has the interesting property of often requiring no non-local changes to a program.
15542 However, vectorization works best with simple data structures and with algorithms specifically crafted to enable it.
15544 Vectorization rule summary:
15546 * ???
15547 * ???
15549 ## <a name="SScp-free"></a>CP.free: Lock-free programming
15551 Synchronization using `mutex`es and `condition_variable`s can be relatively expensive.
15552 Furthermore, it can lead to deadlock.
15553 For performance and to eliminate the possibility of deadlock, we sometimes have to use the tricky low-level "lock-free" facilities
15554 that rely on briefly gaining exclusive ("atomic") access to memory.
15555 Lock-free programming is also used to implement higher-level concurrency mechanisms, such as `thread`s and `mutex`es.
15557 Lock-free programming rule summary:
15559 * [CP.100: Don't use lock-free programming unless you absolutely have to](#Rconc-lockfree)
15560 * [CP.101: Distrust your hardware/compiler combination](#Rconc-distrust)
15561 * [CP.102: Carefully study the literature](#Rconc-literature)
15562 * how/when to use atomics
15563 * avoid starvation
15564 * use a lock-free data structure rather than hand-crafting specific lock-free access
15565 * [CP.110: Do not write your own double-checked locking for initialization](#Rconc-double)
15566 * [CP.111: Use a conventional pattern if you really need double-checked locking](#Rconc-double-pattern)
15567 * how/when to compare and swap
15570 ### <a name="Rconc-lockfree"></a>CP.100: Don't use lock-free programming unless you absolutely have to
15572 ##### Reason
15574 It's error-prone and requires expert level knowledge of language features, machine architecture, and data structures.
15576 ##### Example, bad
15578     extern atomic<Link*> head;        // the shared head of a linked list
15580     Link* nh = new Link(data, nullptr);    // make a link ready for insertion
15581     Link* h = head.load();                 // read the shared head of the list
15583     do {
15584         if (h->data <= data) break;        // if so, insert elsewhere
15585         nh->next = h;                      // next element is the previous head
15586     } while (!head.compare_exchange_weak(h, nh));    // write nh to head or to h
15588 Spot the bug.
15589 It would be really hard to find through testing.
15590 Read up on the ABA problem.
15592 ##### Exception
15594 [Atomic variables](#???) can be used simply and safely, as long as you are using the sequentially consistent memory model (memory_order_seq_cst), which is the default.
15596 ##### Note
15598 Higher-level concurrency mechanisms, such as `thread`s and `mutex`es are implemented using lock-free programming.
15600 **Alternative**: Use lock-free data structures implemented by others as part of some library.
15603 ### <a name="Rconc-distrust"></a>CP.101: Distrust your hardware/compiler combination
15605 ##### Reason
15607 The low-level hardware interfaces used by lock-free programming are among the hardest to implement well and among
15608 the areas where the most subtle portability problems occur.
15609 If you are doing lock-free programming for performance, you need to check for regressions.
15611 ##### Note
15613 Instruction reordering (static and dynamic) makes it hard for us to think effectively at this level (especially if you use relaxed memory models).
15614 Experience, (semi)formal models and model checking can be useful.
15615 Testing - often to an extreme extent - is essential.
15616 "Don't fly too close to the sun."
15618 ##### Enforcement
15620 Have strong rules for re-testing in place that covers any change in hardware, operating system, compiler, and libraries.
15623 ### <a name="Rconc-literature"></a>CP.102: Carefully study the literature
15625 ##### Reason
15627 With the exception of atomics and a few other standard patterns, lock-free programming is really an expert-only topic.
15628 Become an expert before shipping lock-free code for others to use.
15630 ##### References
15632 * Anthony Williams: C++ concurrency in action. Manning Publications.
15633 * Boehm, Adve, You Don't Know Jack About Shared Variables or Memory Models , Communications of the ACM, Feb 2012.
15634 * Boehm, "Threads Basics", HPL TR 2009-259.
15635 * Adve, Boehm, "Memory Models: A Case for Rethinking Parallel Languages and Hardware", Communications of the ACM, August 2010.
15636 * Boehm, Adve, "Foundations of the C++ Concurrency Memory Model", PLDI 08.
15637 * Mark Batty, Scott Owens, Susmit Sarkar, Peter Sewell, and Tjark Weber, "Mathematizing C++ Concurrency", POPL 2011.
15638 * Damian Dechev, Peter Pirkelbauer, and Bjarne Stroustrup: Understanding and Effectively Preventing the ABA Problem in Descriptor-based Lock-free Designs. 13th IEEE Computer Society ISORC 2010 Symposium. May 2010.
15639 * Damian Dechev and Bjarne Stroustrup: Scalable Non-blocking Concurrent Objects for Mission Critical Code. ACM OOPSLA'09. October 2009
15640 * Damian Dechev, Peter Pirkelbauer, Nicolas Rouquette, and Bjarne Stroustrup: Semantically Enhanced Containers for Concurrent Real-Time Systems. Proc. 16th Annual IEEE International Conference and Workshop on the Engineering of Computer Based Systems (IEEE ECBS). April 2009.
15641 * Maurice Herlihy, Nir Shavit, Victor Luchangco, Michael Spear, "The Art of Multiprocessor Programming", 2nd ed. September 2020
15643 ### <a name="Rconc-double"></a>CP.110: Do not write your own double-checked locking for initialization
15645 ##### Reason
15647 Since C++11, static local variables are now initialized in a thread-safe way. When combined with the RAII pattern, static local variables can replace the need for writing your own double-checked locking for initialization. std::call_once can also achieve the same purpose. Use either static local variables of C++11 or std::call_once instead of writing your own double-checked locking for initialization.
15649 ##### Example
15651 Example with std::call_once.
15653     void f()
15654     {
15655         static std::once_flag my_once_flag;
15656         std::call_once(my_once_flag, []()
15657         {
15658             // do this only once
15659         });
15660         // ...
15661     }
15663 Example with thread-safe static local variables of C++11.
15665     void f()
15666     {
15667         // Assuming the compiler is compliant with C++11
15668         static My_class my_object; // Constructor called only once
15669         // ...
15670     }
15672     class My_class
15673     {
15674     public:
15675         My_class()
15676         {
15677             // do this only once
15678         }
15679     };
15681 ##### Enforcement
15683 ??? Is it possible to detect the idiom?
15686 ### <a name="Rconc-double-pattern"></a>CP.111: Use a conventional pattern if you really need double-checked locking
15688 ##### Reason
15690 Double-checked locking is easy to mess up. If you really need to write your own double-checked locking, in spite of the rules [CP.110: Do not write your own double-checked locking for initialization](#Rconc-double) and [CP.100: Don't use lock-free programming unless you absolutely have to](#Rconc-lockfree), then do it in a conventional pattern.
15692 The uses of the double-checked locking pattern that are not in violation of [CP.110: Do not write your own double-checked locking for initialization](#Rconc-double) arise when a non-thread-safe action is both hard and rare, and there exists a fast thread-safe test that can be used to guarantee that the action is not needed, but cannot be used to guarantee the converse.
15694 ##### Example, bad
15696 The use of volatile does not make the first check thread-safe, see also [CP.200: Use `volatile` only to talk to non-C++ memory](#Rconc-volatile2)
15698     mutex action_mutex;
15699     volatile bool action_needed;
15701     if (action_needed) {
15702         std::lock_guard<std::mutex> lock(action_mutex);
15703         if (action_needed) {
15704             take_action();
15705             action_needed = false;
15706         }
15707     }
15709 ##### Example, good
15711     mutex action_mutex;
15712     atomic<bool> action_needed;
15714     if (action_needed) {
15715         std::lock_guard<std::mutex> lock(action_mutex);
15716         if (action_needed) {
15717             take_action();
15718             action_needed = false;
15719         }
15720     }
15722 Fine-tuned memory order might be beneficial where acquire load is more efficient than sequentially-consistent load
15724     mutex action_mutex;
15725     atomic<bool> action_needed;
15727     if (action_needed.load(memory_order_acquire)) {
15728         lock_guard<std::mutex> lock(action_mutex);
15729         if (action_needed.load(memory_order_relaxed)) {
15730             take_action();
15731             action_needed.store(false, memory_order_release);
15732         }
15733     }
15735 ##### Enforcement
15737 ??? Is it possible to detect the idiom?
15740 ## <a name="SScp-etc"></a>CP.etc: Etc. concurrency rules
15742 These rules defy simple categorization:
15744 * [CP.200: Use `volatile` only to talk to non-C++ memory](#Rconc-volatile2)
15745 * [CP.201: ??? Signals](#Rconc-signal)
15747 ### <a name="Rconc-volatile2"></a>CP.200: Use `volatile` only to talk to non-C++ memory
15749 ##### Reason
15751 `volatile` is used to refer to objects that are shared with "non-C++" code or hardware that does not follow the C++ memory model.
15753 ##### Example
15755     const volatile long clock;
15757 This describes a register constantly updated by a clock circuit.
15758 `clock` is `volatile` because its value will change without any action from the C++ program that uses it.
15759 For example, reading `clock` twice will often yield two different values, so the optimizer had better not optimize away the second read in this code:
15761     long t1 = clock;
15762     // ... no use of clock here ...
15763     long t2 = clock;
15765 `clock` is `const` because the program should not try to write to `clock`.
15767 ##### Note
15769 Unless you are writing the lowest level code manipulating hardware directly, consider `volatile` an esoteric feature that is best avoided.
15771 ##### Example
15773 Usually C++ code receives `volatile` memory that is owned elsewhere (hardware or another language):
15775     int volatile* vi = get_hardware_memory_location();
15776         // note: we get a pointer to someone else's memory here
15777         // volatile says "treat this with extra respect"
15779 Sometimes C++ code allocates the `volatile` memory and shares it with "elsewhere" (hardware or another language) by deliberately escaping a pointer:
15781     static volatile long vl;
15782     please_use_this(&vl);   // escape a reference to this to "elsewhere" (not C++)
15784 ##### Example, bad
15786 `volatile` local variables are nearly always wrong -- how can they be shared with other languages or hardware if they're ephemeral?
15787 The same applies almost as strongly to member variables, for the same reason.
15789     void f()
15790     {
15791         volatile int i = 0; // bad, volatile local variable
15792         // etc.
15793     }
15795     class My_type {
15796         volatile int i = 0; // suspicious, volatile member variable
15797         // etc.
15798     };
15800 ##### Note
15802 In C++, unlike in some other languages, `volatile` has [nothing to do with synchronization](#Rconc-volatile).
15804 ##### Enforcement
15806 * Flag `volatile T` local and member variables; almost certainly you intended to use `atomic<T>` instead.
15807 * ???
15809 ### <a name="Rconc-signal"></a>CP.201: ??? Signals
15811 ???UNIX signal handling???. Might be worth reminding how little is async-signal-safe, and how to communicate with a signal handler (best is probably "not at all")
15814 # <a name="S-errors"></a>E: Error handling
15816 Error handling involves:
15818 * Detecting an error
15819 * Transmitting information about an error to some handler code
15820 * Preserving a valid state of the program
15821 * Avoiding resource leaks
15823 It is not possible to recover from all errors. If recovery from an error is not possible, it is important to quickly "get out" in a well-defined way. A strategy for error handling must be simple, or it becomes a source of even worse errors.  Untested and rarely executed error-handling code is itself the source of many bugs.
15825 The rules are designed to help avoid several kinds of errors:
15827 * Type violations (e.g., misuse of `union`s and casts)
15828 * Resource leaks (including memory leaks)
15829 * Bounds errors
15830 * Lifetime errors (e.g., accessing an object after it has been `delete`d)
15831 * Complexity errors (logical errors made likely by overly complex expression of ideas)
15832 * Interface errors (e.g., an unexpected value is passed through an interface)
15834 Error-handling rule summary:
15836 * [E.1: Develop an error-handling strategy early in a design](#Re-design)
15837 * [E.2: Throw an exception to signal that a function can't perform its assigned task](#Re-throw)
15838 * [E.3: Use exceptions for error handling only](#Re-errors)
15839 * [E.4: Design your error-handling strategy around invariants](#Re-design-invariants)
15840 * [E.5: Let a constructor establish an invariant, and throw if it cannot](#Re-invariant)
15841 * [E.6: Use RAII to prevent leaks](#Re-raii)
15842 * [E.7: State your preconditions](#Re-precondition)
15843 * [E.8: State your postconditions](#Re-postcondition)
15845 * [E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable](#Re-noexcept)
15846 * [E.13: Never throw while being the direct owner of an object](#Re-never-throw)
15847 * [E.14: Use purpose-designed user-defined types as exceptions (not built-in types)](#Re-exception-types)
15848 * [E.15: Throw by value, catch exceptions from a hierarchy by reference](#Re-exception-ref)
15849 * [E.16: Destructors, deallocation, `swap`, and exception type copy/move construction must never fail](#Re-never-fail)
15850 * [E.17: Don't try to catch every exception in every function](#Re-not-always)
15851 * [E.18: Minimize the use of explicit `try`/`catch`](#Re-catch)
15852 * [E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available](#Re-finally)
15854 * [E.25: If you can't throw exceptions, simulate RAII for resource management](#Re-no-throw-raii)
15855 * [E.26: If you can't throw exceptions, consider failing fast](#Re-no-throw-crash)
15856 * [E.27: If you can't throw exceptions, use error codes systematically](#Re-no-throw-codes)
15857 * [E.28: Avoid error handling based on global state (e.g. `errno`)](#Re-no-throw)
15859 * [E.30: Don't use exception specifications](#Re-specifications)
15860 * [E.31: Properly order your `catch`-clauses](#Re_catch)
15862 ### <a name="Re-design"></a>E.1: Develop an error-handling strategy early in a design
15864 ##### Reason
15866 A consistent and complete strategy for handling errors and resource leaks is hard to retrofit into a system.
15868 ### <a name="Re-throw"></a>E.2: Throw an exception to signal that a function can't perform its assigned task
15870 ##### Reason
15872 To make error handling systematic, robust, and non-repetitive.
15874 ##### Example
15876     struct Foo {
15877         vector<Thing> v;
15878         File_handle f;
15879         string s;
15880     };
15882     void use()
15883     {
15884         Foo bar {{Thing{1}, Thing{2}, Thing{monkey}}, {"my_file", "r"}, "Here we go!"};
15885         // ...
15886     }
15888 Here, `vector` and `string`s constructors might not be able to allocate sufficient memory for their elements, `vector`s constructor might not be able to copy the `Thing`s in its initializer list, and `File_handle` might not be able to open the required file.
15889 In each case, they throw an exception for `use()`'s caller to handle.
15890 If `use()` could handle the failure to construct `bar` it can take control using `try`/`catch`.
15891 In either case, `Foo`'s constructor correctly destroys constructed members before passing control to whatever tried to create a `Foo`.
15892 Note that there is no return value that could contain an error code.
15894 The `File_handle` constructor might be defined like this:
15896     File_handle::File_handle(const string& name, const string& mode)
15897         : f{fopen(name.c_str(), mode.c_str())}
15898     {
15899         if (!f)
15900             throw runtime_error{"File_handle: could not open " + name + " as " + mode};
15901     }
15903 ##### Note
15905 It is often said that exceptions are meant to signal exceptional events and failures.
15906 However, that's a bit circular because "what is exceptional?"
15907 Examples:
15909 * A precondition that cannot be met
15910 * A constructor that cannot construct an object (failure to establish its class's [invariant](#Rc-struct))
15911 * An out-of-range error (e.g., `v[v.size()] = 7`)
15912 * Inability to acquire a resource (e.g., the network is down)
15914 In contrast, termination of an ordinary loop is not exceptional.
15915 Unless the loop was meant to be infinite, termination is normal and expected.
15917 ##### Note
15919 Don't use a `throw` as simply an alternative way of returning a value from a function.
15921 ##### Exception
15923 Some systems, such as hard-real-time systems require a guarantee that an action is taken in a (typically short) constant maximum time known before execution starts. Such systems can use exceptions only if there is tool support for accurately predicting the maximum time to recover from a `throw`.
15925 **See also**: [RAII](#Re-raii)
15927 **See also**: [discussion](#Sd-noexcept)
15929 ##### Note
15931 Before deciding that you cannot afford or don't like exception-based error handling, have a look at the [alternatives](#Re-no-throw-raii);
15932 they have their own complexities and problems.
15933 Also, as far as possible, measure before making claims about efficiency.
15935 ### <a name="Re-errors"></a>E.3: Use exceptions for error handling only
15937 ##### Reason
15939 To keep error handling separated from "ordinary code."
15940 C++ implementations tend to be optimized based on the assumption that exceptions are rare.
15942 ##### Example, don't
15944     // don't: exception not used for error handling
15945     int find_index(vector<string>& vec, const string& x)
15946     {
15947         try {
15948             for (gsl::index i = 0; i < vec.size(); ++i)
15949                 if (vec[i] == x) throw i;  // found x
15950         }
15951         catch (int i) {
15952             return i;
15953         }
15954         return -1;   // not found
15955     }
15957 This is more complicated and most likely runs much slower than the obvious alternative.
15958 There is nothing exceptional about finding a value in a `vector`.
15960 ##### Enforcement
15962 Would need to be heuristic.
15963 Look for exception values "leaked" out of `catch` clauses.
15965 ### <a name="Re-design-invariants"></a>E.4: Design your error-handling strategy around invariants
15967 ##### Reason
15969 To use an object it must be in a valid state (defined formally or informally by an invariant) and to recover from an error every object not destroyed must be in a valid state.
15971 ##### Note
15973 An [invariant](#Rc-struct) is a logical condition for the members of an object that a constructor must establish for the public member functions to assume.
15975 ##### Enforcement
15979 ### <a name="Re-invariant"></a>E.5: Let a constructor establish an invariant, and throw if it cannot
15981 ##### Reason
15983 Leaving an object without its invariant established is asking for trouble.
15984 Not all member functions can be called.
15986 ##### Example
15988     class Vector {  // very simplified vector of doubles
15989         // if elem != nullptr then elem points to sz doubles
15990     public:
15991         Vector() : elem{nullptr}, sz{0}{}
15992         Vector(int s) : elem{new double[s]}, sz{s} { /* initialize elements */ }
15993         ~Vector() { delete [] elem; }
15994         double& operator[](int s) { return elem[s]; }
15995         // ...
15996     private:
15997         owner<double*> elem;
15998         int sz;
15999     };
16001 The class invariant - here stated as a comment - is established by the constructors.
16002 `new` throws if it cannot allocate the required memory.
16003 The operators, notably the subscript operator, rely on the invariant.
16005 **See also**: [If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
16007 ##### Enforcement
16009 Flag classes with `private` state without a constructor (public, protected, or private).
16011 ### <a name="Re-raii"></a>E.6: Use RAII to prevent leaks
16013 ##### Reason
16015 Leaks are typically unacceptable.
16016 Manual resource release is error-prone.
16017 RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks.
16019 ##### Example
16021     void f1(int i)   // Bad: possible leak
16022     {
16023         int* p = new int[12];
16024         // ...
16025         if (i < 17) throw Bad{"in f()", i};
16026         // ...
16027     }
16029 We could carefully release the resource before the throw:
16031     void f2(int i)   // Clumsy and error-prone: explicit release
16032     {
16033         int* p = new int[12];
16034         // ...
16035         if (i < 17) {
16036             delete[] p;
16037             throw Bad{"in f()", i};
16038         }
16039         // ...
16040     }
16042 This is verbose. In larger code with multiple possible `throw`s explicit releases become repetitive and error-prone.
16044     void f3(int i)   // OK: resource management done by a handle (but see below)
16045     {
16046         auto p = make_unique<int[]>(12);
16047         // ...
16048         if (i < 17) throw Bad{"in f()", i};
16049         // ...
16050     }
16052 Note that this works even when the `throw` is implicit because it happened in a called function:
16054     void f4(int i)   // OK: resource management done by a handle (but see below)
16055     {
16056         auto p = make_unique<int[]>(12);
16057         // ...
16058         helper(i);   // might throw
16059         // ...
16060     }
16062 Unless you really need pointer semantics, use a local resource object:
16064     void f5(int i)   // OK: resource management done by local object
16065     {
16066         vector<int> v(12);
16067         // ...
16068         helper(i);   // might throw
16069         // ...
16070     }
16072 That's even simpler and safer, and often more efficient.
16074 ##### Note
16076 If there is no obvious resource handle and for some reason defining a proper RAII object/handle is infeasible,
16077 as a last resort, cleanup actions can be represented by a [`final_action`](#Re-finally) object.
16079 ##### Note
16081 But what do we do if we are writing a program where exceptions cannot be used?
16082 First challenge that assumption; there are many anti-exceptions myths around.
16083 We know of only a few good reasons:
16085 * We are on a system so small that the exception support would eat up most of our 2K memory.
16086 * We are in a hard-real-time system and we don't have tools that guarantee us that an exception is handled within the required time.
16087 * We are in a system with tons of legacy code using lots of pointers in difficult-to-understand ways
16088   (in particular without a recognizable ownership strategy) so that exceptions could cause leaks.
16089 * Our implementation of the C++ exception mechanisms is unreasonably poor
16090 (slow, memory consuming, failing to work correctly for dynamically linked libraries, etc.).
16091 Complain to your implementation purveyor; if no user complains, no improvement will happen.
16092 * We get fired if we challenge our manager's ancient wisdom.
16094 Only the first of these reasons is fundamental, so whenever possible, use exceptions to implement RAII, or design your RAII objects to never fail.
16095 When exceptions cannot be used, simulate RAII.
16096 That is, systematically check that objects are valid after construction and still release all resources in the destructor.
16097 One strategy is to add a `valid()` operation to every resource handle:
16099     void f()
16100     {
16101         vector<string> vs(100);   // not std::vector: valid() added
16102         if (!vs.valid()) {
16103             // handle error or exit
16104         }
16106         ifstream fs("foo");   // not std::ifstream: valid() added
16107         if (!fs.valid()) {
16108             // handle error or exit
16109         }
16111         // ...
16112     } // destructors clean up as usual
16114 Obviously, this increases the size of the code, doesn't allow for implicit propagation of "exceptions" (`valid()` checks), and `valid()` checks can be forgotten.
16115 Prefer to use exceptions.
16117 **See also**: [Use of `noexcept`](#Re-noexcept)
16119 ##### Enforcement
16123 ### <a name="Re-precondition"></a>E.7: State your preconditions
16125 ##### Reason
16127 To avoid interface errors.
16129 **See also**: [precondition rule](#Ri-pre)
16131 ### <a name="Re-postcondition"></a>E.8: State your postconditions
16133 ##### Reason
16135 To avoid interface errors.
16137 **See also**: [postcondition rule](#Ri-post)
16139 ### <a name="Re-noexcept"></a>E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable
16141 ##### Reason
16143 To make error handling systematic, robust, and efficient.
16145 ##### Example
16147     double compute(double d) noexcept
16148     {
16149         return log(sqrt(d <= 0 ? 1 : d));
16150     }
16152 Here, we know that `compute` will not throw because it is composed out of operations that don't throw.
16153 By declaring `compute` to be `noexcept`, we give the compiler and human readers information that can make it easier for them to understand and manipulate `compute`.
16155 ##### Note
16157 Many standard-library functions are `noexcept` including all the standard-library functions "inherited" from the C Standard Library.
16159 ##### Example
16161     vector<double> munge(const vector<double>& v) noexcept
16162     {
16163         vector<double> v2(v.size());
16164         // ... do something ...
16165     }
16167 The `noexcept` here states that I am not willing or able to handle the situation where I cannot construct the local `vector`.
16168 That is, I consider memory exhaustion a serious design error (on par with hardware failures) so that I'm willing to crash the program if it happens.
16170 ##### Note
16172 Do not use traditional [exception-specifications](#Re-specifications).
16174 ##### See also
16176 [discussion](#Sd-noexcept).
16178 ### <a name="Re-never-throw"></a>E.13: Never throw while being the direct owner of an object
16180 ##### Reason
16182 That would be a leak.
16184 ##### Example
16186     void leak(int x)   // don't: might leak
16187     {
16188         auto p = new int{7};
16189         if (x < 0) throw Get_me_out_of_here{};  // might leak *p
16190         // ...
16191         delete p;   // we might never get here
16192     }
16194 One way of avoiding such problems is to use resource handles consistently:
16196     void no_leak(int x)
16197     {
16198         auto p = make_unique<int>(7);
16199         if (x < 0) throw Get_me_out_of_here{};  // will delete *p if necessary
16200         // ...
16201         // no need for delete p
16202     }
16204 Another solution (often better) would be to use a local variable to eliminate explicit use of pointers:
16206     void no_leak_simplified(int x)
16207     {
16208         vector<int> v(7);
16209         // ...
16210     }
16212 ##### Note
16214 If you have a local "thing" that requires cleanup, but is not represented by an object with a destructor, such cleanup must
16215 also be done before a `throw`.
16216 Sometimes, [`finally()`](#Re-finally) can make such unsystematic cleanup a bit more manageable.
16218 ### <a name="Re-exception-types"></a>E.14: Use purpose-designed user-defined types as exceptions (not built-in types)
16220 ##### Reason
16222 A user-defined type can better transmit information about an error to a handler.  Information
16223 can be encoded into the type itself and the type is unlikely to clash with other people's exceptions.
16225 ##### Example
16227     throw 7; // bad
16229     throw "something bad";  // bad
16231     throw std::exception{}; // bad - no info
16233 Deriving from `std::exception` gives the flexibility to catch the specific exception or handle generally through `std::exception`:
16235     class MyException : public std::runtime_error
16236     {
16237     public:
16238         MyException(const string& msg) : std::runtime_error{msg} {}
16239         // ...
16240     };
16242     // ...
16244     throw MyException{"something bad"};  // good
16246 Exceptions do not need to be derived from `std::exception`:
16248     class MyCustomError final {};  // not derived from std::exception
16250     // ...
16252     throw MyCustomError{};  // good - handlers must catch this type (or ...)
16254 Library types derived from `std::exception` can be used as generic exceptions if
16255 no useful information can be added at the point of detection:
16257     throw std::runtime_error("someting bad"); // good
16259     // ...
16261     throw std::invalid_argument("i is not even"); // good
16263 `enum` classes are also allowed:
16265     enum class alert {RED, YELLOW, GREEN};
16267     throw alert::RED; // good
16269 ##### Enforcement
16271 Catch `throw` of built-in types and `std::exception`.
16273 ### <a name="Re-exception-ref"></a>E.15: Throw by value, catch exceptions from a hierarchy by reference
16275 ##### Reason
16277 Throwing by value (not by pointer) and catching by reference prevents copying, especially slicing base subobjects.
16279 ##### Example; bad
16281     void f()
16282     {
16283         try {
16284             // ...
16285             throw new widget{}; // don't: throw by value not by raw pointer
16286             // ...
16287         }
16288         catch (base_class e) {  // don't: might slice
16289             // ...
16290         }
16291     }
16293 Instead, use a reference:
16295     catch (base_class& e) { /* ... */ }
16297 or - typically better still - a `const` reference:
16299     catch (const base_class& e) { /* ... */ }
16301 Most handlers do not modify their exception and in general we [recommend use of `const`](#Res-const).
16303 ##### Note
16305 Catch by value can be appropriate for a small value type such as an `enum` value.
16307 ##### Note
16309 To rethrow a caught exception use `throw;` not `throw e;`. Using `throw e;` would throw a new copy of `e` (sliced to the static type `std::exception`, when the exception is caught by `catch (const std::exception& e)`) instead of rethrowing the original exception of type `std::runtime_error`. (But keep [Don't try to catch every exception in every function](#Re-not-always) and [Minimize the use of explicit `try`/`catch`](#Re-catch) in mind.)
16311 ##### Enforcement
16313 * Flag catching by value of a type that has a virtual function.
16314 * Flag throwing raw pointers.
16316 ### <a name="Re-never-fail"></a>E.16: Destructors, deallocation, `swap`, and exception type copy/move construction must never fail
16318 ##### Reason
16320 We don't know how to write reliable programs if a destructor, a swap, a memory deallocation, or attempting to copy/move-construct an exception object fails; that is, if it exits by an exception or simply doesn't perform its required action.
16322 ##### Example, don't
16324     class Connection {
16325         // ...
16326     public:
16327         ~Connection()   // Don't: very bad destructor
16328         {
16329             if (cannot_disconnect()) throw I_give_up{information};
16330             // ...
16331         }
16332     };
16334 ##### Note
16336 Many have tried to write reliable code violating this rule for examples, such as a network connection that "refuses to close".
16337 To the best of our knowledge nobody has found a general way of doing this.
16338 Occasionally, for very specific examples, you can get away with setting some state for future cleanup.
16339 For example, we might put a socket that does not want to close on a "bad socket" list,
16340 to be examined by a regular sweep of the system state.
16341 Every example we have seen of this is error-prone, specialized, and often buggy.
16343 ##### Note
16345 The standard library assumes that destructors, deallocation functions (e.g., `operator delete`), and `swap` do not throw. If they do, basic standard-library invariants are broken.
16347 ##### Note
16349 * Deallocation functions, including `operator delete`, must be `noexcept`.
16350 * `swap` functions must be `noexcept`.
16351 * Most destructors are implicitly `noexcept` by default.
16352 * Also, [make move operations `noexcept`](#Rc-move-noexcept).
16353 * If writing a type intended to be used as an exception type, ensure its copy constructor is not `noexcept`. In general we cannot mechanically enforce this, because we do not know whether a type is intended to be used as an exception type.
16354 * Try not to `throw` a type whose copy constructor is not `noexcept`. In general we cannot mechanically enforce this, because even `throw std::string(...)` could throw but does not in practice.
16356 ##### Enforcement
16358 * Catch destructors, deallocation operations, and `swap`s that `throw`.
16359 * Catch such operations that are not `noexcept`.
16361 **See also**: [discussion](#Sd-never-fail)
16363 ### <a name="Re-not-always"></a>E.17: Don't try to catch every exception in every function
16365 ##### Reason
16367 Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste.
16368 Let an exception propagate until it reaches a function that can handle it.
16369 Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii).
16371 ##### Example, don't
16373     void f()   // bad
16374     {
16375         try {
16376             // ...
16377         }
16378         catch (...) {
16379             // no action
16380             throw;   // propagate exception
16381         }
16382     }
16384 ##### Enforcement
16386 * Flag nested try-blocks.
16387 * Flag source code files with a too high ratio of try-blocks to functions. (??? Problem: define "too high")
16389 ### <a name="Re-catch"></a>E.18: Minimize the use of explicit `try`/`catch`
16391 ##### Reason
16393  `try`/`catch` is verbose and non-trivial uses are error-prone.
16394  `try`/`catch` can be a sign of unsystematic and/or low-level resource management or error handling.
16396 ##### Example, Bad
16398     void f(zstring s)
16399     {
16400         Gadget* p;
16401         try {
16402             p = new Gadget(s);
16403             // ...
16404             delete p;
16405         }
16406         catch (Gadget_construction_failure) {
16407             delete p;
16408             throw;
16409         }
16410     }
16412 This code is messy.
16413 There could be a leak from the naked pointer in the `try` block.
16414 Not all exceptions are handled.
16415 `deleting` an object that failed to construct is almost certainly a mistake.
16416 Better:
16418     void f2(zstring s)
16419     {
16420         Gadget g {s};
16421     }
16423 ##### Alternatives
16425 * proper resource handles and [RAII](#Re-raii)
16426 * [`finally`](#Re-finally)
16428 ##### Enforcement
16430 ??? hard, needs a heuristic
16432 ### <a name="Re-finally"></a>E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available
16434 ##### Reason
16436 `finally` from the [GSL](#gsl-guidelines-support-library) is less verbose and harder to get wrong than `try`/`catch`.
16438 ##### Example
16440     void f(int n)
16441     {
16442         void* p = malloc(n);
16443         auto _ = gsl::finally([p] { free(p); });
16444         // ...
16445     }
16447 ##### Note
16449 `finally` is not as messy as `try`/`catch`, but it is still ad-hoc.
16450 Prefer [proper resource management objects](#Re-raii).
16451 Consider `finally` a last resort.
16453 ##### Note
16455 Use of `finally` is a systematic and reasonably clean alternative to the old [`goto exit;` technique](#Re-no-throw-codes)
16456 for dealing with cleanup where resource management is not systematic.
16458 ##### Enforcement
16460 Heuristic: Detect `goto exit;`
16462 ### <a name="Re-no-throw-raii"></a>E.25: If you can't throw exceptions, simulate RAII for resource management
16464 ##### Reason
16466 Even without exceptions, [RAII](#Re-raii) is usually the best and most systematic way of dealing with resources.
16468 ##### Note
16470 Error handling using exceptions is the only complete and systematic way of handling non-local errors in C++.
16471 In particular, non-intrusively signaling failure to construct an object requires an exception.
16472 Signaling errors in a way that cannot be ignored requires exceptions.
16473 If you can't use exceptions, simulate their use as best you can.
16475 A lot of fear of exceptions is misguided.
16476 When used for exceptional circumstances in code that is not littered with pointers and complicated control structures,
16477 exception handling is almost always affordable (in time and space) and almost always leads to better code.
16478 This, of course, assumes a good implementation of the exception handling mechanisms, which is not available on all systems.
16479 There are also cases where the problems above do not apply, but exceptions cannot be used for other reasons.
16480 Some hard-real-time systems are an example: An operation has to be completed within a fixed time with an error or a correct answer.
16481 In the absence of appropriate time estimation tools, this is hard to guarantee for exceptions.
16482 Such systems (e.g. flight control software) typically also ban the use of dynamic (heap) memory.
16484 So, the primary guideline for error handling is "use exceptions and [RAII](#Re-raii)."
16485 This section deals with the cases where you either do not have an efficient implementation of exceptions,
16486 or have such a rat's nest of old-style code
16487 (e.g., lots of pointers, ill-defined ownership, and lots of unsystematic error handling based on tests of error codes)
16488 that it is infeasible to introduce simple and systematic exception handling.
16490 Before condemning exceptions or complaining too much about their cost, consider examples of the use of [error codes](#Re-no-throw-codes).
16491 Consider the cost and complexity of the use of error codes.
16492 If performance is your worry, measure.
16494 ##### Example
16496 Assume you wanted to write
16498     void func(zstring arg)
16499     {
16500         Gadget g {arg};
16501         // ...
16502     }
16504 If the `gadget` isn't correctly constructed, `func` exits with an exception.
16505 If we cannot throw an exception, we can simulate this RAII style of resource handling by adding a `valid()` member function to `Gadget`:
16507     error_indicator func(zstring arg)
16508     {
16509         Gadget g {arg};
16510         if (!g.valid()) return gadget_construction_error;
16511         // ...
16512         return 0;   // zero indicates "good"
16513     }
16515 The problem is of course that the caller now has to remember to test the return value. To encourage doing so, consider adding a `[[nodiscard]]`.
16517 **See also**: [Discussion](#Sd-???)
16519 ##### Enforcement
16521 Possible (only) for specific versions of this idea: e.g., test for systematic test of `valid()` after resource handle construction
16523 ### <a name="Re-no-throw-crash"></a>E.26: If you can't throw exceptions, consider failing fast
16525 ##### Reason
16527 If you can't do a good job at recovering, at least you can get out before too much consequential damage is done.
16529 **See also**: [Simulating RAII](#Re-no-throw-raii)
16531 ##### Note
16533 If you cannot be systematic about error handling, consider "crashing" as a response to any error that cannot be handled locally.
16534 That is, if you cannot recover from an error in the context of the function that detected it, call `abort()`, `quick_exit()`,
16535 or a similar function that will trigger some sort of system restart.
16537 In systems where you have lots of processes and/or lots of computers, you need to expect and handle fatal crashes anyway,
16538 say from hardware failures.
16539 In such cases, "crashing" is simply leaving error handling to the next level of the system.
16541 ##### Example
16543     void f(int n)
16544     {
16545         // ...
16546         p = static_cast<X*>(malloc(n * sizeof(X)));
16547         if (!p) abort();     // abort if memory is exhausted
16548         // ...
16549     }
16551 Most programs cannot handle memory exhaustion gracefully anyway. This is roughly equivalent to
16553     void f(int n)
16554     {
16555         // ...
16556         p = new X[n];    // throw if memory is exhausted (by default, terminate)
16557         // ...
16558     }
16560 Typically, it is a good idea to log the reason for the "crash" before exiting.
16562 ##### Enforcement
16564 Awkward
16566 ### <a name="Re-no-throw-codes"></a>E.27: If you can't throw exceptions, use error codes systematically
16568 ##### Reason
16570 Systematic use of any error-handling strategy minimizes the chance of forgetting to handle an error.
16572 **See also**: [Simulating RAII](#Re-no-throw-raii)
16574 ##### Note
16576 There are several issues to be addressed:
16578 * How do you transmit an error indicator from out of a function?
16579 * How do you release all resources from a function before doing an error exit?
16580 * What do you use as an error indicator?
16582 In general, returning an error indicator implies returning two values: The result and an error indicator.
16583 The error indicator can be part of the object, e.g. an object can have a `valid()` indicator
16584 or a pair of values can be returned.
16586 ##### Example
16588     Gadget make_gadget(int n)
16589     {
16590         // ...
16591     }
16593     void user()
16594     {
16595         Gadget g = make_gadget(17);
16596         if (!g.valid()) {
16597                 // error handling
16598         }
16599         // ...
16600     }
16602 This approach fits with [simulated RAII resource management](#Re-no-throw-raii).
16603 The `valid()` function could return an `error_indicator` (e.g. a member of an `error_indicator` enumeration).
16605 ##### Example
16607 What if we cannot or do not want to modify the `Gadget` type?
16608 In that case, we must return a pair of values.
16609 For example:
16611     std::pair<Gadget, error_indicator> make_gadget(int n)
16612     {
16613         // ...
16614     }
16616     void user()
16617     {
16618         auto r = make_gadget(17);
16619         if (!r.second) {
16620                 // error handling
16621         }
16622         Gadget& g = r.first;
16623         // ...
16624     }
16626 As shown, `std::pair` is a possible return type.
16627 Some people prefer a specific type.
16628 For example:
16630     Gval make_gadget(int n)
16631     {
16632         // ...
16633     }
16635     void user()
16636     {
16637         auto r = make_gadget(17);
16638         if (!r.err) {
16639                 // error handling
16640         }
16641         Gadget& g = r.val;
16642         // ...
16643     }
16645 One reason to prefer a specific return type is to have names for its members, rather than the somewhat cryptic `first` and `second`
16646 and to avoid confusion with other uses of `std::pair`.
16648 ##### Example
16650 In general, you must clean up before an error exit.
16651 This can be messy:
16653     std::pair<int, error_indicator> user()
16654     {
16655         Gadget g1 = make_gadget(17);
16656         if (!g1.valid()) {
16657             return {0, g1_error};
16658         }
16660         Gadget g2 = make_gadget(31);
16661         if (!g2.valid()) {
16662             cleanup(g1);
16663             return {0, g2_error};
16664         }
16666         // ...
16668         if (all_foobar(g1, g2)) {
16669             cleanup(g2);
16670             cleanup(g1);
16671             return {0, foobar_error};
16672         }
16674         // ...
16676         cleanup(g2);
16677         cleanup(g1);
16678         return {res, 0};
16679     }
16681 Simulating RAII can be non-trivial, especially in functions with multiple resources and multiple possible errors.
16682 A not uncommon technique is to gather cleanup at the end of the function to avoid repetition (note that the extra scope around `g2` is undesirable but necessary to make the `goto` version compile):
16684     std::pair<int, error_indicator> user()
16685     {
16686         error_indicator err = 0;
16687         int res = 0;
16689         Gadget g1 = make_gadget(17);
16690         if (!g1.valid()) {
16691             err = g1_error;
16692             goto g1_exit;
16693         }
16695         {
16696             Gadget g2 = make_gadget(31);
16697             if (!g2.valid()) {
16698                 err = g2_error;
16699                 goto g2_exit;
16700             }
16702             if (all_foobar(g1, g2)) {
16703                 err = foobar_error;
16704                 goto g2_exit;
16705             }
16707             // ...
16709         g2_exit:
16710             if (g2.valid()) cleanup(g2);
16711         }
16713     g1_exit:
16714         if (g1.valid()) cleanup(g1);
16715         return {res, err};
16716     }
16718 The larger the function, the more tempting this technique becomes.
16719 `finally` can [ease the pain a bit](#Re-finally).
16720 Also, the larger the program becomes the harder it is to apply an error-indicator-based error-handling strategy systematically.
16722 We [prefer exception-based error handling](#Re-throw) and recommend [keeping functions short](#Rf-single).
16724 **See also**: [Discussion](#Sd-???)
16726 **See also**: [Returning multiple values](#Rf-out-multi)
16728 ##### Enforcement
16730 Awkward.
16732 ### <a name="Re-no-throw"></a>E.28: Avoid error handling based on global state (e.g. `errno`)
16734 ##### Reason
16736 Global state is hard to manage and it is easy to forget to check it.
16737 When did you last test the return value of `printf()`?
16739 **See also**: [Simulating RAII](#Re-no-throw-raii)
16741 ##### Example, bad
16743     int last_err;
16745     void f(int n)
16746     {
16747         // ...
16748         p = static_cast<X*>(malloc(n * sizeof(X)));
16749         if (!p) last_err = -1;     // error if memory is exhausted
16750         // ...
16751     }
16753 ##### Note
16755 C-style error handling is based on the global variable `errno`, so it is essentially impossible to avoid this style completely.
16757 ##### Enforcement
16759 Awkward.
16762 ### <a name="Re-specifications"></a>E.30: Don't use exception specifications
16764 ##### Reason
16766 Exception specifications make error handling brittle, impose a run-time cost, and have been removed from the C++ standard.
16768 ##### Example
16770     int use(int arg)
16771         throw(X, Y)
16772     {
16773         // ...
16774         auto x = f(arg);
16775         // ...
16776     }
16778 If `f()` throws an exception different from `X` and `Y` the unexpected handler is invoked, which by default terminates.
16779 That's OK, but say that we have checked that this cannot happen and `f` is changed to throw a new exception `Z`,
16780 we now have a crash on our hands unless we change `use()` (and re-test everything).
16781 The snag is that `f()` might be in a library we do not control and the new exception is not anything that `use()` can do
16782 anything about or is in any way interested in.
16783 We can change `use()` to pass `Z` through, but now `use()`'s callers probably need to be modified.
16784 This quickly becomes unmanageable.
16785 Alternatively, we can add a `try`-`catch` to `use()` to map `Z` into an acceptable exception.
16786 This too, quickly becomes unmanageable.
16787 Note that changes to the set of exceptions often happens at the lowest level of a system
16788 (e.g., because of changes to a network library or some middleware), so changes "bubble up" through long call chains.
16789 In a large code base, this could mean that nobody could update to a new version of a library until the last user was modified.
16790 If `use()` is part of a library, it might not be possible to update it because a change could affect unknown clients.
16792 The policy of letting exceptions propagate until they reach a function that potentially can handle it has proven itself over the years.
16794 ##### Note
16796 No. This would not be any better had exception specifications been statically enforced.
16797 For example, see [Stroustrup94](#Stroustrup94).
16799 ##### Note
16801 If no exception can be thrown, use [`noexcept`](#Re-noexcept).
16803 ##### Enforcement
16805 Flag every exception specification.
16807 ### <a name="Re_catch"></a>E.31: Properly order your `catch`-clauses
16809 ##### Reason
16811 `catch`-clauses are evaluated in the order they appear and one clause can hide another.
16813 ##### Example, bad
16815     void f()
16816     {
16817         // ...
16818         try {
16819                 // ...
16820         }
16821         catch (Base& b) { /* ... */ }
16822         catch (Derived& d) { /* ... */ }
16823         catch (...) { /* ... */ }
16824         catch (std::exception& e) { /* ... */ }
16825     }
16827 If `Derived`is derived from `Base` the `Derived`-handler will never be invoked.
16828 The "catch everything" handler ensured that the `std::exception`-handler will never be invoked.
16830 ##### Enforcement
16832 Flag all "hiding handlers".
16834 # <a name="S-const"></a>Con: Constants and immutability
16836 You can't have a race condition on a constant.
16837 It is easier to reason about a program when many of the objects cannot change their values.
16838 Interfaces that promise "no change" of objects passed as arguments greatly increase readability.
16840 Constant rule summary:
16842 * [Con.1: By default, make objects immutable](#Rconst-immutable)
16843 * [Con.2: By default, make member functions `const`](#Rconst-fct)
16844 * [Con.3: By default, pass pointers and references to `const`s](#Rconst-ref)
16845 * [Con.4: Use `const` to define objects with values that do not change after construction](#Rconst-const)
16846 * [Con.5: Use `constexpr` for values that can be computed at compile time](#Rconst-constexpr)
16848 ### <a name="Rconst-immutable"></a>Con.1: By default, make objects immutable
16850 ##### Reason
16852 Immutable objects are easier to reason about, so make objects non-`const` only when there is a need to change their value.
16853 Prevents accidental or hard-to-notice change of value.
16855 ##### Example
16857     for (const int i : c) cout << i << '\n';    // just reading: const
16859     for (int i : c) cout << i << '\n';          // BAD: just reading
16861 ##### Exceptions
16863 A local variable that is returned by value and is cheaper to move than copy should not be declared `const`
16864 because it can force an unnecessary copy.
16866     std::vector<int> f(int i)
16867     {
16868         std::vector<int> v{ i, i, i };  // const not needed
16869         return v;
16870     }
16872 Function parameters passed by value are rarely mutated, but also rarely declared `const`.
16873 To avoid confusion and lots of false positives, don't enforce this rule for function parameters.
16875     void g(const int i) { ... }  // pedantic
16877 Note that a function parameter is a local variable so changes to it are local.
16879 ##### Enforcement
16881 * Flag non-`const` variables that are not modified (except for parameters to avoid many false positives
16882 and returned local variables)
16884 ### <a name="Rconst-fct"></a>Con.2: By default, make member functions `const`
16886 ##### Reason
16888 A member function should be marked `const` unless it changes the object's observable state.
16889 This gives a more precise statement of design intent, better readability, more errors caught by the compiler, and sometimes more optimization opportunities.
16891 ##### Example, bad
16893     class Point {
16894         int x, y;
16895     public:
16896         int getx() { return x; }    // BAD, should be const as it doesn't modify the object's state
16897         // ...
16898     };
16900     void f(const Point& pt)
16901     {
16902         int x = pt.getx();          // ERROR, doesn't compile because getx was not marked const
16903     }
16905 ##### Note
16907 It is not inherently bad to pass a pointer or reference to non-`const`,
16908 but that should be done only when the called function is supposed to modify the object.
16909 A reader of code must assume that a function that takes a "plain" `T*` or `T&` will modify the object referred to.
16910 If it doesn't now, it might do so later without forcing recompilation.
16912 ##### Note
16914 There are code/libraries that offer functions that declare a `T*` even though
16915 those functions do not modify that `T`.
16916 This is a problem for people modernizing code.
16917 You can
16919 * update the library to be `const`-correct; preferred long-term solution
16920 * "cast away `const`"; [best avoided](#Res-casts-const)
16921 * provide a wrapper function
16923 Example:
16925     void f(int* p);   // old code: f() does not modify `*p`
16926     void f(const int* p) { f(const_cast<int*>(p)); } // wrapper
16928 Note that this wrapper solution is a patch that should be used only when the declaration of `f()` cannot be modified,
16929 e.g. because it is in a library that you cannot modify.
16931 ##### Note
16933 A `const` member function can modify the value of an object that is `mutable` or accessed through a pointer member.
16934 A common use is to maintain a cache rather than repeatedly do a complicated computation.
16935 For example, here is a `Date` that caches (memoizes) its string representation to simplify repeated uses:
16937     class Date {
16938     public:
16939         // ...
16940         const string& string_ref() const
16941         {
16942             if (string_val == "") compute_string_rep();
16943             return string_val;
16944         }
16945         // ...
16946     private:
16947         void compute_string_rep() const;    // compute string representation and place it in string_val
16948         mutable string string_val;
16949         // ...
16950     };
16952 Another way of saying this is that `const`ness is not transitive.
16953 It is possible for a `const` member function to change the value of `mutable` members and the value of objects accessed
16954 through non-`const` pointers.
16955 It is the job of the class to ensure such mutation is done only when it makes sense according to the semantics (invariants)
16956 it offers to its users.
16958 **See also**: [Pimpl](#Ri-pimpl)
16960 ##### Enforcement
16962 * Flag a member function that is not marked `const`, but that does not perform a non-`const` operation on any member variable.
16964 ### <a name="Rconst-ref"></a>Con.3: By default, pass pointers and references to `const`s
16966 ##### Reason
16968  To avoid a called function unexpectedly changing the value.
16969  It's far easier to reason about programs when called functions don't modify state.
16971 ##### Example
16973     void f(char* p);        // does f modify *p? (assume it does)
16974     void g(const char* p);  // g does not modify *p
16976 ##### Note
16978 It is not inherently bad to pass a pointer or reference to non-`const`,
16979 but that should be done only when the called function is supposed to modify the object.
16981 ##### Note
16983 [Do not cast away `const`](#Res-casts-const).
16985 ##### Enforcement
16987 * Flag a function that does not modify an object passed by pointer or reference to non-`const`
16988 * Flag a function that (using a cast) modifies an object passed by pointer or reference to `const`
16990 ### <a name="Rconst-const"></a>Con.4: Use `const` to define objects with values that do not change after construction
16992 ##### Reason
16994  Prevent surprises from unexpectedly changed object values.
16996 ##### Example
16998     void f()
16999     {
17000         int x = 7;
17001         const int y = 9;
17003         for (;;) {
17004             // ...
17005         }
17006         // ...
17007     }
17009 As `x` is not `const`, we must assume that it is modified somewhere in the loop.
17011 ##### Enforcement
17013 * Flag unmodified non-`const` variables.
17015 ### <a name="Rconst-constexpr"></a>Con.5: Use `constexpr` for values that can be computed at compile time
17017 ##### Reason
17019 Better performance, better compile-time checking, guaranteed compile-time evaluation, no possibility of race conditions.
17021 ##### Example
17023     double x = f(2);            // possible run-time evaluation
17024     const double y = f(2);      // possible run-time evaluation
17025     constexpr double z = f(2);  // error unless f(2) can be evaluated at compile time
17027 ##### Note
17029 See F.4.
17031 ##### Enforcement
17033 * Flag `const` definitions with constant expression initializers.
17035 # <a name="S-templates"></a>T: Templates and generic programming
17037 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
17038 In C++, generic programming is supported by the `template` language mechanisms.
17040 Arguments to generic functions are characterized by sets of requirements on the argument types and values involved.
17041 In C++, these requirements are expressed by compile-time predicates called concepts.
17043 Templates can also be used for meta-programming; that is, programs that compose code at compile time.
17045 A central notion in generic programming is "concepts"; that is, requirements on template arguments presented as compile-time predicates.
17046 "Concepts" were standardized in C++20, although they were first made available, in slightly older syntax, in GCC 6.1.
17048 Template use rule summary:
17050 * [T.1: Use templates to raise the level of abstraction of code](#Rt-raise)
17051 * [T.2: Use templates to express algorithms that apply to many argument types](#Rt-algo)
17052 * [T.3: Use templates to express containers and ranges](#Rt-cont)
17053 * [T.4: Use templates to express syntax tree manipulation](#Rt-expr)
17054 * [T.5: Combine generic and OO techniques to amplify their strengths, not their costs](#Rt-generic-oo)
17056 Concept use rule summary:
17058 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
17059 * [T.11: Whenever possible use standard concepts](#Rt-std-concepts)
17060 * [T.12: Prefer concept names over `auto` for local variables](#Rt-auto)
17061 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
17062 * ???
17064 Concept definition rule summary:
17066 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
17067 * [T.21: Require a complete set of operations for a concept](#Rt-complete)
17068 * [T.22: Specify axioms for concepts](#Rt-axiom)
17069 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
17070 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
17071 * [T.25: Avoid complementary constraints](#Rt-not)
17072 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
17073 * [T.30: Use concept negation (`!C<T>`) sparingly to express a minor difference](#Rt-???)
17074 * [T.31: Use concept disjunction (`C1<T> || C2<T>`) sparingly to express alternatives](#Rt-???)
17075 * ???
17077 Template interface rule summary:
17079 * [T.40: Use function objects to pass operations to algorithms](#Rt-fo)
17080 * [T.41: Require only essential properties in a template's concepts](#Rt-essential)
17081 * [T.42: Use template aliases to simplify notation and hide implementation details](#Rt-alias)
17082 * [T.43: Prefer `using` over `typedef` for defining aliases](#Rt-using)
17083 * [T.44: Use function templates to deduce class template argument types (where feasible)](#Rt-deduce)
17084 * [T.46: Require template arguments to be at least semiregular](#Rt-regular)
17085 * [T.47: Avoid highly visible unconstrained templates with common names](#Rt-visible)
17086 * [T.48: If your compiler does not support concepts, fake them with `enable_if`](#Rt-concept-def)
17087 * [T.49: Where possible, avoid type-erasure](#Rt-erasure)
17089 Template definition rule summary:
17091 * [T.60: Minimize a template's context dependencies](#Rt-depend)
17092 * [T.61: Do not over-parameterize members (SCARY)](#Rt-scary)
17093 * [T.62: Place non-dependent class template members in a non-templated base class](#Rt-nondependent)
17094 * [T.64: Use specialization to provide alternative implementations of class templates](#Rt-specialization)
17095 * [T.65: Use tag dispatch to provide alternative implementations of functions](#Rt-tag-dispatch)
17096 * [T.67: Use specialization to provide alternative implementations for irregular types](#Rt-specialization2)
17097 * [T.68: Use `{}` rather than `()` within templates to avoid ambiguities](#Rt-cast)
17098 * [T.69: Inside a template, don't make an unqualified non-member function call unless you intend it to be a customization point](#Rt-customization)
17100 Template and hierarchy rule summary:
17102 * [T.80: Do not naively templatize a class hierarchy](#Rt-hier)
17103 * [T.81: Do not mix hierarchies and arrays](#Rt-array) // ??? somewhere in "hierarchies"
17104 * [T.82: Linearize a hierarchy when virtual functions are undesirable](#Rt-linear)
17105 * [T.83: Do not declare a member function template virtual](#Rt-virtual)
17106 * [T.84: Use a non-template core implementation to provide an ABI-stable interface](#Rt-abi)
17107 * [T.??: ????](#Rt-???)
17109 Variadic template rule summary:
17111 * [T.100: Use variadic templates when you need a function that takes a variable number of arguments of a variety of types](#Rt-variadic)
17112 * [T.101: ??? How to pass arguments to a variadic template ???](#Rt-variadic-pass)
17113 * [T.102: ??? How to process arguments to a variadic template ???](#Rt-variadic-process)
17114 * [T.103: Don't use variadic templates for homogeneous argument lists](#Rt-variadic-not)
17115 * [T.??: ????](#Rt-???)
17117 Metaprogramming rule summary:
17119 * [T.120: Use template metaprogramming only when you really need to](#Rt-metameta)
17120 * [T.121: Use template metaprogramming primarily to emulate concepts](#Rt-emulate)
17121 * [T.122: Use templates (usually template aliases) to compute types at compile time](#Rt-tmp)
17122 * [T.123: Use `constexpr` functions to compute values at compile time](#Rt-fct)
17123 * [T.124: Prefer to use standard-library TMP facilities](#Rt-std-tmp)
17124 * [T.125: If you need to go beyond the standard-library TMP facilities, use an existing library](#Rt-lib)
17125 * [T.??: ????](#Rt-???)
17127 Other template rules summary:
17129 * [T.140: If an operation can be reused, give it a name](#Rt-name)
17130 * [T.141: Use an unnamed lambda if you need a simple function object in one place only](#Rt-lambda)
17131 * [T.142: Use template variables to simplify notation](#Rt-var)
17132 * [T.143: Don't write unintentionally non-generic code](#Rt-non-generic)
17133 * [T.144: Don't specialize function templates](#Rt-specialize-function)
17134 * [T.150: Check that a class matches a concept using `static_assert`](#Rt-check-class)
17135 * [T.??: ????](#Rt-???)
17137 ## <a name="SS-GP"></a>T.gp: Generic programming
17139 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
17141 ### <a name="Rt-raise"></a>T.1: Use templates to raise the level of abstraction of code
17143 ##### Reason
17145 Generality. Reuse. Efficiency. Encourages consistent definition of user types.
17147 ##### Example, bad
17149 Conceptually, the following requirements are wrong because what we want of `T` is more than just the very low-level concepts of "can be incremented" or "can be added":
17151     template<typename T>
17152         requires Incrementable<T>
17153     T sum1(vector<T>& v, T s)
17154     {
17155         for (auto x : v) s += x;
17156         return s;
17157     }
17159     template<typename T>
17160         requires Simple_number<T>
17161     T sum2(vector<T>& v, T s)
17162     {
17163         for (auto x : v) s = s + x;
17164         return s;
17165     }
17167 Assuming that `Incrementable` does not support `+` and `Simple_number` does not support `+=`, we have overconstrained implementers of `sum1` and `sum2`.
17168 And, in this case, missed an opportunity for a generalization.
17170 ##### Example
17172     template<typename T>
17173         requires Arithmetic<T>
17174     T sum(vector<T>& v, T s)
17175     {
17176         for (auto x : v) s += x;
17177         return s;
17178     }
17180 Assuming that `Arithmetic` requires both `+` and `+=`, we have constrained the user of `sum` to provide a complete arithmetic type.
17181 That is not a minimal requirement, but it gives the implementer of algorithms much needed freedom and ensures that any `Arithmetic` type
17182 can be used for a wide variety of algorithms.
17184 For additional generality and reusability, we could also use a more general `Container` or `Range` concept instead of committing to only one container, `vector`.
17186 ##### Note
17188 If we define a template to require exactly the operations required for a single implementation of a single algorithm
17189 (e.g., requiring just `+=` rather than also `=` and `+`) and only those, we have overconstrained maintainers.
17190 We aim to minimize requirements on template arguments, but the absolutely minimal requirements of an implementation is rarely a meaningful concept.
17192 ##### Note
17194 Templates can be used to express essentially everything (they are Turing complete), but the aim of generic programming (as expressed using templates)
17195 is to efficiently generalize operations/algorithms over a set of types with similar semantic properties.
17197 ##### Enforcement
17199 * Flag algorithms with "overly simple" requirements, such as direct use of specific operators without a concept.
17200 * Do not flag the definition of the "overly simple" concepts themselves; they might simply be building blocks for more useful concepts.
17202 ### <a name="Rt-algo"></a>T.2: Use templates to express algorithms that apply to many argument types
17204 ##### Reason
17206 Generality. Minimizing the amount of source code. Interoperability. Reuse.
17208 ##### Example
17210 That's the foundation of the STL. A single `find` algorithm easily works with any kind of input range:
17212     template<typename Iter, typename Val>
17213         // requires Input_iterator<Iter>
17214         //       && Equality_comparable<Value_type<Iter>, Val>
17215     Iter find(Iter b, Iter e, Val v)
17216     {
17217         // ...
17218     }
17220 ##### Note
17222 Don't use a template unless you have a realistic need for more than one template argument type.
17223 Don't overabstract.
17225 ##### Enforcement
17227 ??? tough, probably needs a human
17229 ### <a name="Rt-cont"></a>T.3: Use templates to express containers and ranges
17231 ##### Reason
17233 Containers need an element type, and expressing that as a template argument is general, reusable, and type safe.
17234 It also avoids brittle or inefficient workarounds. Convention: That's the way the STL does it.
17236 ##### Example
17238     template<typename T>
17239         // requires Regular<T>
17240     class Vector {
17241         // ...
17242         T* elem;   // points to sz Ts
17243         int sz;
17244     };
17246     Vector<double> v(10);
17247     v[7] = 9.9;
17249 ##### Example, bad
17251     class Container {
17252         // ...
17253         void* elem;   // points to size elements of some type
17254         int sz;
17255     };
17257     Container c(10, sizeof(double));
17258     ((double*) c.elem)[7] = 9.9;
17260 This doesn't directly express the intent of the programmer and hides the structure of the program from the type system and optimizer.
17262 Hiding the `void*` behind macros simply obscures the problems and introduces new opportunities for confusion.
17264 **Exceptions**: If you need an ABI-stable interface, you might have to provide a base implementation and express the (type-safe) template in terms of that.
17265 See [Stable base](#Rt-abi).
17267 ##### Enforcement
17269 * Flag uses of `void*`s and casts outside low-level implementation code
17271 ### <a name="Rt-expr"></a>T.4: Use templates to express syntax tree manipulation
17273 ##### Reason
17275  ???
17277 ##### Example
17279     ???
17281 **Exceptions**: ???
17283 ### <a name="Rt-generic-oo"></a>T.5: Combine generic and OO techniques to amplify their strengths, not their costs
17285 ##### Reason
17287 Generic and OO techniques are complementary.
17289 ##### Example
17291 Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces.
17293     class Command {
17294         // pure virtual functions
17295     };
17297     // implementations
17298     template</*...*/>
17299     class ConcreteCommand : public Command {
17300         // implement virtuals
17301     };
17303 ##### Example
17305 Dynamic helps static: Offer a generic, comfortable, statically bound interface, but internally dispatch dynamically, so you offer a uniform object layout.
17306 Examples include type erasure as with `std::shared_ptr`'s deleter (but [don't overuse type erasure](#Rt-erasure)).
17308     #include <memory>
17310     class Object {
17311     public:
17312         template<typename T>
17313         Object(T&& obj)
17314             : concept_(std::make_shared<ConcreteCommand<T>>(std::forward<T>(obj))) {}
17316         int get_id() const { return concept_->get_id(); }
17318     private:
17319         struct Command {
17320             virtual ~Command() {}
17321             virtual int get_id() const = 0;
17322         };
17324         template<typename T>
17325         struct ConcreteCommand final : Command {
17326             ConcreteCommand(T&& obj) noexcept : object_(std::forward<T>(obj)) {}
17327             int get_id() const final { return object_.get_id(); }
17329         private:
17330             T object_;
17331         };
17333         std::shared_ptr<Command> concept_;
17334     };
17336     class Bar {
17337     public:
17338         int get_id() const { return 1; }
17339     };
17341     struct Foo {
17342     public:
17343         int get_id() const { return 2; }
17344     };
17346     Object o(Bar{});
17347     Object o2(Foo{});
17349 ##### Note
17351 In a class template, non-virtual functions are only instantiated if they're used -- but virtual functions are instantiated every time.
17352 This can bloat code size, and might overconstrain a generic type by instantiating functionality that is never needed.
17353 Avoid this, even though the standard-library facets made this mistake.
17355 ##### See also
17357 * ref ???
17358 * ref ???
17359 * ref ???
17361 ##### Enforcement
17363 See the reference to more specific rules.
17365 ## <a name="SS-concepts"></a>T.concepts: Concept rules
17367 Concepts is a C++20 facility for specifying requirements for template arguments.
17368 They are crucial in the thinking about generic programming and the basis of much work on future C++ libraries
17369 (standard and other).
17371 This section assumes concept support
17373 Concept use rule summary:
17375 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
17376 * [T.11: Whenever possible use standard concepts](#Rt-std-concepts)
17377 * [T.12: Prefer concept names over `auto`](#Rt-auto)
17378 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
17379 * ???
17381 Concept definition rule summary:
17383 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
17384 * [T.21: Require a complete set of operations for a concept](#Rt-complete)
17385 * [T.22: Specify axioms for concepts](#Rt-axiom)
17386 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
17387 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
17388 * [T.25: Avoid complimentary constraints](#Rt-not)
17389 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
17390 * ???
17392 ## <a name="SS-concept-use"></a>T.con-use: Concept use
17394 ### <a name="Rt-concepts"></a>T.10: Specify concepts for all template arguments
17396 ##### Reason
17398 Correctness and readability.
17399 The assumed meaning (syntax and semantics) of a template argument is fundamental to the interface of a template.
17400 A concept dramatically improves documentation and error handling for the template.
17401 Specifying concepts for template arguments is a powerful design tool.
17403 ##### Example
17405     template<typename Iter, typename Val>
17406         requires input_iterator<Iter>
17407                  && equality_comparable_with<iter_value_t<Iter>, Val>
17408     Iter find(Iter b, Iter e, Val v)
17409     {
17410         // ...
17411     }
17413 or equivalently and more succinctly:
17415     template<input_iterator Iter, typename Val>
17416         requires equality_comparable_with<iter_value_t<Iter>, Val>
17417     Iter find(Iter b, Iter e, Val v)
17418     {
17419         // ...
17420     }
17422 ##### Note
17424 Plain `typename` (or `auto`) is the least constraining concept.
17425 It should be used only rarely when nothing more than "it's a type" can be assumed.
17426 This is typically only needed when (as part of template metaprogramming code) we manipulate pure expression trees, postponing type checking.
17428 **References**: TC++PL4
17430 ##### Enforcement
17432 Flag template type arguments without concepts
17434 ### <a name="Rt-std-concepts"></a>T.11: Whenever possible use standard concepts
17436 ##### Reason
17438  "Standard" concepts (as provided by the [GSL](#gsl-guidelines-support-library) and the ISO standard itself)
17439 save us the work of thinking up our own concepts, are better thought out than we can manage to do in a hurry, and improve interoperability.
17441 ##### Note
17443 Unless you are creating a new generic library, most of the concepts you need will already be defined by the standard library.
17445 ##### Example
17447     template<typename T>
17448         // don't define this: sortable is in <iterator>
17449     concept Ordered_container = Sequence<T> && Random_access<Iterator<T>> && Ordered<Value_type<T>>;
17451     void sort(Ordered_container auto& s);
17453 This `Ordered_container` is quite plausible, but it is very similar to the `sortable` concept in the standard library.
17454 Is it better? Is it right? Does it accurately reflect the standard's requirements for `sort`?
17455 It is better and simpler just to use `sortable`:
17457     void sort(sortable auto& s);   // better
17459 ##### Note
17461 The set of "standard" concepts is evolving as we approach an ISO standard including concepts.
17463 ##### Note
17465 Designing a useful concept is challenging.
17467 ##### Enforcement
17469 Hard.
17471 * Look for unconstrained arguments, templates that use "unusual"/non-standard concepts, templates that use "homebrew" concepts without axioms.
17472 * Develop a concept-discovery tool (e.g., see [an early experiment](http://www.stroustrup.com/sle2010_webversion.pdf)).
17474 ### <a name="Rt-auto"></a>T.12: Prefer concept names over `auto` for local variables
17476 ##### Reason
17478  `auto` is the weakest concept. Concept names convey more meaning than just `auto`.
17480 ##### Example
17482     vector<string> v{ "abc", "xyz" };
17483     auto& x = v.front();        // bad
17484     String auto& s = v.front(); // good (String is a GSL concept)
17486 ##### Enforcement
17488 * ???
17490 ### <a name="Rt-shorthand"></a>T.13: Prefer the shorthand notation for simple, single-type argument concepts
17492 ##### Reason
17494 Readability. Direct expression of an idea.
17496 ##### Example
17498 To say "`T` is `sortable`":
17500     template<typename T>       // Correct but verbose: "The parameter is
17501         requires sortable<T>   // of type T which is the name of a type
17502     void sort(T&);             // that is sortable"
17504     template<sortable T>       // Better: "The parameter is of type T
17505     void sort(T&);             // which is Sortable"
17507     void sort(sortable auto&); // Best: "The parameter is Sortable"
17509 The shorter versions better match the way we speak. Note that many templates don't need to use the `template` keyword.
17511 ##### Enforcement
17513 * Not feasible in the short term when people convert from the `<typename T>` and `<class T`> notation.
17514 * Later, flag declarations that first introduce a typename and then constrain it with a simple, single-type-argument concept.
17516 ## <a name="SS-concepts-def"></a>T.concepts.def: Concept definition rules
17518 Defining good concepts is non-trivial.
17519 Concepts are meant to represent fundamental concepts in an application domain (hence the name "concepts").
17520 Similarly throwing together a set of syntactic constraints to be used for the arguments for a single class or algorithm is not what concepts were designed for
17521 and will not give the full benefits of the mechanism.
17523 Obviously, defining concepts is most useful for code that can use an implementation (e.g., C++20 or later)
17524 but defining concepts is in itself a useful design technique and help catch conceptual errors and clean up the concepts (sic!) of an implementation.
17526 ### <a name="Rt-low"></a>T.20: Avoid "concepts" without meaningful semantics
17528 ##### Reason
17530 Concepts are meant to express semantic notions, such as "a number", "a range" of elements, and "totally ordered."
17531 Simple constraints, such as "has a `+` operator" and "has a `>` operator" cannot be meaningfully specified in isolation
17532 and should be used only as building blocks for meaningful concepts, rather than in user code.
17534 ##### Example, bad
17536     template<typename T>
17537     // bad; insufficient
17538     concept Addable = requires(T a, T b) { a + b; };
17540     template<Addable N>
17541     auto algo(const N& a, const N& b) // use two numbers
17542     {
17543         // ...
17544         return a + b;
17545     }
17547     int x = 7;
17548     int y = 9;
17549     auto z = algo(x, y);   // z = 16
17551     string xx = "7";
17552     string yy = "9";
17553     auto zz = algo(xx, yy);   // zz = "79"
17555 Maybe the concatenation was expected. More likely, it was an accident. Defining minus equivalently would give dramatically different sets of accepted types.
17556 This `Addable` violates the mathematical rule that addition is supposed to be commutative: `a+b == b+a`.
17558 ##### Note
17560 The ability to specify meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint.
17562 ##### Example
17564     template<typename T>
17565     // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
17566     concept Number = requires(T a, T b) { a + b; a - b; a * b; a / b; };
17568     template<Number N>
17569     auto algo(const N& a, const N& b)
17570     {
17571         // ...
17572         return a + b;
17573     }
17575     int x = 7;
17576     int y = 9;
17577     auto z = algo(x, y);   // z = 16
17579     string xx = "7";
17580     string yy = "9";
17581     auto zz = algo(xx, yy);   // error: string is not a Number
17583 ##### Note
17585 Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept.
17587 ##### Enforcement
17589 * Flag single-operation `concepts` when used outside the definition of other `concepts`.
17590 * Flag uses of `enable_if` that appear to simulate single-operation `concepts`.
17593 ### <a name="Rt-complete"></a>T.21: Require a complete set of operations for a concept
17595 ##### Reason
17597 Ease of comprehension.
17598 Improved interoperability.
17599 Helps implementers and maintainers.
17601 ##### Note
17603 This is a specific variant of the general rule that [a concept must make semantic sense](#Rt-low).
17605 ##### Example, bad
17607     template<typename T> concept Subtractable = requires(T a, T b) { a - b; };
17609 This makes no semantic sense.
17610 You need at least `+` to make `-` meaningful and useful.
17612 Examples of complete sets are
17614 * `Arithmetic`: `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`
17615 * `Comparable`: `<`, `>`, `<=`, `>=`, `==`, `!=`
17617 ##### Note
17619 This rule applies whether we use direct language support for concepts or not.
17620 It is a general design rule that even applies to non-templates:
17622     class Minimal {
17623         // ...
17624     };
17626     bool operator==(const Minimal&, const Minimal&);
17627     bool operator<(const Minimal&, const Minimal&);
17629     Minimal operator+(const Minimal&, const Minimal&);
17630     // no other operators
17632     void f(const Minimal& x, const Minimal& y)
17633     {
17634         if (!(x == y)) { /* ... */ }    // OK
17635         if (x != y) { /* ... */ }       // surprise! error
17637         while (!(x < y)) { /* ... */ }  // OK
17638         while (x >= y) { /* ... */ }    // surprise! error
17640         x = x + y;          // OK
17641         x += y;             // surprise! error
17642     }
17644 This is minimal, but surprising and constraining for users.
17645 It could even be less efficient.
17647 The rule supports the view that a concept should reflect a (mathematically) coherent set of operations.
17649 ##### Example
17651     class Convenient {
17652         // ...
17653     };
17655     bool operator==(const Convenient&, const Convenient&);
17656     bool operator<(const Convenient&, const Convenient&);
17657     // ... and the other comparison operators ...
17659     Convenient operator+(const Convenient&, const Convenient&);
17660     // ... and the other arithmetic operators ...
17662     void f(const Convenient& x, const Convenient& y)
17663     {
17664         if (!(x == y)) { /* ... */ }    // OK
17665         if (x != y) { /* ... */ }       // OK
17667         while (!(x < y)) { /* ... */ }  // OK
17668         while (x >= y) { /* ... */ }    // OK
17670         x = x + y;     // OK
17671         x += y;        // OK
17672     }
17674 It can be a nuisance to define all operators, but not hard.
17675 Ideally, that rule should be language supported by giving you comparison operators by default.
17677 ##### Enforcement
17679 * Flag classes that support "odd" subsets of a set of operators, e.g., `==` but not `!=` or `+` but not `-`.
17680   Yes, `std::string` is "odd", but it's too late to change that.
17683 ### <a name="Rt-axiom"></a>T.22: Specify axioms for concepts
17685 ##### Reason
17687 A meaningful/useful concept has a semantic meaning.
17688 Expressing these semantics in an informal, semi-formal, or formal way makes the concept comprehensible to readers and the effort to express it can catch conceptual errors.
17689 Specifying semantics is a powerful design tool.
17691 ##### Example
17693     template<typename T>
17694         // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
17695         // axiom(T a, T b) { a + b == b + a; a - a == 0; a * (b + c) == a * b + a * c; /*...*/ }
17696         concept Number = requires(T a, T b) {
17697             { a + b } -> convertible_to<T>;
17698             { a - b } -> convertible_to<T>;
17699             { a * b } -> convertible_to<T>;
17700             { a / b } -> convertible_to<T>;
17701         };
17703 ##### Note
17705 This is an axiom in the mathematical sense: something that can be assumed without proof.
17706 In general, axioms are not provable, and when they are the proof is often beyond the capability of a compiler.
17707 An axiom might not be general, but the template writer can assume that it holds for all inputs actually used (similar to a precondition).
17709 ##### Note
17711 In this context axioms are Boolean expressions.
17712 See the [Palo Alto TR](#S-references) for examples.
17713 Currently, C++ does not support axioms (even the ISO Concepts TS), so we have to make do with comments for a longish while.
17714 Once language support is available, the `//` in front of the axiom can be removed
17716 ##### Note
17718 The GSL concepts have well-defined semantics; see the Palo Alto TR and the Ranges TS.
17720 ##### Exception
17722 Early versions of a new "concept" still under development will often just define simple sets of constraints without a well-specified semantics.
17723 Finding good semantics can take effort and time.
17724 An incomplete set of constraints can still be very useful:
17726     // balancer for a generic binary tree
17727     template<typename Node> concept Balancer = requires(Node* p) {
17728         add_fixup(p);
17729         touch(p);
17730         detach(p);
17731     };
17733 So a `Balancer` must supply at least these operations on a tree `Node`,
17734 but we are not yet ready to specify detailed semantics because a new kind of balanced tree might require more operations
17735 and the precise general semantics for all nodes is hard to pin down in the early stages of design.
17737 A "concept" that is incomplete or without a well-specified semantics can still be useful.
17738 For example, it allows for some checking during initial experimentation.
17739 However, it should not be assumed to be stable.
17740 Each new use case might require such an incomplete concept to be improved.
17742 ##### Enforcement
17744 * Look for the word "axiom" in concept definition comments
17746 ### <a name="Rt-refine"></a>T.23: Differentiate a refined concept from its more general case by adding new use patterns.
17748 ##### Reason
17750 Otherwise they cannot be distinguished automatically by the compiler.
17752 ##### Example
17754     template<typename I>
17755     // Note: input_iterator is defined in <iterator>
17756     concept Input_iter = requires(I iter) { ++iter; };
17758     template<typename I>
17759     // Note: forward_iterator is defined in <iterator>
17760     concept Fwd_iter = Input_iter<I> && requires(I iter) { iter++; };
17762 The compiler can determine refinement based on the sets of required operations (here, suffix `++`).
17763 This decreases the burden on implementers of these types since
17764 they do not need any special declarations to "hook into the concept".
17765 If two concepts have exactly the same requirements, they are logically equivalent (there is no refinement).
17767 ##### Enforcement
17769 * Flag a concept that has exactly the same requirements as another already-seen concept (neither is more refined).
17770 To disambiguate them, see [T.24](#Rt-tag).
17772 ### <a name="Rt-tag"></a>T.24: Use tag classes or traits to differentiate concepts that differ only in semantics.
17774 ##### Reason
17776 Two concepts requiring the same syntax but having different semantics leads to ambiguity unless the programmer differentiates them.
17778 ##### Example
17780     template<typename I>    // iterator providing random access
17781     // Note: random_access_iterator is defined in <iterator>
17782     concept RA_iter = ...;
17784     template<typename I>    // iterator providing random access to contiguous data
17785     // Note: contiguous_iterator is defined in <iterator>
17786     concept Contiguous_iter =
17787         RA_iter<I> && is_contiguous_v<I>;  // using is_contiguous trait
17789 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
17791 Wrapping a tag class into a concept leads to a simpler expression of this idea:
17793     template<typename I> concept Contiguous = is_contiguous_v<I>;
17795     template<typename I>
17796     concept Contiguous_iter = RA_iter<I> && Contiguous<I>;
17798 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
17800 ##### Note
17802 Traits can be trait classes or type traits.
17803 These can be user-defined or standard-library ones.
17804 Prefer the standard-library ones.
17806 ##### Enforcement
17808 * The compiler flags ambiguous use of identical concepts.
17809 * Flag the definition of identical concepts.
17811 ### <a name="Rt-not"></a>T.25: Avoid complementary constraints
17813 ##### Reason
17815 Clarity. Maintainability.
17816 Functions with complementary requirements expressed using negation are brittle.
17818 ##### Example
17820 Initially, people will try to define functions with complementary requirements:
17822     template<typename T>
17823         requires !C<T>    // bad
17824     void f();
17826     template<typename T>
17827         requires C<T>
17828     void f();
17830 This is better:
17832     template<typename T>   // general template
17833         void f();
17835     template<typename T>   // specialization by concept
17836         requires C<T>
17837     void f();
17839 The compiler will choose the unconstrained template only when `C<T>` is
17840 unsatisfied. If you do not want to (or cannot) define an unconstrained
17841 version of `f()`, then delete it.
17843     template<typename T>
17844     void f() = delete;
17846 The compiler will select the overload, or emit an appropriate error.
17848 ##### Note
17850 Complementary constraints are unfortunately common in `enable_if` code:
17852     template<typename T>
17853     enable_if<!C<T>, void>   // bad
17854     f();
17856     template<typename T>
17857     enable_if<C<T>, void>
17858     f();
17861 ##### Note
17863 Complementary requirements on one requirement is sometimes (wrongly) considered manageable.
17864 However, for two or more requirements the number of definitions needs can go up exponentially (2,4,8,16,...):
17866     C1<T> && C2<T>
17867     !C1<T> && C2<T>
17868     C1<T> && !C2<T>
17869     !C1<T> && !C2<T>
17871 Now the opportunities for errors multiply.
17873 ##### Enforcement
17875 * Flag pairs of functions with `C<T>` and `!C<T>` constraints
17877 ### <a name="Rt-use"></a>T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax
17879 ##### Reason
17881 The definition is more readable and corresponds directly to what a user has to write.
17882 Conversions are taken into account. You don't have to remember the names of all the type traits.
17884 ##### Example
17886 You might be tempted to define a concept `Equality` like this:
17888     template<typename T> concept Equality = has_equal<T> && has_not_equal<T>;
17890 Obviously, it would be better and easier just to use the standard `equality_comparable`,
17891 but - just as an example - if you had to define such a concept, prefer:
17893     template<typename T> concept Equality = requires(T a, T b) {
17894         { a == b } -> std::convertible_to<bool>;
17895         { a != b } -> std::convertible_to<bool>;
17896         // axiom { !(a == b) == (a != b) }
17897         // axiom { a = b; => a == b }  // => means "implies"
17898     };
17900 as opposed to defining two meaningless concepts `has_equal` and `has_not_equal` just as helpers in the definition of `Equality`.
17901 By "meaningless" we mean that we cannot specify the semantics of `has_equal` in isolation.
17903 ##### Enforcement
17907 ## <a name="SS-temp-interface"></a>Template interfaces
17909 Over the years, programming with templates have suffered from a weak distinction between the interface of a template
17910 and its implementation.
17911 Before concepts, that distinction had no direct language support.
17912 However, the interface to a template is a critical concept - a contract between a user and an implementer - and should be carefully designed.
17914 ### <a name="Rt-fo"></a>T.40: Use function objects to pass operations to algorithms
17916 ##### Reason
17918 Function objects can carry more information through an interface than a "plain" pointer to function.
17919 In general, passing function objects gives better performance than passing pointers to functions.
17921 ##### Example
17923     bool greater(double x, double y) { return x > y; }
17924     sort(v, greater);                                    // pointer to function: potentially slow
17925     sort(v, [](double x, double y) { return x > y; });   // function object
17926     sort(v, std::greater{});                             // function object
17928     bool greater_than_7(double x) { return x > 7; }
17929     auto x = find_if(v, greater_than_7);                 // pointer to function: inflexible
17930     auto y = find_if(v, [](double x) { return x > 7; }); // function object: carries the needed data
17931     auto z = find_if(v, Greater_than<double>(7));        // function object: carries the needed data
17933 You can, of course, generalize those functions using `auto` or concepts. For example:
17935     auto y1 = find_if(v, [](totally_ordered auto x) { return x > 7; }); // require an ordered type
17936     auto z1 = find_if(v, [](auto x) { return x > 7; });                 // hope that the type has a >
17938 ##### Note
17940 Lambdas generate function objects.
17942 ##### Note
17944 The performance argument depends on compiler and optimizer technology.
17946 ##### Enforcement
17948 * Flag pointer to function template arguments.
17949 * Flag pointers to functions passed as arguments to a template (risk of false positives).
17952 ### <a name="Rt-essential"></a>T.41: Require only essential properties in a template's concepts
17954 ##### Reason
17956 Keep interfaces simple and stable.
17958 ##### Example
17960 Consider, a `sort` instrumented with (oversimplified) simple debug support:
17962     void sort(sortable auto& s)  // sort sequence s
17963     {
17964         if (debug) cerr << "enter sort( " << s <<  ")\n";
17965         // ...
17966         if (debug) cerr << "exit sort( " << s <<  ")\n";
17967     }
17969 Should this be rewritten to:
17971     template<sortable S>
17972         requires Streamable<S>
17973     void sort(S& s)  // sort sequence s
17974     {
17975         if (debug) cerr << "enter sort( " << s <<  ")\n";
17976         // ...
17977         if (debug) cerr << "exit sort( " << s <<  ")\n";
17978     }
17980 After all, there is nothing in `sortable` that requires `iostream` support.
17981 On the other hand, there is nothing in the fundamental idea of sorting that says anything about debugging.
17983 ##### Note
17985 If we require every operation used to be listed among the requirements, the interface becomes unstable:
17986 Every time we change the debug facilities, the usage data gathering, testing support, error reporting, etc.,
17987 the definition of the template would need change and every use of the template would have to be recompiled.
17988 This is cumbersome, and in some environments infeasible.
17990 Conversely, if we use an operation in the implementation that is not guaranteed by concept checking,
17991 we might get a late compile-time error.
17993 By not using concept checking for properties of a template argument that is not considered essential,
17994 we delay checking until instantiation time.
17995 We consider this a worthwhile tradeoff.
17997 Note that using non-local, non-dependent names (such as `debug` and `cerr`) also introduces context dependencies that might lead to "mysterious" errors.
17999 ##### Note
18001 It can be hard to decide which properties of a type are essential and which are not.
18003 ##### Enforcement
18007 ### <a name="Rt-alias"></a>T.42: Use template aliases to simplify notation and hide implementation details
18009 ##### Reason
18011 Improved readability.
18012 Implementation hiding.
18013 Note that template aliases replace many uses of traits to compute a type.
18014 They can also be used to wrap a trait.
18016 ##### Example
18018     template<typename T, size_t N>
18019     class Matrix {
18020         // ...
18021         using Iterator = typename std::vector<T>::iterator;
18022         // ...
18023     };
18025 This saves the user of `Matrix` from having to know that its elements are stored in a `vector` and also saves the user from repeatedly typing `typename std::vector<T>::`.
18027 ##### Example
18029     template<typename T>
18030     void user(T& c)
18031     {
18032         // ...
18033         typename container_traits<T>::value_type x; // bad, verbose
18034         // ...
18035     }
18037     template<typename T>
18038     using Value_type = typename container_traits<T>::value_type;
18041 This saves the user of `Value_type` from having to know the technique used to implement `value_type`s.
18043     template<typename T>
18044     void user2(T& c)
18045     {
18046         // ...
18047         Value_type<T> x;
18048         // ...
18049     }
18051 ##### Note
18053 A simple, common use could be expressed: "Wrap traits!"
18055 ##### Enforcement
18057 * Flag use of `typename` as a disambiguator outside `using` declarations.
18058 * ???
18060 ### <a name="Rt-using"></a>T.43: Prefer `using` over `typedef` for defining aliases
18062 ##### Reason
18064 Improved readability: With `using`, the new name comes first rather than being embedded somewhere in a declaration.
18065 Generality: `using` can be used for template aliases, whereas `typedef`s can't easily be templates.
18066 Uniformity: `using` is syntactically similar to `auto`.
18068 ##### Example
18070     typedef int (*PFI)(int);   // OK, but convoluted
18072     using PFI2 = int (*)(int);   // OK, preferred
18074     template<typename T>
18075     typedef int (*PFT)(T);      // error
18077     template<typename T>
18078     using PFT2 = int (*)(T);   // OK
18080 ##### Enforcement
18082 * Flag uses of `typedef`. This will give a lot of "hits" :-(
18084 ### <a name="Rt-deduce"></a>T.44: Use function templates to deduce class template argument types (where feasible)
18086 ##### Reason
18088 Writing the template argument types explicitly can be tedious and unnecessarily verbose.
18090 ##### Example
18092     tuple<int, string, double> t1 = {1, "Hamlet", 3.14};   // explicit type
18093     auto t2 = make_tuple(1, "Ophelia"s, 3.14);         // better; deduced type
18095 Note the use of the `s` suffix to ensure that the string is a `std::string`, rather than a C-style string.
18097 ##### Note
18099 Since you can trivially write a `make_T` function, so could the compiler. Thus, `make_T` functions might become redundant in the future.
18101 ##### Exception
18103 Sometimes there isn't a good way of getting the template arguments deduced and sometimes, you want to specify the arguments explicitly:
18105     vector<double> v = { 1, 2, 3, 7.9, 15.99 };
18106     list<Record*> lst;
18108 ##### Note
18110 Note that C++17 will make this rule redundant by allowing the template arguments to be deduced directly from constructor arguments:
18111 [Template parameter deduction for constructors (Rev. 3)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r1.html).
18112 For example:
18114     tuple t1 = {1, "Hamlet"s, 3.14}; // deduced: tuple<int, string, double>
18116 ##### Enforcement
18118 Flag uses where an explicitly specialized type exactly matches the types of the arguments used.
18120 ### <a name="Rt-regular"></a>T.46: Require template arguments to be at least semiregular
18122 ##### Reason
18124 Readability.
18125 Preventing surprises and errors.
18126 Most uses support that anyway.
18128 ##### Example
18130     class X {
18131     public:
18132         explicit X(int);
18133         X(const X&);            // copy
18134         X operator=(const X&);
18135         X(X&&) noexcept;        // move
18136         X& operator=(X&&) noexcept;
18137         ~X();
18138         // ... no more constructors ...
18139     };
18141     X x {1};              // fine
18142     X y = x;              // fine
18143     std::vector<X> v(10); // error: no default constructor
18145 ##### Note
18147 Semiregular requires default constructible.
18149 ##### Enforcement
18151 * Flag types used as template arguments that are not at least semiregular.
18153 ### <a name="Rt-visible"></a>T.47: Avoid highly visible unconstrained templates with common names
18155 ##### Reason
18157  An unconstrained template argument is a perfect match for anything so such a template can be preferred over more specific types that require minor conversions.
18158  This is particularly annoying/dangerous when ADL is used.
18159  Common names make this problem more likely.
18161 ##### Example
18163     namespace Bad {
18164         struct S { int m; };
18165         template<typename T1, typename T2>
18166         bool operator==(T1, T2) { cout << "Bad\n"; return true; }
18167     }
18169     namespace T0 {
18170         bool operator==(int, Bad::S) { cout << "T0\n"; return true; }  // compare to int
18172         void test()
18173         {
18174             Bad::S bad{ 1 };
18175             vector<int> v(10);
18176             bool b = 1 == bad;
18177             bool b2 = v.size() == bad;
18178         }
18179     }
18181 This prints `T0` and `Bad`.
18183 Now the `==` in `Bad` was designed to cause trouble, but would you have spotted the problem in real code?
18184 The problem is that `v.size()` returns an `unsigned` integer so that a conversion is needed to call the local `==`;
18185 the `==` in `Bad` requires no conversions.
18186 Realistic types, such as the standard-library iterators can be made to exhibit similar anti-social tendencies.
18188 ##### Note
18190 If an unconstrained template is defined in the same namespace as a type,
18191 that unconstrained template can be found by ADL (as happened in the example).
18192 That is, it is highly visible.
18194 ##### Note
18196 This rule should not be necessary, but the committee cannot agree to exclude unconstrained templates from ADL.
18198 Unfortunately this will get many false positives; the standard library violates this widely, by putting many unconstrained templates and types into the single namespace `std`.
18201 ##### Enforcement
18203 Flag templates defined in a namespace where concrete types are also defined (maybe not feasible until we have concepts).
18206 ### <a name="Rt-concept-def"></a>T.48: If your compiler does not support concepts, fake them with `enable_if`
18208 ##### Reason
18210 Because that's the best we can do without direct concept support.
18211 `enable_if` can be used to conditionally define functions and to select among a set of functions.
18213 ##### Example
18215     template<typename T>
18216     enable_if_t<is_integral_v<T>>
18217     f(T v)
18218     {
18219         // ...
18220     }
18222     // Equivalent to:
18223     template<Integral T>
18224     void f(T v)
18225     {
18226         // ...
18227     }
18229 ##### Note
18231 Beware of [complementary constraints](#Rt-not).
18232 Faking concept overloading using `enable_if` sometimes forces us to use that error-prone design technique.
18234 ##### Enforcement
18238 ### <a name="Rt-erasure"></a>T.49: Where possible, avoid type-erasure
18240 ##### Reason
18242 Type erasure incurs an extra level of indirection by hiding type information behind a separate compilation boundary.
18244 ##### Example
18246     ???
18248 **Exceptions**: Type erasure is sometimes appropriate, such as for `std::function`.
18250 ##### Enforcement
18255 ##### Note
18258 ## <a name="SS-temp-def"></a>T.def: Template definitions
18260 A template definition (class or function) can contain arbitrary code, so only a comprehensive review of C++ programming techniques would cover this topic.
18261 However, this section focuses on what is specific to template implementation.
18262 In particular, it focuses on a template definition's dependence on its context.
18264 ### <a name="Rt-depend"></a>T.60: Minimize a template's context dependencies
18266 ##### Reason
18268 Eases understanding.
18269 Minimizes errors from unexpected dependencies.
18270 Eases tool creation.
18272 ##### Example
18274     template<typename C>
18275     void sort(C& c)
18276     {
18277         std::sort(begin(c), end(c)); // necessary and useful dependency
18278     }
18280     template<typename Iter>
18281     Iter algo(Iter first, Iter last)
18282     {
18283         for (; first != last; ++first) {
18284             auto x = sqrt(*first); // potentially surprising dependency: which sqrt()?
18285             helper(first, x);      // potentially surprising dependency:
18286                                    // helper is chosen based on first and x
18287             TT var = 7;            // potentially surprising dependency: which TT?
18288         }
18289     }
18291 ##### Note
18293 Templates typically appear in header files so their context dependencies are more vulnerable to `#include` order dependencies than functions in `.cpp` files.
18295 ##### Note
18297 Having a template operate only on its arguments would be one way of reducing the number of dependencies to a minimum, but that would generally be unmanageable.
18298 For example, algorithms usually use other algorithms and invoke operations that do not exclusively operate on arguments.
18299 And don't get us started on macros!
18301 **See also**: [T.69](#Rt-customization)
18303 ##### Enforcement
18305 ??? Tricky
18307 ### <a name="Rt-scary"></a>T.61: Do not over-parameterize members (SCARY)
18309 ##### Reason
18311 A member that does not depend on a template parameter cannot be used except for a specific template argument.
18312 This limits use and typically increases code size.
18314 ##### Example, bad
18316     template<typename T, typename A = std::allocator<T>>
18317         // requires Regular<T> && Allocator<A>
18318     class List {
18319     public:
18320         struct Link {   // does not depend on A
18321             T elem;
18322             Link* pre;
18323             Link* suc;
18324         };
18326         using iterator = Link*;
18328         iterator first() const { return head; }
18330         // ...
18331     private:
18332         Link* head;
18333     };
18335     List<int> lst1;
18336     List<int, My_allocator> lst2;
18338 This looks innocent enough, but now `Link` formally depends on the allocator (even though it doesn't use the allocator). This forces redundant instantiations that can be surprisingly costly in some real-world scenarios.
18339 Typically, the solution is to make what would have been a nested class non-local, with its own minimal set of template parameters.
18341     template<typename T>
18342     struct Link {
18343         T elem;
18344         Link* pre;
18345         Link* suc;
18346     };
18348     template<typename T, typename A = std::allocator<T>>
18349         // requires Regular<T> && Allocator<A>
18350     class List2 {
18351     public:
18352         using iterator = Link<T>*;
18354         iterator first() const { return head; }
18356         // ...
18357     private:
18358         Link<T>* head;
18359     };
18361     List2<int> lst1;
18362     List2<int, My_allocator> lst2;
18364 Some people found the idea that the `Link` no longer was hidden inside the list scary, so we named the technique
18365 [SCARY](http://www.open-std.org/jtc1/sc22/WG21/docs/papers/2009/n2911.pdf). From that academic paper:
18366 "The acronym SCARY describes assignments and initializations that are Seemingly erroneous (appearing Constrained by conflicting generic parameters), but Actually work with the Right implementation (unconstrained bY the conflict due to minimized dependencies)."
18368 ##### Note
18370 This also applies to lambdas that don't depend on all of the template parameters.
18372 ##### Enforcement
18374 * Flag member types that do not depend on every template parameter
18375 * Flag member functions that do not depend on every template parameter
18376 * Flag lambdas or variable templates that do not depend on every template parameter
18378 ### <a name="Rt-nondependent"></a>T.62: Place non-dependent class template members in a non-templated base class
18380 ##### Reason
18382  Allow the base class members to be used without specifying template arguments and without template instantiation.
18384 ##### Example
18386     template<typename T>
18387     class Foo {
18388     public:
18389         enum { v1, v2 };
18390         // ...
18391     };
18395     struct Foo_base {
18396         enum { v1, v2 };
18397         // ...
18398     };
18400     template<typename T>
18401     class Foo : public Foo_base {
18402     public:
18403         // ...
18404     };
18406 ##### Note
18408 A more general version of this rule would be
18409 "If a class template member depends on only N template parameters out of M, place it in a base class with only N parameters."
18410 For N == 1, we have a choice of a base class of a class in the surrounding scope as in [T.61](#Rt-scary).
18412 ??? What about constants? class statics?
18414 ##### Enforcement
18416 * Flag ???
18418 ### <a name="Rt-specialization"></a>T.64: Use specialization to provide alternative implementations of class templates
18420 ##### Reason
18422 A template defines a general interface.
18423 Specialization offers a powerful mechanism for providing alternative implementations of that interface.
18425 ##### Example
18427     ??? string specialization (==)
18429     ??? representation specialization ?
18431 ##### Note
18435 ##### Enforcement
18439 ### <a name="Rt-tag-dispatch"></a>T.65: Use tag dispatch to provide alternative implementations of a function
18441 ##### Reason
18443 * A template defines a general interface.
18444 * Tag dispatch allows us to select implementations based on specific properties of an argument type.
18445 * Performance.
18447 ##### Example
18449 This is a simplified version of `std::copy` (ignoring the possibility of non-contiguous sequences)
18451     struct trivially_copyable_tag {};
18452     struct non_trivially_copyable_tag {};
18454     // T is not trivially copyable
18455     template<class T> struct copy_trait { using tag = non_trivially_copyable_tag; };
18456     // int is trivially copyable
18457     template<> struct copy_trait<int> { using tag = trivially_copyable_tag; };
18459     template<class Iter>
18460     Out copy_helper(Iter first, Iter last, Iter out, trivially_copyable_tag)
18461     {
18462         // use memmove
18463     }
18465     template<class Iter>
18466     Out copy_helper(Iter first, Iter last, Iter out, non_trivially_copyable_tag)
18467     {
18468         // use loop calling copy constructors
18469     }
18471     template<class Iter>
18472     Out copy(Iter first, Iter last, Iter out)
18473     {
18474         using tag_type = typename copy_trait<std::iter_value_t<Iter>>;
18475         return copy_helper(first, last, out, tag_type{})
18476     }
18478     void use(vector<int>& vi, vector<int>& vi2, vector<string>& vs, vector<string>& vs2)
18479     {
18480         copy(vi.begin(), vi.end(), vi2.begin()); // uses memmove
18481         copy(vs.begin(), vs.end(), vs2.begin()); // uses a loop calling copy constructors
18482     }
18484 This is a general and powerful technique for compile-time algorithm selection.
18486 ##### Note
18488 With C++20 constraints, such alternatives can be distinguished directly:
18490     template<class Iter>
18491         requires std::is_trivially_copyable_v<std::iter_value_t<Iter>>
18492     Out copy_helper(In, first, In last, Out out)
18493     {
18494         // use memmove
18495     }
18497     template<class Iter>
18498     Out copy_helper(In, first, In last, Out out)
18499     {
18500         // use loop calling copy constructors
18501     }
18503 ##### Enforcement
18508 ### <a name="Rt-specialization2"></a>T.67: Use specialization to provide alternative implementations for irregular types
18510 ##### Reason
18512  ???
18514 ##### Example
18516     ???
18518 ##### Enforcement
18522 ### <a name="Rt-cast"></a>T.68: Use `{}` rather than `()` within templates to avoid ambiguities
18524 ##### Reason
18526 `()` is vulnerable to grammar ambiguities.
18528 ##### Example
18530     template<typename T, typename U>
18531     void f(T t, U u)
18532     {
18533         T v1(T(u));    // mistake: oops, v1 is a function not a variable
18534         T v2{u};       // clear:   obviously a variable
18535         auto x = T(u); // unclear: construction or cast?
18536     }
18538     f(1, "asdf"); // bad: cast from const char* to int
18540 ##### Enforcement
18542 * flag `()` initializers
18543 * flag function-style casts
18546 ### <a name="Rt-customization"></a>T.69: Inside a template, don't make an unqualified non-member function call unless you intend it to be a customization point
18548 ##### Reason
18550 * Provide only intended flexibility.
18551 * Avoid vulnerability to accidental environmental changes.
18553 ##### Example
18555 There are three major ways to let calling code customize a template.
18557     template<class T>
18558         // Call a member function
18559     void test1(T t)
18560     {
18561         t.f();    // require T to provide f()
18562     }
18564     template<class T>
18565     void test2(T t)
18566         // Call a non-member function without qualification
18567     {
18568         f(t);     // require f(/*T*/) be available in caller's scope or in T's namespace
18569     }
18571     template<class T>
18572     void test3(T t)
18573         // Invoke a "trait"
18574     {
18575         test_traits<T>::f(t); // require customizing test_traits<>
18576                               // to get non-default functions/types
18577     }
18579 A trait is usually a type alias to compute a type,
18580 a `constexpr` function to compute a value,
18581 or a traditional traits template to be specialized on the user's type.
18583 ##### Note
18585 If you intend to call your own helper function `helper(t)` with a value `t` that depends on a template type parameter,
18586 put it in a `::detail` namespace and qualify the call as `detail::helper(t);`.
18587 An unqualified call becomes a customization point where any function `helper` in the namespace of `t`'s type can be invoked;
18588 this can cause problems like [unintentionally invoking unconstrained function templates](#Rt-visible).
18591 ##### Enforcement
18593 * In a template, flag an unqualified call to a non-member function that passes a variable of dependent type when there is a non-member function of the same name in the template's namespace.
18596 ## <a name="SS-temp-hier"></a>T.temp-hier: Template and hierarchy rules:
18598 Templates are the backbone of C++'s support for generic programming and class hierarchies the backbone of its support
18599 for object-oriented programming.
18600 The two language mechanisms can be used effectively in combination, but a few design pitfalls must be avoided.
18602 ### <a name="Rt-hier"></a>T.80: Do not naively templatize a class hierarchy
18604 ##### Reason
18606 Templating a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat.
18608 ##### Example, bad
18610     template<typename T>
18611     struct Container {         // an interface
18612         virtual T* get(int i);
18613         virtual T* first();
18614         virtual T* next();
18615         virtual void sort();
18616     };
18618     template<typename T>
18619     class Vector : public Container<T> {
18620     public:
18621         // ...
18622     };
18624     Vector<int> vi;
18625     Vector<string> vs;
18627 It is probably a bad idea to define a `sort` as a member function of a container, but it is not unheard of and it makes a good example of what not to do.
18629 Given this, the compiler cannot know if `vector<int>::sort()` is called, so it must generate code for it.
18630 Similar for `vector<string>::sort()`.
18631 Unless those two functions are called that's code bloat.
18632 Imagine what this would do to a class hierarchy with dozens of member functions and dozens of derived classes with many instantiations.
18634 ##### Note
18636 In many cases you can provide a stable interface by not parameterizing a base;
18637 see ["stable base"](#Rt-abi) and [OO and GP](#Rt-generic-oo)
18639 ##### Enforcement
18641 * Flag virtual functions that depend on a template argument. ??? False positives
18643 ### <a name="Rt-array"></a>T.81: Do not mix hierarchies and arrays
18645 ##### Reason
18647 An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results.
18649 ##### Example
18651 Assume that `Apple` and `Pear` are two kinds of `Fruit`s.
18653     void maul(Fruit* p)
18654     {
18655         *p = Pear{};     // put a Pear into *p
18656         p[1] = Pear{};   // put a Pear into p[1]
18657     }
18659     Apple aa [] = { an_apple, another_apple };   // aa contains Apples (obviously!)
18661     maul(aa);
18662     Apple& a0 = &aa[0];   // a Pear?
18663     Apple& a1 = &aa[1];   // a Pear?
18665 Probably, `aa[0]` will be a `Pear` (without the use of a cast!).
18666 If `sizeof(Apple) != sizeof(Pear)` the access to `aa[1]` will not be aligned to the proper start of an object in the array.
18667 We have a type violation and possibly (probably) a memory corruption.
18668 Never write such code.
18670 Note that `maul()` violates the a [`T*` points to an individual object rule](#Rf-ptr).
18672 **Alternative**: Use a proper (templatized) container:
18674     void maul2(Fruit* p)
18675     {
18676         *p = Pear{};   // put a Pear into *p
18677     }
18679     vector<Apple> va = { an_apple, another_apple };   // va contains Apples (obviously!)
18681     maul2(va);       // error: cannot convert a vector<Apple> to a Fruit*
18682     maul2(&va[0]);   // you asked for it
18684     Apple& a0 = &va[0];   // a Pear?
18686 Note that the assignment in `maul2()` violated the [no-slicing rule](#Res-slice).
18688 ##### Enforcement
18690 * Detect this horror!
18692 ### <a name="Rt-linear"></a>T.82: Linearize a hierarchy when virtual functions are undesirable
18694 ##### Reason
18696  ???
18698 ##### Example
18700     ???
18702 ##### Enforcement
18706 ### <a name="Rt-virtual"></a>T.83: Do not declare a member function template virtual
18708 ##### Reason
18710 C++ does not support that.
18711 If it did, vtbls could not be generated until link time.
18712 And in general, implementations must deal with dynamic linking.
18714 ##### Example, don't
18716     class Shape {
18717         // ...
18718         template<class T>
18719         virtual bool intersect(T* p);   // error: template cannot be virtual
18720     };
18722 ##### Note
18724 We need a rule because people keep asking about this
18726 ##### Alternative
18728 Double dispatch, visitors, calculate which function to call
18730 ##### Enforcement
18732 The compiler handles that.
18734 ### <a name="Rt-abi"></a>T.84: Use a non-template core implementation to provide an ABI-stable interface
18736 ##### Reason
18738 Improve stability of code.
18739 Avoid code bloat.
18741 ##### Example
18743 It could be a base class:
18745     struct Link_base {   // stable
18746         Link_base* suc;
18747         Link_base* pre;
18748     };
18750     template<typename T>   // templated wrapper to add type safety
18751     struct Link : Link_base {
18752         T val;
18753     };
18755     struct List_base {
18756         Link_base* first;   // first element (if any)
18757         int sz;             // number of elements
18758         void add_front(Link_base* p);
18759         // ...
18760     };
18762     template<typename T>
18763     class List : List_base {
18764     public:
18765         void put_front(const T& e) { add_front(new Link<T>{e}); }   // implicit cast to Link_base
18766         T& front() { static_cast<Link<T>*>(first).val; }   // explicit cast back to Link<T>
18767         // ...
18768     };
18770     List<int> li;
18771     List<string> ls;
18773 Now there is only one copy of the operations linking and unlinking elements of a `List`.
18774 The `Link` and `List` classes do nothing but type manipulation.
18776 Instead of using a separate "base" type, another common technique is to specialize for `void` or `void*` and have the general template for `T` be just the safely-encapsulated casts to and from the core `void` implementation.
18778 **Alternative**: Use a [Pimpl](#Ri-pimpl) implementation.
18780 ##### Enforcement
18784 ## <a name="SS-variadic"></a>T.var: Variadic template rules
18788 ### <a name="Rt-variadic"></a>T.100: Use variadic templates when you need a function that takes a variable number of arguments of a variety of types
18790 ##### Reason
18792 Variadic templates is the most general mechanism for that, and is both efficient and type-safe. Don't use C varargs.
18794 ##### Example
18796     ??? printf
18798 ##### Enforcement
18800 * Flag uses of `va_arg` in user code.
18802 ### <a name="Rt-variadic-pass"></a>T.101: ??? How to pass arguments to a variadic template ???
18804 ##### Reason
18806  ???
18808 ##### Example
18810     ??? beware of move-only and reference arguments
18812 ##### Enforcement
18816 ### <a name="Rt-variadic-process"></a>T.102: How to process arguments to a variadic template
18818 ##### Reason
18820  ???
18822 ##### Example
18824     ??? forwarding, type checking, references
18826 ##### Enforcement
18830 ### <a name="Rt-variadic-not"></a>T.103: Don't use variadic templates for homogeneous argument lists
18832 ##### Reason
18834 There are more precise ways of specifying a homogeneous sequence, such as an `initializer_list`.
18836 ##### Example
18838     ???
18840 ##### Enforcement
18844 ## <a name="SS-meta"></a>T.meta: Template metaprogramming (TMP)
18846 Templates provide a general mechanism for compile-time programming.
18848 Metaprogramming is programming where at least one input or one result is a type.
18849 Templates offer Turing-complete (modulo memory capacity) duck typing at compile time.
18850 The syntax and techniques needed are pretty horrendous.
18852 ### <a name="Rt-metameta"></a>T.120: Use template metaprogramming only when you really need to
18854 ##### Reason
18856 Template metaprogramming is hard to get right, slows down compilation, and is often very hard to maintain.
18857 However, there are real-world examples where template metaprogramming provides better performance than any alternative short of expert-level assembly code.
18858 Also, there are real-world examples where template metaprogramming expresses the fundamental ideas better than run-time code.
18859 For example, if you really need AST manipulation at compile time (e.g., for optional matrix operation folding) there might be no other way in C++.
18861 ##### Example, bad
18863     ???
18865 ##### Example, bad
18867     enable_if
18869 Instead, use concepts. But see [How to emulate concepts if you don't have language support](#Rt-emulate).
18871 ##### Example
18873     ??? good
18875 **Alternative**: If the result is a value, rather than a type, use a [`constexpr` function](#Rt-fct).
18877 ##### Note
18879 If you feel the need to hide your template metaprogramming in macros, you have probably gone too far.
18881 ### <a name="Rt-emulate"></a>T.121: Use template metaprogramming primarily to emulate concepts
18883 ##### Reason
18885 Where C++20 is not available, we need to emulate them using TMP.
18886 Use cases that require concepts (e.g. overloading based on concepts) are among the most common (and simple) uses of TMP.
18888 ##### Example
18890     template<typename Iter>
18891         /*requires*/ enable_if<random_access_iterator<Iter>, void>
18892     advance(Iter p, int n) { p += n; }
18894     template<typename Iter>
18895         /*requires*/ enable_if<forward_iterator<Iter>, void>
18896     advance(Iter p, int n) { assert(n >= 0); while (n--) ++p;}
18898 ##### Note
18900 Such code is much simpler using concepts:
18902     void advance(random_access_iterator auto p, int n) { p += n; }
18904     void advance(forward_iterator auto p, int n) { assert(n >= 0); while (n--) ++p;}
18906 ##### Enforcement
18910 ### <a name="Rt-tmp"></a>T.122: Use templates (usually template aliases) to compute types at compile time
18912 ##### Reason
18914 Template metaprogramming is the only directly supported and half-way principled way of generating types at compile time.
18916 ##### Note
18918 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
18920 ##### Example
18922     ??? big object / small object optimization
18924 ##### Enforcement
18928 ### <a name="Rt-fct"></a>T.123: Use `constexpr` functions to compute values at compile time
18930 ##### Reason
18932 A function is the most obvious and conventional way of expressing the computation of a value.
18933 Often a `constexpr` function implies less compile-time overhead than alternatives.
18935 ##### Note
18937 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
18939 ##### Example
18941     template<typename T>
18942         // requires Number<T>
18943     constexpr T pow(T v, int n)   // power/exponential
18944     {
18945         T res = 1;
18946         while (n--) res *= v;
18947         return res;
18948     }
18950     constexpr auto f7 = pow(pi, 7);
18952 ##### Enforcement
18954 * Flag template metaprograms yielding a value. These should be replaced with `constexpr` functions.
18956 ### <a name="Rt-std-tmp"></a>T.124: Prefer to use standard-library TMP facilities
18958 ##### Reason
18960 Facilities defined in the standard, such as `conditional`, `enable_if`, and `tuple`, are portable and can be assumed to be known.
18962 ##### Example
18964     ???
18966 ##### Enforcement
18970 ### <a name="Rt-lib"></a>T.125: If you need to go beyond the standard-library TMP facilities, use an existing library
18972 ##### Reason
18974 Getting advanced TMP facilities is not easy and using a library makes you part of a (hopefully supportive) community.
18975 Write your own "advanced TMP support" only if you really have to.
18977 ##### Example
18979     ???
18981 ##### Enforcement
18985 ## <a name="SS-temp-other"></a>Other template rules
18987 ### <a name="Rt-name"></a>T.140: If an operation can be reused, give it a name
18989 See [F.10](#Rf-name)
18991 ### <a name="Rt-lambda"></a>T.141: Use an unnamed lambda if you need a simple function object in one place only
18993 See [F.11](#Rf-lambda)
18995 ### <a name="Rt-var"></a>T.142?: Use template variables to simplify notation
18997 ##### Reason
18999 Improved readability.
19001 ##### Example
19003     ???
19005 ##### Enforcement
19009 ### <a name="Rt-non-generic"></a>T.143: Don't write unintentionally non-generic code
19011 ##### Reason
19013 Generality. Reusability. Don't gratuitously commit to details; use the most general facilities available.
19015 ##### Example
19017 Use `!=` instead of `<` to compare iterators; `!=` works for more objects because it doesn't rely on ordering.
19019     for (auto i = first; i < last; ++i) {   // less generic
19020         // ...
19021     }
19023     for (auto i = first; i != last; ++i) {   // good; more generic
19024         // ...
19025     }
19027 Of course, range-`for` is better still where it does what you want.
19029 ##### Example
19031 Use the least-derived class that has the functionality you need.
19033     class Base {
19034     public:
19035         Bar f();
19036         Bar g();
19037     };
19039     class Derived1 : public Base {
19040     public:
19041         Bar h();
19042     };
19044     class Derived2 : public Base {
19045     public:
19046         Bar j();
19047     };
19049     // bad, unless there is a specific reason for limiting to Derived1 objects only
19050     void my_func(Derived1& param)
19051     {
19052         use(param.f());
19053         use(param.g());
19054     }
19056     // good, uses only Base interface so only commit to that
19057     void my_func(Base& param)
19058     {
19059         use(param.f());
19060         use(param.g());
19061     }
19063 ##### Enforcement
19065 * Flag comparison of iterators using `<` instead of `!=`.
19066 * Flag `x.size() == 0` when `x.empty()` or `x.is_empty()` is available. Emptiness works for more containers than size(), because some containers don't know their size or are conceptually of unbounded size.
19067 * Flag functions that take a pointer or reference to a more-derived type but only use functions declared in a base type.
19069 ### <a name="Rt-specialize-function"></a>T.144: Don't specialize function templates
19071 ##### Reason
19073 You can't partially specialize a function template per language rules. You can fully specialize a function template but you almost certainly want to overload instead -- because function template specializations don't participate in overloading, they don't act as you probably wanted. Rarely, you should actually specialize by delegating to a class template that you can specialize properly.
19075 ##### Example
19077     ???
19079 **Exceptions**: If you do have a valid reason to specialize a function template, just write a single function template that delegates to a class template, then specialize the class template (including the ability to write partial specializations).
19081 ##### Enforcement
19083 * Flag all specializations of a function template. Overload instead.
19086 ### <a name="Rt-check-class"></a>T.150: Check that a class matches a concept using `static_assert`
19088 ##### Reason
19090 If you intend for a class to match a concept, verifying that early saves users' pain.
19092 ##### Example
19094     class X {
19095     public:
19096         X() = delete;
19097         X(const X&) = default;
19098         X(X&&) = default;
19099         X& operator=(const X&) = default;
19100         // ...
19101     };
19103 Somewhere, possibly in an implementation file, let the compiler check the desired properties of `X`:
19105     static_assert(Default_constructible<X>);    // error: X has no default constructor
19106     static_assert(Copyable<X>);                 // error: we forgot to define X's move constructor
19109 ##### Enforcement
19111 Not feasible.
19113 # <a name="S-cpl"></a>CPL: C-style programming
19115 C and C++ are closely related languages.
19116 They both originate in "Classic C" from 1978 and have evolved in ISO committees since then.
19117 Many attempts have been made to keep them compatible, but neither is a subset of the other.
19119 C rule summary:
19121 * [CPL.1: Prefer C++ to C](#Rcpl-C)
19122 * [CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++](#Rcpl-subset)
19123 * [CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces](#Rcpl-interface)
19125 ### <a name="Rcpl-C"></a>CPL.1: Prefer C++ to C
19127 ##### Reason
19129 C++ provides better type checking and more notational support.
19130 It provides better support for high-level programming and often generates faster code.
19132 ##### Example
19134     char ch = 7;
19135     void* pv = &ch;
19136     int* pi = pv;   // not C++
19137     *pi = 999;      // overwrite sizeof(int) bytes near &ch
19139 The rules for implicit casting to and from `void*` in C are subtle and unenforced.
19140 In particular, this example violates a rule against converting to a type with stricter alignment.
19142 ##### Enforcement
19144 Use a C++ compiler.
19146 ### <a name="Rcpl-subset"></a>CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++
19148 ##### Reason
19150 That subset can be compiled with both C and C++ compilers, and when compiled as C++ is better type checked than "pure C."
19152 ##### Example
19154     int* p1 = malloc(10 * sizeof(int));                      // not C++
19155     int* p2 = static_cast<int*>(malloc(10 * sizeof(int)));   // not C, C-style C++
19156     int* p3 = new int[10];                                   // not C
19157     int* p4 = (int*) malloc(10 * sizeof(int));               // both C and C++
19159 ##### Enforcement
19161 * Flag if using a build mode that compiles code as C.
19163   * The C++ compiler will enforce that the code is valid C++ unless you use C extension options.
19165 ### <a name="Rcpl-interface"></a>CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces
19167 ##### Reason
19169 C++ is more expressive than C and offers better support for many types of programming.
19171 ##### Example
19173 For example, to use a 3rd party C library or C systems interface, define the low-level interface in the common subset of C and C++ for better type checking.
19174 Whenever possible encapsulate the low-level interface in an interface that follows the C++ guidelines (for better abstraction, memory safety, and resource safety) and use that C++ interface in C++ code.
19176 ##### Example
19178 You can call C from C++:
19180     // in C:
19181     double sqrt(double);
19183     // in C++:
19184     extern "C" double sqrt(double);
19186     sqrt(2);
19188 ##### Example
19190 You can call C++ from C:
19192     // in C:
19193     X call_f(struct Y*, int);
19195     // in C++:
19196     extern "C" X call_f(Y* p, int i)
19197     {
19198         return p->f(i);   // possibly a virtual function call
19199     }
19201 ##### Enforcement
19203 None needed
19205 # <a name="S-source"></a>SF: Source files
19207 Distinguish between declarations (used as interfaces) and definitions (used as implementations).
19208 Use header files to represent interfaces and to emphasize logical structure.
19210 Source file rule summary:
19212 * [SF.1: Use a `.cpp` suffix for code files and `.h` for interface files if your project doesn't already follow another convention](#Rs-file-suffix)
19213 * [SF.2: A header file must not contain object definitions or non-inline function definitions](#Rs-inline)
19214 * [SF.3: Use header files for all declarations used in multiple source files](#Rs-declaration-header)
19215 * [SF.4: Include header files before other declarations in a file](#Rs-include-order)
19216 * [SF.5: A `.cpp` file must include the header file(s) that defines its interface](#Rs-consistency)
19217 * [SF.6: Use `using namespace` directives for transition, for foundation libraries (such as `std`), or within a local scope (only)](#Rs-using)
19218 * [SF.7: Don't write `using namespace` at global scope in a header file](#Rs-using-directive)
19219 * [SF.8: Use `#include` guards for all header files](#Rs-guards)
19220 * [SF.9: Avoid cyclic dependencies among source files](#Rs-cycles)
19221 * [SF.10: Avoid dependencies on implicitly `#include`d names](#Rs-implicit)
19222 * [SF.11: Header files should be self-contained](#Rs-contained)
19223 * [SF.12: Prefer the quoted form of `#include` for files relative to the including file and the angle bracket form everywhere else](#Rs-incform)
19224 * [SF.13: Use portable header identifiers in `#include` statements](#Rs-portable-header-id)
19226 * [SF.20: Use `namespace`s to express logical structure](#Rs-namespace)
19227 * [SF.21: Don't use an unnamed (anonymous) namespace in a header](#Rs-unnamed)
19228 * [SF.22: Use an unnamed (anonymous) namespace for all internal/non-exported entities](#Rs-unnamed2)
19230 ### <a name="Rs-file-suffix"></a>SF.1: Use a `.cpp` suffix for code files and `.h` for interface files if your project doesn't already follow another convention
19232 See [NL.27](#Rl-file-suffix)
19234 ### <a name="Rs-inline"></a>SF.2: A header file must not contain object definitions or non-inline function definitions
19236 ##### Reason
19238 Including entities subject to the one-definition rule leads to linkage errors.
19240 ##### Example
19242     // file.h:
19243     namespace Foo {
19244         int x = 7;
19245         int xx() { return x+x; }
19246     }
19248     // file1.cpp:
19249     #include <file.h>
19250     // ... more ...
19252      // file2.cpp:
19253     #include <file.h>
19254     // ... more ...
19256 Linking `file1.cpp` and `file2.cpp` will give two linker errors.
19258 **Alternative formulation**: A header file must contain only:
19260 * `#include`s of other header files (possibly with include guards)
19261 * templates
19262 * class definitions
19263 * function declarations
19264 * `extern` declarations
19265 * `inline` function definitions
19266 * `constexpr` definitions
19267 * `const` definitions
19268 * `using` alias definitions
19269 * ???
19271 ##### Enforcement
19273 Check the positive list above.
19275 ### <a name="Rs-declaration-header"></a>SF.3: Use header files for all declarations used in multiple source files
19277 ##### Reason
19279 Maintainability. Readability.
19281 ##### Example, bad
19283     // bar.cpp:
19284     void bar() { cout << "bar\n"; }
19286     // foo.cpp:
19287     extern void bar();
19288     void foo() { bar(); }
19290 A maintainer of `bar` cannot find all declarations of `bar` if its type needs changing.
19291 The user of `bar` cannot know if the interface used is complete and correct. At best, error messages come (late) from the linker.
19293 ##### Enforcement
19295 * Flag declarations of entities in other source files not placed in a `.h`.
19297 ### <a name="Rs-include-order"></a>SF.4: Include header files before other declarations in a file
19299 ##### Reason
19301 Minimize context dependencies and increase readability.
19303 ##### Example
19305     #include <vector>
19306     #include <algorithm>
19307     #include <string>
19309     // ... my code here ...
19311 ##### Example, bad
19313     #include <vector>
19315     // ... my code here ...
19317     #include <algorithm>
19318     #include <string>
19320 ##### Note
19322 This applies to both `.h` and `.cpp` files.
19324 ##### Note
19326 There is an argument for insulating code from declarations and macros in header files by `#including` headers *after* the code we want to protect
19327 (as in the example labeled "bad").
19328 However
19330 * that only works for one file (at one level): Use that technique in a header included with other headers and the vulnerability reappears.
19331 * a namespace (an "implementation namespace") can protect against many context dependencies.
19332 * full protection and flexibility require modules.
19334 **See also**:
19336 * [Working Draft, Extensions to C++ for Modules](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4592.pdf)
19337 * [Modules, Componentization, and Transition](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0141r0.pdf)
19339 ##### Enforcement
19341 Easy.
19343 ### <a name="Rs-consistency"></a>SF.5: A `.cpp` file must include the header file(s) that defines its interface
19345 ##### Reason
19347 This enables the compiler to do an early consistency check.
19349 ##### Example, bad
19351     // foo.h:
19352     void foo(int);
19353     int bar(long);
19354     int foobar(int);
19356     // foo.cpp:
19357     void foo(int) { /* ... */ }
19358     int bar(double) { /* ... */ }
19359     double foobar(int);
19361 The errors will not be caught until link time for a program calling `bar` or `foobar`.
19363 ##### Example
19365     // foo.h:
19366     void foo(int);
19367     int bar(long);
19368     int foobar(int);
19370     // foo.cpp:
19371     #include "foo.h"
19373     void foo(int) { /* ... */ }
19374     int bar(double) { /* ... */ }
19375     double foobar(int);   // error: wrong return type
19377 The return-type error for `foobar` is now caught immediately when `foo.cpp` is compiled.
19378 The argument-type error for `bar` cannot be caught until link time because of the possibility of overloading, but systematic use of `.h` files increases the likelihood that it is caught earlier by the programmer.
19380 ##### Enforcement
19384 ### <a name="Rs-using"></a>SF.6: Use `using namespace` directives for transition, for foundation libraries (such as `std`), or within a local scope (only)
19386 ##### Reason
19388  `using namespace` can lead to name clashes, so it should be used sparingly.
19389  However, it is not always possible to qualify every name from a namespace in user code (e.g., during transition)
19390  and sometimes a namespace is so fundamental and prevalent in a code base, that consistent qualification would be verbose and distracting.
19392 ##### Example
19394     #include <string>
19395     #include <vector>
19396     #include <iostream>
19397     #include <memory>
19398     #include <algorithm>
19400     using namespace std;
19402     // ...
19404 Here (obviously), the standard library is used pervasively and apparently no other library is used, so requiring `std::` everywhere
19405 could be distracting.
19407 ##### Example
19409 The use of `using namespace std;` leaves the programmer open to a name clash with a name from the standard library
19411     #include <cmath>
19412     using namespace std;
19414     int g(int x)
19415     {
19416         int sqrt = 7;
19417         // ...
19418         return sqrt(x); // error
19419     }
19421 However, this is not particularly likely to lead to a resolution that is not an error and
19422 people who use `using namespace std` are supposed to know about `std` and about this risk.
19424 ##### Note
19426 A `.cpp` file is a form of local scope.
19427 There is little difference in the opportunities for name clashes in an N-line `.cpp` containing a `using namespace X`,
19428 an N-line function containing a `using namespace X`,
19429 and M functions each containing a `using namespace X`with N lines of code in total.
19431 ##### Note
19433 [Don't write `using namespace` at global scope in a header file](#Rs-using-directive).
19435 ### <a name="Rs-using-directive"></a>SF.7: Don't write `using namespace` at global scope in a header file
19437 ##### Reason
19439 Doing so takes away an `#include`r's ability to effectively disambiguate and to use alternatives. It also makes `#include`d headers order-dependent as they might have different meaning when included in different orders.
19441 ##### Example
19443     // bad.h
19444     #include <iostream>
19445     using namespace std; // bad
19447     // user.cpp
19448     #include "bad.h"
19450     bool copy(/*... some parameters ...*/);    // some function that happens to be named copy
19452     int main()
19453     {
19454         copy(/*...*/);    // now overloads local ::copy and std::copy, could be ambiguous
19455     }
19457 ##### Note
19459 An exception is `using namespace std::literals;`. This is necessary to use string literals
19460 in header files and given [the rules](http://eel.is/c++draft/over.literal) - users are required
19461 to name their own UDLs `operator""_x` - they will not collide with the standard library.
19463 ##### Enforcement
19465 Flag `using namespace` at global scope in a header file.
19467 ### <a name="Rs-guards"></a>SF.8: Use `#include` guards for all header files
19469 ##### Reason
19471 To avoid files being `#include`d several times.
19473 In order to avoid include guard collisions, do not just name the guard after the filename.
19474 Be sure to also include a key and good differentiator, such as the name of library or component
19475 the header file is part of.
19477 ##### Example
19479     // file foobar.h:
19480     #ifndef LIBRARY_FOOBAR_H
19481     #define LIBRARY_FOOBAR_H
19482     // ... declarations ...
19483     #endif // LIBRARY_FOOBAR_H
19485 ##### Enforcement
19487 Flag `.h` files without `#include` guards.
19489 ##### Note
19491 Some implementations offer vendor extensions like `#pragma once` as alternative to include guards.
19492 It is not standard and it is not portable.  It injects the hosting machine's filesystem semantics
19493 into your program, in addition to locking you down to a vendor.
19494 Our recommendation is to write in ISO C++: See [rule P.2](#Rp-Cplusplus).
19496 ### <a name="Rs-cycles"></a>SF.9: Avoid cyclic dependencies among source files
19498 ##### Reason
19500 Cycles complicate comprehension and slow down compilation. They also
19501 complicate conversion to use language-supported modules (when they become
19502 available).
19504 ##### Note
19506 Eliminate cycles; don't just break them with `#include` guards.
19508 ##### Example, bad
19510     // file1.h:
19511     #include "file2.h"
19513     // file2.h:
19514     #include "file3.h"
19516     // file3.h:
19517     #include "file1.h"
19519 ##### Enforcement
19521 Flag all cycles.
19524 ### <a name="Rs-implicit"></a>SF.10: Avoid dependencies on implicitly `#include`d names
19526 ##### Reason
19528 Avoid surprises.
19529 Avoid having to change `#include`s if an `#include`d header changes.
19530 Avoid accidentally becoming dependent on implementation details and logically separate entities included in a header.
19532 ##### Example, bad
19534     #include <iostream>
19535     using namespace std;
19537     void use()
19538     {
19539         string s;
19540         cin >> s;               // fine
19541         getline(cin, s);        // error: getline() not defined
19542         if (s == "surprise") {  // error == not defined
19543             // ...
19544         }
19545     }
19547 `<iostream>` exposes the definition of `std::string` ("why?" makes for a fun trivia question),
19548 but it is not required to do so by transitively including the entire `<string>` header,
19549 resulting in the popular beginner question "why doesn't `getline(cin,s);` work?"
19550 or even an occasional "`string`s cannot be compared with `==`").
19552 The solution is to explicitly `#include <string>`:
19554 ##### Example, good
19556     #include <iostream>
19557     #include <string>
19558     using namespace std;
19560     void use()
19561     {
19562         string s;
19563         cin >> s;               // fine
19564         getline(cin, s);        // fine
19565         if (s == "surprise") {  // fine
19566             // ...
19567         }
19568     }
19570 ##### Note
19572 Some headers exist exactly to collect a set of consistent declarations from a variety of headers.
19573 For example:
19575     // basic_std_lib.h:
19577     #include <string>
19578     #include <map>
19579     #include <iostream>
19580     #include <random>
19581     #include <vector>
19583 a user can now get that set of declarations with a single `#include`
19585     #include "basic_std_lib.h"
19587 This rule against implicit inclusion is not meant to prevent such deliberate aggregation.
19589 ##### Enforcement
19591 Enforcement would require some knowledge about what in a header is meant to be "exported" to users and what is there to enable implementation.
19592 No really good solution is possible until we have modules.
19594 ### <a name="Rs-contained"></a>SF.11: Header files should be self-contained
19596 ##### Reason
19598 Usability, headers should be simple to use and work when included on their own.
19599 Headers should encapsulate the functionality they provide.
19600 Avoid clients of a header having to manage that header's dependencies.
19602 ##### Example
19604     #include "helpers.h"
19605     // helpers.h depends on std::string and includes <string>
19607 ##### Note
19609 Failing to follow this results in difficult to diagnose errors for clients of a header.
19611 ##### Note
19613 A header should include all its dependencies. Be careful about using relative paths because C++ implementations diverge on their meaning.
19615 ##### Enforcement
19617 A test should verify that the header file itself compiles or that a cpp file which only includes the header file compiles.
19619 ### <a name="Rs-incform"></a>SF.12: Prefer the quoted form of `#include` for files relative to the including file and the angle bracket form everywhere else
19621 ##### Reason
19623 The [standard](http://eel.is/c++draft/cpp.include) provides flexibility for compilers to implement
19624 the two forms of `#include` selected using the angle (`<>`) or quoted (`""`) syntax. Vendors take
19625 advantage of this and use different search algorithms and methods for specifying the include path.
19627 Nevertheless, the guidance is to use the quoted form for including files that exist at a relative path to the file containing the `#include` statement (from within the same component or project) and to use the angle bracket form everywhere else, where possible. This encourages being clear about the locality of the file relative to files that include it, or scenarios where the different search algorithm is required. It makes it easy to understand at a glance whether a header is being included from a local relative file versus a standard library header or a header from the alternate search path (e.g. a header from another library or a common set of includes).
19629 ##### Example
19631     // foo.cpp:
19632     #include <string>                // From the standard library, requires the <> form
19633     #include <some_library/common.h> // A file that is not locally relative, included from another library; use the <> form
19634     #include "foo.h"                 // A file locally relative to foo.cpp in the same project, use the "" form
19635     #include "util/util.h"           // A file locally relative to foo.cpp in the same project, use the "" form
19636     #include <component_b/bar.h>     // A file in the same project located via a search path, use the <> form
19638 ##### Note
19640 Failing to follow this results in difficult to diagnose errors due to picking up the wrong file by incorrectly specifying the scope when it is included. For example, in a typical case where the `#include ""` search algorithm might search for a file existing at a local relative path first, then using this form to refer to a file that is not locally relative could mean that if a file ever comes into existence at the local relative path (e.g. the including file is moved to a new location), it will now be found ahead of the previous include file and the set of includes will have been changed in an unexpected way.
19642 Library creators should put their headers in a folder and have clients include those files using the relative path `#include <some_library/common.h>`
19644 ##### Enforcement
19646 A test should identify whether headers referenced via `""` could be referenced with `<>`.
19648 ### <a name="Rs-portable-header-id"></a>SF.13: Use portable header identifiers in `#include` statements
19650 ##### Reason
19652 The [standard](http://eel.is/c++draft/cpp.include) does not specify how compilers uniquely locate headers from an identifier in an `#include` directive, nor does it specify what constitutes uniqueness. For example, whether the implementation considers the identifiers to be case-sensitive, or whether the identifiers are file system paths to a header file, and if so, how a hierarchical file system path is delimited.
19654 To maximize the portability of `#include` directives across compilers, guidance is to:
19656 * use case-sensitivity for the header identifier, matching how the header is defined by the standard, specification, implementation, or file that provides the header.
19657 * when the header identifier is a hierarchical file path, use forward-slash `/` to delimit path components as this is the most widely-accepted path-delimiting character.
19659 ##### Example
19661     // good examples
19662     #include <vector>
19663     #include <string>
19664     #include "util/util.h"
19665     
19666     // bad examples
19667     #include <VECTOR>        // bad: the standard library defines a header identified as <vector>, not <VECTOR>
19668     #include <String>        // bad: the standard library defines a header identified as <string>, not <String>
19669     #include "Util/Util.H"   // bad: the header file exists on the file system as "util/util.h"
19670     #include "util\util.h"   // bad: may not work if the implementation interprets `\u` as an escape sequence, or where '\' is not a valid path separator
19672 ##### Enforcement
19674 It is only possible to enforce on implementations where header identifiers are case-sensitive and which only support `/` as a file path delimiter.
19676 ### <a name="Rs-namespace"></a>SF.20: Use `namespace`s to express logical structure
19678 ##### Reason
19680  ???
19682 ##### Example
19684     ???
19686 ##### Enforcement
19690 ### <a name="Rs-unnamed"></a>SF.21: Don't use an unnamed (anonymous) namespace in a header
19692 ##### Reason
19694 It is almost always a bug to mention an unnamed namespace in a header file.
19696 ##### Example
19698     // file foo.h:
19699     namespace
19700     {
19701         const double x = 1.234;  // bad
19703         double foo(double y)     // bad
19704         {
19705             return y + x;
19706         }
19707     }
19709     namespace Foo
19710     {
19711         const double x = 1.234; // good
19713         inline double foo(double y)        // good
19714         {
19715             return y + x;
19716         }
19717     }
19719 ##### Enforcement
19721 * Flag any use of an anonymous namespace in a header file.
19723 ### <a name="Rs-unnamed2"></a>SF.22: Use an unnamed (anonymous) namespace for all internal/non-exported entities
19725 ##### Reason
19727 Nothing external can depend on an entity in a nested unnamed namespace.
19728 Consider putting every definition in an implementation source file in an unnamed namespace unless that is defining an "external/exported" entity.
19730 ##### Example; bad
19732     static int f();
19733     int g();
19734     static bool h();
19735     int k();
19737 ##### Example; good
19739     namespace {
19740         int f();
19741         bool h();
19742     }
19743     int g();
19744     int k();
19746 ##### Example
19748 An API class and its members can't live in an unnamed namespace; but any "helper" class or function that is defined in an implementation source file should be at an unnamed namespace scope.
19750     ???
19752 ##### Enforcement
19754 * ???
19756 # <a name="S-stdlib"></a>SL: The Standard Library
19758 Using only the bare language, every task is tedious (in any language).
19759 Using a suitable library any task can be reasonably simple.
19761 The standard library has steadily grown over the years.
19762 Its description in the standard is now larger than that of the language features.
19763 So, it is likely that this library section of the guidelines will eventually grow in size to equal or exceed all the rest.
19765 << ??? We need another level of rule numbering ??? >>
19767 C++ Standard Library component summary:
19769 * [SL.con: Containers](#SS-con)
19770 * [SL.str: String](#SS-string)
19771 * [SL.io: Iostream](#SS-io)
19772 * [SL.regex: Regex](#SS-regex)
19773 * [SL.chrono: Time](#SS-chrono)
19774 * [SL.C: The C Standard Library](#SS-clib)
19776 Standard-library rule summary:
19778 * [SL.1: Use libraries wherever possible](#Rsl-lib)
19779 * [SL.2: Prefer the standard library to other libraries](#Rsl-sl)
19780 * [SL.3: Do not add non-standard entities to namespace `std`](#sl-std)
19781 * [SL.4: Use the standard library in a type-safe manner](#sl-safe)
19782 * ???
19784 ### <a name="Rsl-lib"></a>SL.1:  Use libraries wherever possible
19786 ##### Reason
19788 Save time. Don't re-invent the wheel.
19789 Don't replicate the work of others.
19790 Benefit from other people's work when they make improvements.
19791 Help other people when you make improvements.
19793 ### <a name="Rsl-sl"></a>SL.2: Prefer the standard library to other libraries
19795 ##### Reason
19797 More people know the standard library.
19798 It is more likely to be stable, well-maintained, and widely available than your own code or most other libraries.
19801 ### <a name="sl-std"></a>SL.3: Do not add non-standard entities to namespace `std`
19803 ##### Reason
19805 Adding to `std` might change the meaning of otherwise standards conforming code.
19806 Additions to `std` might clash with future versions of the standard.
19808 ##### Example
19810     namespace std { // BAD: violates standard
19812     class My_vector {
19813         //     . . .
19814     };
19816     }
19818     namespace Foo { // GOOD: user namespace is allowed
19820     class My_vector {
19821         //     . . .
19822     };
19824     }
19826 ##### Enforcement
19828 Possible, but messy and likely to cause problems with platforms.
19830 ### <a name="sl-safe"></a>SL.4: Use the standard library in a type-safe manner
19832 ##### Reason
19834 Because, obviously, breaking this rule can lead to undefined behavior, memory corruption, and all kinds of other bad errors.
19836 ##### Note
19838 This is a semi-philosophical meta-rule, which needs many supporting concrete rules.
19839 We need it as an umbrella for the more specific rules.
19841 Summary of more specific rules:
19843 * [SL.4: Use the standard library in a type-safe manner](#sl-safe)
19846 ## <a name="SS-con"></a>SL.con: Containers
19850 Container rule summary:
19852 * [SL.con.1: Prefer using STL `array` or `vector` instead of a C array](#Rsl-arrays)
19853 * [SL.con.2: Prefer using STL `vector` by default unless you have a reason to use a different container](#Rsl-vector)
19854 * [SL.con.3: Avoid bounds errors](#Rsl-bounds)
19855 * [SL.con.4: don't use `memset` or `memcpy` for arguments that are not trivially-copyable](#Rsl-copy)
19857 ### <a name="Rsl-arrays"></a>SL.con.1: Prefer using STL `array` or `vector` instead of a C array
19859 ##### Reason
19861 C arrays are less safe, and have no advantages over `array` and `vector`.
19862 For a fixed-length array, use `std::array`, which does not degenerate to a pointer when passed to a function and does know its size.
19863 Also, like a built-in array, a stack-allocated `std::array` keeps its elements on the stack.
19864 For a variable-length array, use `std::vector`, which additionally can change its size and handles memory allocation.
19866 ##### Example
19868     int v[SIZE];                        // BAD
19870     std::array<int, SIZE> w;            // ok
19872 ##### Example
19874     int* v = new int[initial_size];     // BAD, owning raw pointer
19875     delete[] v;                         // BAD, manual delete
19877     std::vector<int> w(initial_size);   // ok
19879 ##### Note
19881 Use `gsl::span` for non-owning references into a container.
19883 ##### Note
19885 Comparing the performance of a fixed-sized array allocated on the stack against a `vector` with its elements on the free store is bogus.
19886 You could just as well compare a `std::array` on the stack against the result of a `malloc()` accessed through a pointer.
19887 For most code, even the difference between stack allocation and free-store allocation doesn't matter, but the convenience and safety of `vector` does.
19888 People working with code for which that difference matters are quite capable of choosing between `array` and `vector`.
19890 ##### Enforcement
19892 * Flag declaration of a C array inside a function or class that also declares an STL container (to avoid excessive noisy warnings on legacy non-STL code). To fix: At least change the C array to a `std::array`.
19894 ### <a name="Rsl-vector"></a>SL.con.2: Prefer using STL `vector` by default unless you have a reason to use a different container
19896 ##### Reason
19898 `vector` and `array` are the only standard containers that offer the following advantages:
19900 * the fastest general-purpose access (random access, including being vectorization-friendly);
19901 * the fastest default access pattern (begin-to-end or end-to-begin is prefetcher-friendly);
19902 * the lowest space overhead (contiguous layout has zero per-element overhead, which is cache-friendly).
19904 Usually you need to add and remove elements from the container, so use `vector` by default; if you don't need to modify the container's size, use `array`.
19906 Even when other containers seem more suited, such as `map` for O(log N) lookup performance or a `list` for efficient insertion in the middle, a `vector` will usually still perform better for containers up to a few KB in size.
19908 ##### Note
19910 `string` should not be used as a container of individual characters. A `string` is a textual string; if you want a container of characters, use `vector</*char_type*/>` or `array</*char_type*/>` instead.
19912 ##### Exceptions
19914 If you have a good reason to use another container, use that instead. For example:
19916 * If `vector` suits your needs but you don't need the container to be variable size, use `array` instead.
19918 * If you want a dictionary-style lookup container that guarantees O(K) or O(log N) lookups, the container will be larger (more than a few KB) and you perform frequent inserts so that the overhead of maintaining a sorted `vector` is infeasible, go ahead and use an `unordered_map` or `map` instead.
19920 ##### Note
19922 To initialize a vector with a number of elements, use `()`-initialization.
19923 To initialize a vector with a list of elements, use `{}`-initialization.
19925     vector<int> v1(20);  // v1 has 20 elements with the value 0 (vector<int>{})
19926     vector<int> v2 {20}; // v2 has 1 element with the value 20
19928 [Prefer the {}-initializer syntax](#Res-list).
19930 ##### Enforcement
19932 * Flag a `vector` whose size never changes after construction (such as because it's `const` or because no non-`const` functions are called on it). To fix: Use an `array` instead.
19934 ### <a name="Rsl-bounds"></a>SL.con.3: Avoid bounds errors
19936 ##### Reason
19938 Read or write beyond an allocated range of elements typically leads to bad errors, wrong results, crashes, and security violations.
19940 ##### Note
19942 The standard-library functions that apply to ranges of elements all have (or could have) bounds-safe overloads that take `span`.
19943 Standard types such as `vector` can be modified to perform bounds-checks under the bounds profile (in a compatible way, such as by adding contracts), or used with `at()`.
19945 Ideally, the in-bounds guarantee should be statically enforced.
19946 For example:
19948 * a range-`for` cannot loop beyond the range of the container to which it is applied
19949 * a `v.begin(),v.end()` is easily determined to be bounds safe
19951 Such loops are as fast as any unchecked/unsafe equivalent.
19953 Often a simple pre-check can eliminate the need for checking of individual indices.
19954 For example
19956 * for `v.begin(),v.begin()+i` the `i` can easily be checked against `v.size()`
19958 Such loops can be much faster than individually checked element accesses.
19960 ##### Example, bad
19962     void f()
19963     {
19964         array<int, 10> a, b;
19965         memset(a.data(), 0, 10);         // BAD, and contains a length error (length = 10 * sizeof(int))
19966         memcmp(a.data(), b.data(), 10);  // BAD, and contains a length error (length = 10 * sizeof(int))
19967     }
19969 Also, `std::array<>::fill()` or `std::fill()` or even an empty initializer are better candidates than `memset()`.
19971 ##### Example, good
19973     void f()
19974     {
19975         array<int, 10> a, b, c{};       // c is initialized to zero
19976         a.fill(0);
19977         fill(b.begin(), b.end(), 0);    // std::fill()
19978         fill(b, 0);                     // std::ranges::fill()
19980         if ( a == b ) {
19981           // ...
19982         }
19983     }
19985 ##### Example
19987 If code is using an unmodified standard library, then there are still workarounds that enable use of `std::array` and `std::vector` in a bounds-safe manner. Code can call the `.at()` member function on each class, which will result in an `std::out_of_range` exception being thrown. Alternatively, code can call the `at()` free function, which will result in fail-fast (or a customized action) on a bounds violation.
19989     void f(std::vector<int>& v, std::array<int, 12> a, int i)
19990     {
19991         v[0] = a[0];        // BAD
19992         v.at(0) = a[0];     // OK (alternative 1)
19993         at(v, 0) = a[0];    // OK (alternative 2)
19995         v.at(0) = a[i];     // BAD
19996         v.at(0) = a.at(i);  // OK (alternative 1)
19997         v.at(0) = at(a, i); // OK (alternative 2)
19998     }
20000 ##### Enforcement
20002 * Issue a diagnostic for any call to a standard-library function that is not bounds-checked.
20003 ??? insert link to a list of banned functions
20005 This rule is part of the [bounds profile](#SS-bounds).
20008 ### <a name="Rsl-copy"></a>SL.con.4: don't use `memset` or `memcpy` for arguments that are not trivially-copyable
20010 ##### Reason
20012 Doing so messes the semantics of the objects (e.g., by overwriting a `vptr`).
20014 ##### Note
20016 Similarly for (w)memset, (w)memcpy, (w)memmove, and (w)memcmp
20018 ##### Example
20020     struct base {
20021         virtual void update() = 0;
20022     };
20024     struct derived : public base {
20025         void update() override {}
20026     };
20029     void f(derived& a, derived& b) // goodbye v-tables
20030     {
20031         memset(&a, 0, sizeof(derived));
20032         memcpy(&a, &b, sizeof(derived));
20033         memcmp(&a, &b, sizeof(derived));
20034     }
20036 Instead, define proper default initialization, copy, and comparison functions
20038     void g(derived& a, derived& b)
20039     {
20040         a = {};    // default initialize
20041         b = a;     // copy
20042         if (a == b) do_something(a, b);
20043     }
20045 ##### Enforcement
20047 * Flag the use of those functions for types that are not trivially copyable
20049 **TODO Notes**:
20051 * Impact on the standard library will require close coordination with WG21, if only to ensure compatibility even if never standardized.
20052 * We are considering specifying bounds-safe overloads for stdlib (especially C stdlib) functions like `memcmp` and shipping them in the GSL.
20053 * For existing stdlib functions and types like `vector` that are not fully bounds-checked, the goal is for these features to be bounds-checked when called from code with the bounds profile on, and unchecked when called from legacy code, possibly using contracts (concurrently being proposed by several WG21 members).
20057 ## <a name="SS-string"></a>SL.str: String
20059 Text manipulation is a huge topic.
20060 `std::string` doesn't cover all of it.
20061 This section primarily tries to clarify `std::string`'s relation to `char*`, `zstring`, `string_view`, and `gsl::span<char>`.
20062 The important issue of non-ASCII character sets and encodings (e.g., `wchar_t`, Unicode, and UTF-8) will be covered elsewhere.
20064 **See also**: [regular expressions](#SS-regex)
20066 Here, we use "sequence of characters" or "string" to refer to a sequence of characters meant to be read as text (somehow, eventually).
20067 We don't consider ???
20069 String summary:
20071 * [SL.str.1: Use `std::string` to own character sequences](#Rstr-string)
20072 * [SL.str.2: Use `std::string_view` or `gsl::span<char>` to refer to character sequences](#Rstr-view)
20073 * [SL.str.3: Use `zstring` or `czstring` to refer to a C-style, zero-terminated, sequence of characters](#Rstr-zstring)
20074 * [SL.str.4: Use `char*` to refer to a single character](#Rstr-char*)
20075 * [SL.str.5: Use `std::byte` to refer to byte values that do not necessarily represent characters](#Rstr-byte)
20077 * [SL.str.10: Use `std::string` when you need to perform locale-sensitive string operations](#Rstr-locale)
20078 * [SL.str.11: Use `gsl::span<char>` rather than `std::string_view` when you need to mutate a string](#Rstr-span)
20079 * [SL.str.12: Use the `s` suffix for string literals meant to be standard-library `string`s](#Rstr-s)
20081 **See also**:
20083 * [F.24 span](#Rf-range)
20084 * [F.25 zstring](#Rf-zstring)
20087 ### <a name="Rstr-string"></a>SL.str.1: Use `std::string` to own character sequences
20089 ##### Reason
20091 `string` correctly handles allocation, ownership, copying, gradual expansion, and offers a variety of useful operations.
20093 ##### Example
20095     vector<string> read_until(const string& terminator)
20096     {
20097         vector<string> res;
20098         for (string s; cin >> s && s != terminator; ) // read a word
20099             res.push_back(s);
20100         return res;
20101     }
20103 Note how `>>` and `!=` are provided for `string` (as examples of useful operations) and there are no explicit
20104 allocations, deallocations, or range checks (`string` takes care of those).
20106 In C++17, we might use `string_view` as the argument, rather than `const string&` to allow more flexibility to callers:
20108     vector<string> read_until(string_view terminator)   // C++17
20109     {
20110         vector<string> res;
20111         for (string s; cin >> s && s != terminator; ) // read a word
20112             res.push_back(s);
20113         return res;
20114     }
20116 ##### Example, bad
20118 Don't use C-style strings for operations that require non-trivial memory management
20120     char* cat(const char* s1, const char* s2)   // beware!
20121         // return s1 + '.' + s2
20122     {
20123         int l1 = strlen(s1);
20124         int l2 = strlen(s2);
20125         char* p = (char*) malloc(l1 + l2 + 2);
20126         strcpy(p, s1, l1);
20127         p[l1] = '.';
20128         strcpy(p + l1 + 1, s2, l2);
20129         p[l1 + l2 + 1] = 0;
20130         return p;
20131     }
20133 Did we get that right?
20134 Will the caller remember to `free()` the returned pointer?
20135 Will this code pass a security review?
20137 ##### Note
20139 Do not assume that `string` is slower than lower-level techniques without measurement and remember that not all code is performance critical.
20140 [Don't optimize prematurely](#Rper-Knuth)
20142 ##### Enforcement
20146 ### <a name="Rstr-view"></a>SL.str.2: Use `std::string_view` or `gsl::span<char>` to refer to character sequences
20148 ##### Reason
20150 `std::string_view` or `gsl::span<char>` provides simple and (potentially) safe access to character sequences independently of how
20151 those sequences are allocated and stored.
20153 ##### Example
20155     vector<string> read_until(string_view terminator);
20157     void user(zstring p, const string& s, string_view ss)
20158     {
20159         auto v1 = read_until(p);
20160         auto v2 = read_until(s);
20161         auto v3 = read_until(ss);
20162         // ...
20163     }
20165 ##### Note
20167 `std::string_view` (C++17) is read-only.
20169 ##### Enforcement
20173 ### <a name="Rstr-zstring"></a>SL.str.3: Use `zstring` or `czstring` to refer to a C-style, zero-terminated, sequence of characters
20175 ##### Reason
20177 Readability.
20178 Statement of intent.
20179 A plain `char*` can be a pointer to a single character, a pointer to an array of characters, a pointer to a C-style (zero-terminated) string, or even to a small integer.
20180 Distinguishing these alternatives prevents misunderstandings and bugs.
20182 ##### Example
20184     void f1(const char* s); // s is probably a string
20186 All we know is that it is supposed to be the nullptr or point to at least one character
20188     void f1(zstring s);     // s is a C-style string or the nullptr
20189     void f1(czstring s);    // s is a C-style string constant or the nullptr
20190     void f1(std::byte* s);  // s is a pointer to a byte (C++17)
20192 ##### Note
20194 Don't convert a C-style string to `string` unless there is a reason to.
20196 ##### Note
20198 Like any other "plain pointer", a `zstring` should not represent ownership.
20200 ##### Note
20202 There are billions of lines of C++ "out there", most use `char*` and `const char*` without documenting intent.
20203 They are used in a wide variety of ways, including to represent ownership and as generic pointers to memory (instead of `void*`).
20204 It is hard to separate these uses, so this guideline is hard to follow.
20205 This is one of the major sources of bugs in C and C++ programs, so it is worthwhile to follow this guideline wherever feasible.
20207 ##### Enforcement
20209 * Flag uses of `[]` on a `char*`
20210 * Flag uses of `delete` on a `char*`
20211 * Flag uses of `free()` on a `char*`
20213 ### <a name="Rstr-char*"></a>SL.str.4: Use `char*` to refer to a single character
20215 ##### Reason
20217 The variety of uses of `char*` in current code is a major source of errors.
20219 ##### Example, bad
20221     char arr[] = {'a', 'b', 'c'};
20223     void print(const char* p)
20224     {
20225         cout << p << '\n';
20226     }
20228     void use()
20229     {
20230         print(arr);   // run-time error; potentially very bad
20231     }
20233 The array `arr` is not a C-style string because it is not zero-terminated.
20235 ##### Alternative
20237 See [`zstring`](#Rstr-zstring), [`string`](#Rstr-string), and [`string_view`](#Rstr-view).
20239 ##### Enforcement
20241 * Flag uses of `[]` on a `char*`
20243 ### <a name="Rstr-byte"></a>SL.str.5: Use `std::byte` to refer to byte values that do not necessarily represent characters
20245 ##### Reason
20247 Use of `char*` to represent a pointer to something that is not necessarily a character causes confusion
20248 and disables valuable optimizations.
20250 ##### Example
20252     ???
20254 ##### Note
20256 C++17
20258 ##### Enforcement
20263 ### <a name="Rstr-locale"></a>SL.str.10: Use `std::string` when you need to perform locale-sensitive string operations
20265 ##### Reason
20267 `std::string` supports standard-library [`locale` facilities](#Rstr-locale)
20269 ##### Example
20271     ???
20273 ##### Note
20277 ##### Enforcement
20281 ### <a name="Rstr-span"></a>SL.str.11: Use `gsl::span<char>` rather than `std::string_view` when you need to mutate a string
20283 ##### Reason
20285 `std::string_view` is read-only.
20287 ##### Example
20291 ##### Note
20295 ##### Enforcement
20297 The compiler will flag attempts to write to a `string_view`.
20299 ### <a name="Rstr-s"></a>SL.str.12: Use the `s` suffix for string literals meant to be standard-library `string`s
20301 ##### Reason
20303 Direct expression of an idea minimizes mistakes.
20305 ##### Example
20307     auto pp1 = make_pair("Tokyo", 9.00);         // {C-style string,double} intended?
20308     pair<string, double> pp2 = {"Tokyo", 9.00};  // a bit verbose
20309     auto pp3 = make_pair("Tokyo"s, 9.00);        // {std::string,double}    // C++14
20310     pair pp4 = {"Tokyo"s, 9.00};                 // {std::string,double}    // C++17
20314 ##### Enforcement
20319 ## <a name="SS-io"></a>SL.io: Iostream
20321 `iostream`s is a type safe, extensible, formatted and unformatted I/O library for streaming I/O.
20322 It supports multiple (and user extensible) buffering strategies and multiple locales.
20323 It can be used for conventional I/O, reading and writing to memory (string streams),
20324 and user-defined extensions, such as streaming across networks (asio: not yet standardized).
20326 Iostream rule summary:
20328 * [SL.io.1: Use character-level input only when you have to](#Rio-low)
20329 * [SL.io.2: When reading, always consider ill-formed input](#Rio-validate)
20330 * [SL.io.3: Prefer iostreams for I/O](#Rio-streams)
20331 * [SL.io.10: Unless you use `printf`-family functions call `ios_base::sync_with_stdio(false)`](#Rio-sync)
20332 * [SL.io.50: Avoid `endl`](#Rio-endl)
20333 * [???](#???)
20335 ### <a name="Rio-low"></a>SL.io.1: Use character-level input only when you have to
20337 ##### Reason
20339 Unless you genuinely just deal with individual characters, using character-level input leads to the user code performing potentially error-prone
20340 and potentially inefficient composition of tokens out of characters.
20342 ##### Example
20344     char c;
20345     char buf[128];
20346     int i = 0;
20347     while (cin.get(c) && !isspace(c) && i < 128)
20348         buf[i++] = c;
20349     if (i == 128) {
20350         // ... handle too long string ....
20351     }
20353 Better (much simpler and probably faster):
20355     string s;
20356     s.reserve(128);
20357     cin >> s;
20359 and the `reserve(128)` is probably not worthwhile.
20361 ##### Enforcement
20366 ### <a name="Rio-validate"></a>SL.io.2: When reading, always consider ill-formed input
20368 ##### Reason
20370 Errors are typically best handled as soon as possible.
20371 If input isn't validated, every function must be written to cope with bad data (and that is not practical).
20373 ##### Example
20375     ???
20377 ##### Enforcement
20381 ### <a name="Rio-streams"></a>SL.io.3: Prefer `iostream`s for I/O
20383 ##### Reason
20385 `iostream`s are safe, flexible, and extensible.
20387 ##### Example
20389     // write a complex number:
20390     complex<double> z{ 3, 4 };
20391     cout << z << '\n';
20393 `complex` is a user-defined type and its I/O is defined without modifying the `iostream` library.
20395 ##### Example
20397     // read a file of complex numbers:
20398     for (complex<double> z; cin >> z; )
20399         v.push_back(z);
20401 ##### Exception
20403 ??? performance ???
20405 ##### Discussion: `iostream`s vs. the `printf()` family
20407 It is often (and often correctly) pointed out that the `printf()` family has two advantages compared to `iostream`s:
20408 flexibility of formatting and performance.
20409 This has to be weighed against `iostream`s advantages of extensibility to handle user-defined types, resilience against security violations,
20410 implicit memory management, and `locale` handling.
20412 If you need I/O performance, you can almost always do better than `printf()`.
20414 `gets()`, `scanf()` using `%s`, and `printf()` using `%s` are security hazards (vulnerable to buffer overflow and generally error-prone).
20415 C11 defines some "optional extensions" that do extra checking of their arguments.
20416 If present in your C library, `gets_s()`, `scanf_s()`, and `printf_s()` might be safer alternatives, but they are still not type safe.
20418 ##### Enforcement
20420 Optionally flag `<cstdio>` and `<stdio.h>`.
20422 ### <a name="Rio-sync"></a>SL.io.10: Unless you use `printf`-family functions call `ios_base::sync_with_stdio(false)`
20424 ##### Reason
20426 Synchronizing `iostreams` with `printf-style` I/O can be costly.
20427 `cin` and `cout` are by default synchronized with `printf`.
20429 ##### Example
20431     int main()
20432     {
20433         ios_base::sync_with_stdio(false);
20434         // ... use iostreams ...
20435     }
20437 ##### Enforcement
20441 ### <a name="Rio-endl"></a>SL.io.50: Avoid `endl`
20443 ##### Reason
20445 The `endl` manipulator is mostly equivalent to `'\n'` and `"\n"`;
20446 as most commonly used it simply slows down output by doing redundant `flush()`s.
20447 This slowdown can be significant compared to `printf`-style output.
20449 ##### Example
20451     cout << "Hello, World!" << endl;    // two output operations and a flush
20452     cout << "Hello, World!\n";          // one output operation and no flush
20454 ##### Note
20456 For `cin`/`cout` (and equivalent) interaction, there is no reason to flush; that's done automatically.
20457 For writing to a file, there is rarely a need to `flush`.
20459 ##### Note
20461 For string streams (specifically `ostringstream`), the insertion of an `endl` is entirely equivalent
20462 to the insertion of a `'\n'` character, but also in this case, `endl` might be significantly slower.
20464 `endl` does *not* take care of producing a platform specific end-of-line sequence (like `"\r\n"` on
20465 Windows). So for a string stream, `s << endl` just inserts a *single* character, `'\n'`.
20467 ##### Note
20469 Apart from the (occasionally important) issue of performance,
20470 the choice between `'\n'` and `endl` is almost completely aesthetic.
20472 ## <a name="SS-regex"></a>SL.regex: Regex
20474 `<regex>` is the standard C++ regular expression library.
20475 It supports a variety of regular expression pattern conventions.
20477 ## <a name="SS-chrono"></a>SL.chrono: Time
20479 `<chrono>` (defined in namespace `std::chrono`) provides the notions of `time_point` and `duration` together with functions for
20480 outputting time in various units.
20481 It provides clocks for registering `time_points`.
20483 ## <a name="SS-clib"></a>SL.C: The C Standard Library
20487 C Standard Library rule summary:
20489 * [SL.C.1: Don't use setjmp/longjmp](#Rclib-jmp)
20490 * [???](#???)
20491 * [???](#???)
20493 ### <a name="Rclib-jmp"></a>SL.C.1: Don't use setjmp/longjmp
20495 ##### Reason
20497 a `longjmp` ignores destructors, thus invalidating all resource-management strategies relying on RAII
20499 ##### Enforcement
20501 Flag all occurrences of `longjmp`and `setjmp`
20505 # <a name="S-A"></a>A: Architectural ideas
20507 This section contains ideas about higher-level architectural ideas and libraries.
20509 Architectural rule summary:
20511 * [A.1: Separate stable code from less stable code](#Ra-stable)
20512 * [A.2: Express potentially reusable parts as a library](#Ra-lib)
20513 * [A.4: There should be no cycles among libraries](#Ra-dag)
20514 * [???](#???)
20515 * [???](#???)
20516 * [???](#???)
20517 * [???](#???)
20518 * [???](#???)
20519 * [???](#???)
20521 ### <a name="Ra-stable"></a>A.1: Separate stable code from less stable code
20523 Isolating less stable code facilitates its unit testing, interface improvement, refactoring, and eventual deprecation.
20525 ### <a name="Ra-lib"></a>A.2: Express potentially reusable parts as a library
20527 ##### Reason
20529 ##### Note
20531 A library is a collection of declarations and definitions maintained, documented, and shipped together.
20532 A library could be a set of headers (a "header-only library") or a set of headers plus a set of object files.
20533 You can statically or dynamically link a library into a program, or you can `#include` a header-only library.
20536 ### <a name="Ra-dag"></a>A.4: There should be no cycles among libraries
20538 ##### Reason
20540 * A cycle complicates the build process.
20541 * Cycles are hard to understand and might introduce indeterminism (unspecified behavior).
20543 ##### Note
20545 A library can contain cyclic references in the definition of its components.
20546 For example:
20548     ???
20550 However, a library should not depend on another that depends on it.
20553 # <a name="S-not"></a>NR: Non-Rules and myths
20555 This section contains rules and guidelines that are popular somewhere, but that we deliberately don't recommend.
20556 We know perfectly well that there have been times and places where these rules made sense, and we have used them ourselves at times.
20557 However, in the context of the styles of programming we recommend and support with the guidelines, these "non-rules" would do harm.
20559 Even today, there can be contexts where the rules make sense.
20560 For example, lack of suitable tool support can make exceptions unsuitable in hard-real-time systems,
20561 but please don't naïvely trust "common wisdom" (e.g., unsupported statements about "efficiency");
20562 such "wisdom" might be based on decades-old information or experiences from languages with very different properties than C++
20563 (e.g., C or Java).
20565 The positive arguments for alternatives to these non-rules are listed in the rules offered as "Alternatives".
20567 Non-rule summary:
20569 * [NR.1: Don't insist that all declarations should be at the top of a function](#Rnr-top)
20570 * [NR.2: Don't insist to have only a single `return`-statement in a function](#Rnr-single-return)
20571 * [NR.3: Don't avoid exceptions](#Rnr-no-exceptions)
20572 * [NR.4: Don't insist on placing each class definition in its own source file](#Rnr-lots-of-files)
20573 * [NR.5: Don't use two-phase initialization](#Rnr-two-phase-init)
20574 * [NR.6: Don't place all cleanup actions at the end of a function and `goto exit`](#Rnr-goto-exit)
20575 * [NR.7: Don't make all data members `protected`](#Rnr-protected-data)
20576 * ???
20578 ### <a name="Rnr-top"></a>NR.1: Don't insist that all declarations should be at the top of a function
20580 ##### Reason
20582 The "all declarations on top" rule is a legacy of old programming languages that didn't allow initialization of variables and constants after a statement.
20583 This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
20585 ##### Example, bad
20587     int use(int x)
20588     {
20589         int i;
20590         char c;
20591         double d;
20593         // ... some stuff ...
20595         if (x < i) {
20596             // ...
20597             i = f(x, d);
20598         }
20599         if (i < x) {
20600             // ...
20601             i = g(x, c);
20602         }
20603         return i;
20604     }
20606 The larger the distance between the uninitialized variable and its use, the larger the chance of a bug.
20607 Fortunately, compilers catch many "used before set" errors.
20608 Unfortunately, compilers cannot catch all such errors and unfortunately, the bugs aren't always as simple to spot as in this small example.
20611 ##### Alternative
20613 * [Always initialize an object](#Res-always)
20614 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
20616 ### <a name="Rnr-single-return"></a>NR.2: Don't insist to have only a single `return`-statement in a function
20618 ##### Reason
20620 The single-return rule can lead to unnecessarily convoluted code and the introduction of extra state variables.
20621 In particular, the single-return rule makes it harder to concentrate error checking at the top of a function.
20623 ##### Example
20625     template<class T>
20626     //  requires Number<T>
20627     string sign(T x)
20628     {
20629         if (x < 0)
20630             return "negative";
20631         if (x > 0)
20632             return "positive";
20633         return "zero";
20634     }
20636 to use a single return only we would have to do something like
20638     template<class T>
20639     //  requires Number<T>
20640     string sign(T x)        // bad
20641     {
20642         string res;
20643         if (x < 0)
20644             res = "negative";
20645         else if (x > 0)
20646             res = "positive";
20647         else
20648             res = "zero";
20649         return res;
20650     }
20652 This is both longer and likely to be less efficient.
20653 The larger and more complicated the function is, the more painful the workarounds get.
20654 Of course many simple functions will naturally have just one `return` because of their simpler inherent logic.
20656 ##### Example
20658     int index(const char* p)
20659     {
20660         if (!p) return -1;  // error indicator: alternatively "throw nullptr_error{}"
20661         // ... do a lookup to find the index for p
20662         return i;
20663     }
20665 If we applied the rule, we'd get something like
20667     int index2(const char* p)
20668     {
20669         int i;
20670         if (!p)
20671             i = -1;  // error indicator
20672         else {
20673             // ... do a lookup to find the index for p
20674         }
20675         return i;
20676     }
20678 Note that we (deliberately) violated the rule against uninitialized variables because this style commonly leads to that.
20679 Also, this style is a temptation to use the [goto exit](#Rnr-goto-exit) non-rule.
20681 ##### Alternative
20683 * Keep functions short and simple
20684 * Feel free to use multiple `return` statements (and to throw exceptions).
20686 ### <a name="Rnr-no-exceptions"></a>NR.3: Don't avoid exceptions
20688 ##### Reason
20690 There seem to be four main reasons given for not using exceptions:
20692 * exceptions are inefficient
20693 * exceptions lead to leaks and errors
20694 * exception performance is not predictable
20695 * the exception-handling run-time support takes up too much space
20697 There is no way we can settle this issue to the satisfaction of everybody.
20698 After all, the discussions about exceptions have been going on for 40+ years.
20699 Some languages cannot be used without exceptions, but others do not support them.
20700 This leads to strong traditions for the use and non-use of exceptions, and to heated debates.
20702 However, we can briefly outline why we consider exceptions the best alternative for general-purpose programming
20703 and in the context of these guidelines.
20704 Simple arguments for and against are often inconclusive.
20705 There are specialized applications where exceptions indeed can be inappropriate
20706 (e.g., hard-real-time systems without support for reliable estimates of the cost of handling an exception).
20708 Consider the major objections to exceptions in turn
20710 * Exceptions are inefficient:
20711 Compared to what?
20712 When comparing make sure that the same set of errors are handled and that they are handled equivalently.
20713 In particular, do not compare a program that immediately terminates on seeing an error to a program
20714 that carefully cleans up resources before logging an error.
20715 Yes, some systems have poor exception handling implementations; sometimes, such implementations force us to use
20716 other error-handling approaches, but that's not a fundamental problem with exceptions.
20717 When using an efficiency argument - in any context - be careful that you have good data that actually provides
20718 insight into the problem under discussion.
20719 * Exceptions lead to leaks and errors.
20720 They do not.
20721 If your program is a rat's nest of pointers without an overall strategy for resource management,
20722 you have a problem whatever you do.
20723 If your system consists of a million lines of such code,
20724 you probably will not be able to use exceptions,
20725 but that's a problem with excessive and undisciplined pointer use, rather than with exceptions.
20726 In our opinion, you need RAII to make exception-based error handling simple and safe -- simpler and safer than alternatives.
20727 * Exception performance is not predictable.
20728 If you are in a hard-real-time system where you must guarantee completion of a task in a given time,
20729 you need tools to back up such guarantees.
20730 As far as we know such tools are not available (at least not to most programmers).
20731 * The exception-handling run-time support takes up too much space.
20732 This can be the case in small (usually embedded) systems.
20733 However, before abandoning exceptions consider what space consistent error-handling using error-codes would require
20734 and what failure to catch an error would cost.
20736 Many, possibly most, problems with exceptions stem from historical needs to interact with messy old code.
20738 The fundamental arguments for the use of exceptions are
20740 * They clearly differentiate between erroneous return and ordinary return
20741 * They cannot be forgotten or ignored
20742 * They can be used systematically
20744 Remember
20746 * Exceptions are for reporting errors (in C++; other languages can have different uses for exceptions).
20747 * Exceptions are not for errors that can be handled locally.
20748 * Don't try to catch every exception in every function (that's tedious, clumsy, and leads to slow code).
20749 * Exceptions are not for errors that require instant termination of a module/system after a non-recoverable error.
20751 ##### Example
20753     ???
20755 ##### Alternative
20757 * [RAII](#Re-raii)
20758 * Contracts/assertions: Use GSL's `Expects` and `Ensures` (until we get language support for contracts)
20760 ### <a name="Rnr-lots-of-files"></a>NR.4: Don't insist on placing each class definition in its own source file
20762 ##### Reason
20764 The resulting number of files from placing each class in its own file are hard to manage and can slow down compilation.
20765 Individual classes are rarely a good logical unit of maintenance and distribution.
20767 ##### Example
20769     ???
20771 ##### Alternative
20773 * Use namespaces containing logically cohesive sets of classes and functions.
20775 ### <a name="Rnr-two-phase-init"></a>NR.5: Don't use two-phase initialization
20777 ##### Reason
20779 Splitting initialization into two leads to weaker invariants,
20780 more complicated code (having to deal with semi-constructed objects),
20781 and errors (when we didn't deal correctly with semi-constructed objects consistently).
20783 ##### Example, bad
20785     // Old conventional style: many problems
20787     class Picture
20788     {
20789         int mx;
20790         int my;
20791         int * data;
20792     public:
20793         // main problem: constructor does not fully construct
20794         Picture(int x, int y)
20795         {
20796             mx = x;         // also bad: assignment in constructor body
20797                             // rather than in member initializer
20798             my = y;
20799             data = nullptr; // also bad: constant initialization in constructor
20800                             // rather than in member initializer
20801         }
20803         ~Picture()
20804         {
20805             Cleanup();
20806         }
20808         // ...
20810         // bad: two-phase initialization
20811         bool Init()
20812         {
20813             // invariant checks
20814             if (mx <= 0 || my <= 0) {
20815                 return false;
20816             }
20817             if (data) {
20818                 return false;
20819             }
20820             data = (int*) malloc(mx*my*sizeof(int));   // also bad: owning raw * and malloc
20821             return data != nullptr;
20822         }
20824         // also bad: no reason to make cleanup a separate function
20825         void Cleanup()
20826         {
20827             if (data) free(data);
20828             data = nullptr;
20829         }
20830     };
20832     Picture picture(100, 0); // not ready-to-use picture here
20833     // this will fail..
20834     if (!picture.Init()) {
20835         puts("Error, invalid picture");
20836     }
20837     // now have an invalid picture object instance.
20839 ##### Example, good
20841     class Picture
20842     {
20843         int mx;
20844         int my;
20845         vector<int> data;
20847         static int check_size(int size)
20848         {
20849             // invariant check
20850             Expects(size > 0);
20851             return size;
20852         }
20854     public:
20855         // even better would be a class for a 2D Size as one single parameter
20856         Picture(int x, int y)
20857             : mx(check_size(x))
20858             , my(check_size(y))
20859             // now we know x and y have a valid size
20860             , data(mx * my) // will throw std::bad_alloc on error
20861         {
20862             // picture is ready-to-use
20863         }
20865         // compiler generated dtor does the job. (also see C.21)
20867         // ...
20868     };
20870     Picture picture1(100, 100);
20871     // picture1 is ready-to-use here...
20873     // not a valid size for y,
20874     // default contract violation behavior will call std::terminate then
20875     Picture picture2(100, 0);
20876     // not reach here...
20878 ##### Alternative
20880 * Always establish a class invariant in a constructor.
20881 * Don't define an object before it is needed.
20883 ### <a name="Rnr-goto-exit"></a>NR.6: Don't place all cleanup actions at the end of a function and `goto exit`
20885 ##### Reason
20887 `goto` is error-prone.
20888 This technique is a pre-exception technique for RAII-like resource and error handling.
20890 ##### Example, bad
20892     void do_something(int n)
20893     {
20894         if (n < 100) goto exit;
20895         // ...
20896         int* p = (int*) malloc(n);
20897         // ...
20898         if (some_error) goto_exit;
20899         // ...
20900     exit:
20901         free(p);
20902     }
20904 and spot the bug.
20906 ##### Alternative
20908 * Use exceptions and [RAII](#Re-raii)
20909 * for non-RAII resources, use [`finally`](#Re-finally).
20911 ### <a name="Rnr-protected-data"></a>NR.7: Don't make all data members `protected`
20913 ##### Reason
20915 `protected` data is a source of errors.
20916 `protected` data can be manipulated from an unbounded amount of code in various places.
20917 `protected` data is the class hierarchy equivalent to global data.
20919 ##### Example
20921     ???
20923 ##### Alternative
20925 * [Make member data `public` or (preferably) `private`](#Rh-protected)
20928 # <a name="S-references"></a>RF: References
20930 Many coding standards, rules, and guidelines have been written for C++, and especially for specialized uses of C++.
20931 Many
20933 * focus on lower-level issues, such as the spelling of identifiers
20934 * are written by C++ novices
20935 * see "stopping programmers from doing unusual things" as their primary aim
20936 * aim at portability across many compilers (some 10 years old)
20937 * are written to preserve decades old code bases
20938 * aim at a single application domain
20939 * are downright counterproductive
20940 * are ignored (must be ignored by programmers to get their work done well)
20942 A bad coding standard is worse than no coding standard.
20943 However an appropriate set of guidelines are much better than no standards: "Form is liberating."
20945 Why can't we just have a language that allows all we want and disallows all we don't want ("a perfect language")?
20946 Fundamentally, because affordable languages (and their tool chains) also serve people with needs that differ from yours and serve more needs than you have today.
20947 Also, your needs change over time and a general-purpose language is needed to allow you to adapt.
20948 A language that is ideal for today would be overly restrictive tomorrow.
20950 Coding guidelines adapt the use of a language to specific needs.
20951 Thus, there cannot be a single coding style for everybody.
20952 We expect different organizations to provide additions, typically with more restrictions and firmer style rules.
20954 Reference sections:
20956 * [RF.rules: Coding rules](#SS-rules)
20957 * [RF.books: Books with coding guidelines](#SS-books)
20958 * [RF.C++: C++ Programming (C++11/C++14/C++17)](#SS-Cplusplus)
20959 * [RF.web: Websites](#SS-web)
20960 * [RS.video: Videos about "modern C++"](#SS-vid)
20961 * [RF.man: Manuals](#SS-man)
20962 * [RF.core: Core Guidelines materials](#SS-core)
20964 ## <a name="SS-rules"></a>RF.rules: Coding rules
20966 * [AUTOSAR Guidelines for the use of the C++14 language in critical and safety-related systems v17.10](https://web.archive.org/web/20220629085753/https://www.autosar.org/fileadmin/user_upload/standards/adaptive/17-03/AUTOSAR_RS_CPP14Guidelines.pdf)
20967 * [Boost Library Requirements and Guidelines](http://www.boost.org/development/requirements.html).
20968   ???.
20969 * [Bloomberg: BDE C++ Coding](https://github.com/bloomberg/bde/wiki/CodingStandards.pdf).
20970   Has a strong emphasis on code organization and layout.
20971 * Facebook: ???
20972 * [GCC Coding Conventions](https://gcc.gnu.org/codingconventions.html).
20973   C++03 and (reasonably) a bit backwards looking.
20974 * [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html).
20975   Geared toward C++17 and (also) older code bases. Google experts are now actively collaborating here on helping to improve these Guidelines, and hopefully to merge efforts so these can be a modern common set they could also recommend.
20976 * [JSF++: JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS](http://www.stroustrup.com/JSF-AV-rules.pdf).
20977   Document Number 2RDU00001 Rev C. December 2005.
20978   For flight control software.
20979   For hard-real-time.
20980   This means that it is necessarily very restrictive ("if the program fails somebody dies").
20981   For example, no free store allocation or deallocation is allowed to occur after the plane takes off (no memory overflow and no fragmentation allowed).
20982   No exception is allowed to be used (because there was no available tool for guaranteeing that an exception would be handled within a fixed short time).
20983   Libraries used have to have been approved for mission critical applications.
20984   Any similarities to this set of guidelines are unsurprising because Bjarne Stroustrup was an author of JSF++.
20985   Recommended, but note its very specific focus.
20986 * [MISRA C++ 2008: Guidelines for the use of the C++ language in critical systems](https://www.misra.org.uk/Buyonline/tabid/58/Default.aspx).
20987 * [Using C++ in Mozilla Code](https://firefox-source-docs.mozilla.org/code-quality/coding-style/using_cxx_in_firefox_code.html).
20988   As the name indicates, this aims for portability across many (old) compilers.
20989   As such, it is restrictive.
20990 * [Geosoft.no: C++ Programming Style Guidelines](http://geosoft.no/development/cppstyle.html).
20991   ???.
20992 * [Possibility.com: C++ Coding Standard](http://www.possibility.com/Cpp/CppCodingStandard.html).
20993   ???.
20994 * [SEI CERT: Secure C++ Coding Standard](https://wiki.sei.cmu.edu/confluence/x/Wnw-BQ).
20995   A very nicely done set of rules (with examples and rationales) done for security-sensitive code.
20996   Many of their rules apply generally.
20997 * [High Integrity C++ Coding Standard](http://www.codingstandard.com/).
20998 * [llvm](http://llvm.org/docs/CodingStandards.html).
20999   Somewhat brief, based on C++14, and (not unreasonably) adjusted to its domain.
21000 * ???
21002 ## <a name="SS-books"></a>RF.books: Books with coding guidelines
21004 * [Meyers96](#Meyers96) Scott Meyers: *More Effective C++*. Addison-Wesley 1996.
21005 * [Meyers97](#Meyers97) Scott Meyers: *Effective C++, Second Edition*. Addison-Wesley 1997.
21006 * [Meyers01](#Meyers01) Scott Meyers: *Effective STL*. Addison-Wesley 2001.
21007 * [Meyers05](#Meyers05) Scott Meyers: *Effective C++, Third Edition*. Addison-Wesley 2005.
21008 * [Meyers15](#Meyers15) Scott Meyers: *Effective Modern C++*. O'Reilly 2015.
21009 * [SuttAlex05](#SuttAlex05) Sutter and Alexandrescu: *C++ Coding Standards*. Addison-Wesley 2005. More a set of meta-rules than a set of rules. Pre-C++11.
21010 * [Stroustrup05](#Stroustrup05) Bjarne Stroustrup: [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
21011   LCSD05. October 2005.
21012 * [Stroustrup14](#Stroustrup05) Stroustrup: [A Tour of C++](http://www.stroustrup.com/Tour.html).
21013   Addison Wesley 2014.
21014   Each chapter ends with an advice section consisting of a set of recommendations.
21015 * [Stroustrup13](#Stroustrup13) Stroustrup: [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html).
21016   Addison Wesley 2013.
21017   Each chapter ends with an advice section consisting of a set of recommendations.
21018 * Stroustrup: [Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
21019   for [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
21020   Mostly low-level naming and layout rules.
21021   Primarily a teaching tool.
21023 ## <a name="SS-Cplusplus"></a>RF.C++: C++ Programming (C++11/C++14)
21025 * [TC++PL4](http://www.stroustrup.com/4th.html):
21026 A thorough description of the C++ language and standard libraries for experienced programmers.
21027 * [Tour++](http://www.stroustrup.com/Tour.html):
21028 An overview of the C++ language and standard libraries for experienced programmers.
21029 * [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html):
21030 A textbook for beginners and relative novices.
21032 ## <a name="SS-web"></a>RF.web: Websites
21034 * [isocpp.org](https://isocpp.org)
21035 * [Bjarne Stroustrup's home pages](http://www.stroustrup.com)
21036 * [WG21](http://www.open-std.org/jtc1/sc22/wg21/)
21037 * [Boost](http://www.boost.org)<a name="Boost"></a>
21038 * [Adobe open source](https://opensource.adobe.com/)
21039 * [Poco libraries](http://pocoproject.org/)
21040 * Sutter's Mill?
21041 * ???
21043 ## <a name="SS-vid"></a>RS.video: Videos about "modern C++"
21045 * Bjarne Stroustrup: [C++11 Style](http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style). 2012.
21046 * Bjarne Stroustrup: [The Essence of C++: With Examples in C++84, C++98, C++11, and C++14](http://channel9.msdn.com/Events/GoingNative/2013/Opening-Keynote-Bjarne-Stroustrup). 2013
21047 * All the talks from [CppCon '14](https://isocpp.org/blog/2014/11/cppcon-videos-c9)
21048 * Bjarne Stroustrup: [The essence of C++](https://www.youtube.com/watch?v=86xWVb4XIyE) at the University of Edinburgh. 2014.
21049 * Bjarne Stroustrup: [The Evolution of C++ Past, Present and Future](https://www.youtube.com/watch?v=_wzc7a3McOs). CppCon 2016 keynote.
21050 * Bjarne Stroustrup: [Make Simple Tasks Simple!](https://www.youtube.com/watch?v=nesCaocNjtQ). CppCon 2014 keynote.
21051 * Bjarne Stroustrup: [Writing Good C++14](https://www.youtube.com/watch?v=1OEu9C51K2A). CppCon 2015 keynote about the Core Guidelines.
21052 * Herb Sutter: [Writing Good C++14... By Default](https://www.youtube.com/watch?v=hEx5DNLWGgA). CppCon 2015 keynote about the Core Guidelines.
21053 * CppCon 15
21054 * ??? C++ Next
21055 * ??? Meting C++
21056 * ??? more ???
21058 ## <a name="SS-man"></a>RF.man: Manuals
21060 * ISO C++ Standard C++11.
21061 * ISO C++ Standard C++14.
21062 * [ISO C++ Standard C++17](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4606.pdf). Committee Draft.
21063 * [Palo Alto "Concepts" TR](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3351.pdf).
21064 * [ISO C++ Concepts TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
21065 * [WG21 Ranges report](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf). Draft.
21068 ## <a name="SS-core"></a>RF.core: Core Guidelines materials
21070 This section contains materials that have been useful for presenting the core guidelines and the ideas behind them:
21072 * [Our documents directory](https://github.com/isocpp/CppCoreGuidelines/tree/master/docs)
21073 * Stroustrup, Sutter, and Dos Reis: [A brief introduction to C++'s model for type- and resource-safety](http://www.stroustrup.com/resource-model.pdf). A paper with lots of examples.
21074 * Sergey Zubkov: [a Core Guidelines talk](https://www.youtube.com/watch?v=DyLwdl_6vmU)
21075 and here are the [slides](http://2017.cppconf.ru/talks/sergey-zubkov). In Russian. 2017.
21076 * Neil MacIntosh: [The Guideline Support Library: One Year Later](https://www.youtube.com/watch?v=_GhNnCuaEjo). CppCon 2016.
21077 * Bjarne Stroustrup: [Writing Good C++14](https://www.youtube.com/watch?v=1OEu9C51K2A). CppCon 2015 keynote.
21078 * Herb Sutter: [Writing Good C++14... By Default](https://www.youtube.com/watch?v=hEx5DNLWGgA). CppCon 2015 keynote.
21079 * Peter Sommerlad: [C++ Core Guidelines - Modernize your C++ Code Base](https://www.youtube.com/watch?v=fQ926v4ZzAM). ACCU 2017.
21080 * Bjarne Stroustrup: [No Littering!](https://www.youtube.com/watch?v=01zI9kV4h8c). Bay Area ACCU 2016.
21081 It gives some idea of the ambition level for the Core Guidelines.
21083 Note that slides for CppCon presentations are available (links with the posted videos).
21085 Contributions to this list would be most welcome.
21087 ## <a name="SS-ack"></a>Acknowledgements
21089 Thanks to the many people who contributed rules, suggestions, supporting information, references, etc.:
21091 * Peter Juhl
21092 * Neil MacIntosh
21093 * Axel Naumann
21094 * Andrew Pardoe
21095 * Gabriel Dos Reis
21096 * Zhuang, Jiangang (Jeff)
21097 * Sergey Zubkov
21099 and see the contributor list on the github.
21101 # <a name="S-profile"></a>Pro: Profiles
21103 Ideally, we would follow all of the guidelines.
21104 That would give the cleanest, most regular, least error-prone, and often the fastest code.
21105 Unfortunately, that is usually impossible because we have to fit our code into large code bases and use existing libraries.
21106 Often, such code has been written over decades and does not follow these guidelines.
21107 We must aim for [gradual adoption](#S-modernizing).
21109 Whatever strategy for gradual adoption we adopt, we need to be able to apply sets of related guidelines to address some set
21110 of problems first and leave the rest until later.
21111 A similar idea of "related guidelines" becomes important when some, but not all, guidelines are considered relevant to a code base
21112 or if a set of specialized guidelines is to be applied for a specialized application area.
21113 We call such a set of related guidelines a "profile".
21114 We aim for such a set of guidelines to be coherent so that they together help us reach a specific goal, such as "absence of range errors"
21115 or "static type safety."
21116 Each profile is designed to eliminate a class of errors.
21117 Enforcement of "random" rules in isolation is more likely to be disruptive to a code base than delivering a definite improvement.
21119 A "profile" is a set of deterministic and portably enforceable subset of rules (i.e., restrictions) that are designed to achieve a specific guarantee.
21120 "Deterministic" means they require only local analysis and could be implemented in a compiler (though they don't need to be).
21121 "Portably enforceable" means they are like language rules, so programmers can count on different enforcement tools giving the same answer for the same code.
21123 Code written to be warning-free using such a language profile is considered to conform to the profile.
21124 Conforming code is considered to be safe by construction with regard to the safety properties targeted by that profile.
21125 Conforming code will not be the root cause of errors for that property,
21126 although such errors might be introduced into a program by other code, libraries or the external environment.
21127 A profile might also introduce additional library types to ease conformance and encourage correct code.
21129 Profiles summary:
21131 * [Pro.type: Type safety](#SS-type)
21132 * [Pro.bounds: Bounds safety](#SS-bounds)
21133 * [Pro.lifetime: Lifetime safety](#SS-lifetime)
21135 In the future, we expect to define many more profiles and add more checks to existing profiles.
21136 Candidates include:
21138 * narrowing arithmetic promotions/conversions (likely part of a separate safe-arithmetic profile)
21139 * arithmetic cast from negative floating point to unsigned integral type (ditto)
21140 * selected undefined behavior: Start with Gabriel Dos Reis's UB list developed for the WG21 study group
21141 * selected unspecified behavior: Addressing portability concerns.
21142 * `const` violations: Mostly done by compilers already, but we can catch inappropriate casting and underuse of `const`.
21144 Enabling a profile is implementation defined; typically, it is set in the analysis tool used.
21146 To suppress enforcement of a profile check, place a `suppress` annotation on a language contract. For example:
21148     [[suppress(bounds)]] char* raw_find(char* p, int n, char x)    // find x in p[0]..p[n - 1]
21149     {
21150         // ...
21151     }
21153 Now `raw_find()` can scramble memory to its heart's content.
21154 Obviously, suppression should be very rare.
21156 ## <a name="SS-type"></a>Pro.safety: Type-safety profile
21158 This profile makes it easier to construct code that uses types correctly and avoids inadvertent type punning.
21159 It does so by focusing on removing the primary sources of type violations, including unsafe uses of casts and unions.
21161 For the purposes of this section,
21162 type-safety is defined to be the property that a variable is not used in a way that doesn't obey the rules for the type of its definition.
21163 Memory accessed as a type `T` should not be valid memory that actually contains an object of an unrelated type `U`.
21164 Note that the safety is intended to be complete when combined also with [Bounds safety](#SS-bounds) and [Lifetime safety](#SS-lifetime).
21166 An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic.
21168 Type safety profile summary:
21170 * <a name="Pro-type-avoidcasts"></a>Type.1: [Avoid casts](#Res-casts):
21172   1. <a name="Pro-type-reinterpretcast"></a>Don't use `reinterpret_cast`; A strict version of [Avoid casts](#Res-casts) and [prefer named casts](#Res-casts-named).
21173   2. <a name="Pro-type-arithmeticcast"></a>Don't use `static_cast` for arithmetic types; A strict version of [Avoid casts](#Res-casts) and [prefer named casts](#Res-casts-named).
21174   3. <a name="Pro-type-identitycast"></a>Don't cast between pointer types where the source type and the target type are the same; A strict version of [Avoid casts](#Res-casts).
21175   4. <a name="Pro-type-implicitpointercast"></a>Don't cast between pointer types when the conversion could be implicit; A strict version of [Avoid casts](#Res-casts).
21176 * <a name="Pro-type-downcast"></a>Type.2: Don't use `static_cast` to downcast:
21177 [Use `dynamic_cast` instead](#Rh-dynamic_cast).
21178 * <a name="Pro-type-constcast"></a>Type.3: Don't use `const_cast` to cast away `const` (i.e., at all):
21179 [Don't cast away const](#Res-casts-const).
21180 * <a name="Pro-type-cstylecast"></a>Type.4: Don't use C-style `(T)expression` or functional `T(expression)` casts:
21181 Prefer [construction](#Res-construct) or [named casts](#Res-casts-named) or `T{expression}`.
21182 * <a name="Pro-type-init"></a>Type.5: Don't use a variable before it has been initialized:
21183 [always initialize](#Res-always).
21184 * <a name="Pro-type-memberinit"></a>Type.6: Always initialize a member variable:
21185 [always initialize](#Res-always),
21186 possibly using [default constructors](#Rc-default0) or
21187 [default member initializers](#Rc-in-class-initializer).
21188 * <a name="Pro-type-union"></a>Type.7: Avoid naked union:
21189 [Use `variant` instead](#Ru-naked).
21190 * <a name="Pro-type-varargs"></a>Type.8: Avoid varargs:
21191 [Don't use `va_arg` arguments](#F-varargs).
21193 ##### Impact
21195 With the type-safety profile you can trust that every operation is applied to a valid object.
21196 An exception can be thrown to indicate errors that cannot be detected statically (at compile time).
21197 Note that this type-safety can be complete only if we also have [Bounds safety](#SS-bounds) and [Lifetime safety](#SS-lifetime).
21198 Without those guarantees, a region of memory could be accessed independent of which object, objects, or parts of objects are stored in it.
21201 ## <a name="SS-bounds"></a>Pro.bounds: Bounds safety profile
21203 This profile makes it easier to construct code that operates within the bounds of allocated blocks of memory.
21204 It does so by focusing on removing the primary sources of bounds violations: pointer arithmetic and array indexing.
21205 One of the core features of this profile is to restrict pointers to only refer to single objects, not arrays.
21207 We define bounds-safety to be the property that a program does not use an object to access memory outside of the range that was allocated for it.
21208 Bounds safety is intended to be complete only when combined with [Type safety](#SS-type) and [Lifetime safety](#SS-lifetime),
21209 which cover other unsafe operations that allow bounds violations.
21211 Bounds safety profile summary:
21213 * <a name="Pro-bounds-arithmetic"></a>Bounds.1: Don't use pointer arithmetic. Use `span` instead:
21214 [Pass pointers to single objects (only)](#Ri-array) and [Keep pointer arithmetic simple](#Res-ptr).
21215 * <a name="Pro-bounds-arrayindex"></a>Bounds.2: Only index into arrays using constant expressions:
21216 [Pass pointers to single objects (only)](#Ri-array) and [Keep pointer arithmetic simple](#Res-ptr).
21217 * <a name="Pro-bounds-decay"></a>Bounds.3: No array-to-pointer decay:
21218 [Pass pointers to single objects (only)](#Ri-array) and [Keep pointer arithmetic simple](#Res-ptr).
21219 * <a name="Pro-bounds-stdlib"></a>Bounds.4: Don't use standard-library functions and types that are not bounds-checked:
21220 [Use the standard library in a type-safe manner](#Rsl-bounds).
21222 ##### Impact
21224 Bounds safety implies that access to an object - notably arrays - does not access beyond the object's memory allocation.
21225 This eliminates a large class of insidious and hard-to-find errors, including the (in)famous "buffer overflow" errors.
21226 This closes security loopholes as well as a prominent source of memory corruption (when writing out of bounds).
21227 Even if an out-of-bounds access is "just a read", it can lead to invariant violations (when the accessed isn't of the assumed type)
21228 and "mysterious values."
21231 ## <a name="SS-lifetime"></a>Pro.lifetime: Lifetime safety profile
21233 Accessing through a pointer that doesn't point to anything is a major source of errors,
21234 and very hard to avoid in many traditional C or C++ styles of programming.
21235 For example, a pointer might be uninitialized, the `nullptr`, point beyond the range of an array, or to a deleted object.
21237 [See the current design specification here.](https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/Lifetime.pdf)
21239 Lifetime safety profile summary:
21241 * <a name="Pro-lifetime-invalid-deref"></a>Lifetime.1: Don't dereference a possibly invalid pointer:
21242 [detect or avoid](#Res-deref).
21244 ##### Impact
21246 Once completely enforced through a combination of style rules, static analysis, and library support, this profile
21248 * eliminates one of the major sources of nasty errors in C++
21249 * eliminates a major source of potential security violations
21250 * improves performance by eliminating redundant "paranoia" checks
21251 * increases confidence in correctness of code
21252 * avoids undefined behavior by enforcing a key C++ language rule
21255 # <a name="S-gsl"></a>GSL: Guidelines support library
21257 The GSL is a small library of facilities designed to support this set of guidelines.
21258 Without these facilities, the guidelines would have to be far more restrictive on language details.
21260 The Core Guidelines support library is defined in namespace `gsl` and the names might be aliases for standard library or other well-known library names. Using the (compile-time) indirection through the `gsl` namespace allows for experimentation and for local variants of the support facilities.
21262 The GSL is header only, and can be found at [GSL: Guidelines support library](https://github.com/Microsoft/GSL).
21263 The support library facilities are designed to be extremely lightweight (zero-overhead) so that they impose no overhead compared to using conventional alternatives.
21264 Where desirable, they can be "instrumented" with additional functionality (e.g., checks) for tasks such as debugging.
21266 These Guidelines use types from the standard (e.g., C++17) in addition to ones from the GSL.
21267 For example, we assume a `variant` type, but this is not currently in GSL.
21268 Eventually, use [the one voted into C++17](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0088r3.html).
21270 Some of the GSL types listed below might not be supported in the library you use due to technical reasons such as limitations in the current versions of C++.
21271 Therefore, please consult your GSL documentation to find out more.
21273 For each GSL type below we state an invariant for that type. That invariant holds as long as user code only changes the state of a GSL object using the type's provided member/free functions (i.e., user code does not bypass the type's interface to change the object's value/bits by violating any other Guidelines rule).
21275 Summary of GSL components:
21277 * [GSL.view: Views](#SS-views)
21278 * [GSL.owner: Ownership pointers](#SS-ownership)
21279 * [GSL.assert: Assertions](#SS-assertions)
21280 * [GSL.util: Utilities](#SS-utilities)
21281 * [GSL.concept: Concepts](#SS-gsl-concepts)
21283 We plan for a "ISO C++ standard style" semi-formal specification of the GSL.
21285 We rely on the ISO C++ Standard Library and hope for parts of the GSL to be absorbed into the standard library.
21287 ## <a name="SS-views"></a>GSL.view: Views
21289 These types allow the user to distinguish between owning and non-owning pointers and between pointers to a single object and pointers to the first element of a sequence.
21291 These "views" are never owners.
21293 References are never owners (see [R.4](#Rr-ref)). Note: References have many opportunities to outlive the objects they refer to (returning a local variable by reference, holding a reference to an element of a vector and doing `push_back`, binding to `std::max(x, y + 1)`, etc). The Lifetime safety profile aims to address those things, but even so `owner<T&>` does not make sense and is discouraged.
21295 The names are mostly ISO standard-library style (lower case and underscore):
21297 * `T*`      // The `T*` is not an owner, might be null; assumed to be pointing to a single element.
21298 * `T&`      // The `T&` is not an owner and can never be a "null reference"; references are always bound to objects.
21300 The "raw-pointer" notation (e.g. `int*`) is assumed to have its most common meaning; that is, a pointer points to an object, but does not own it.
21301 Owners should be converted to resource handles (e.g., `unique_ptr` or `vector<T>`) or marked `owner<T*>`.
21303 * `owner<T*>`   // a `T*` that owns the object pointed/referred to; might be `nullptr`.
21305 `owner` is used to mark owning pointers in code that cannot be upgraded to use proper resource handles.
21306 Reasons for that include:
21308 * Cost of conversion.
21309 * The pointer is used with an ABI.
21310 * The pointer is part of the implementation of a resource handle.
21312 An `owner<T>` differs from a resource handle for a `T` by still requiring an explicit `delete`.
21314 An `owner<T>` is assumed to refer to an object on the free store (heap).
21316 If something is not supposed to be `nullptr`, say so:
21318 * `not_null<T>`   // `T` is usually a pointer type (e.g., `not_null<int*>` and `not_null<owner<Foo*>>`) that must not be `nullptr`.
21319   `T` can be any type for which `==nullptr` is meaningful.
21321 * `span<T>`       // `[p:p+n)`, constructor from `{p, q}` and `{p, n}`; `T` is the pointer type
21322 * `span_p<T>`     // `{p, predicate}` `[p:q)` where `q` is the first element for which `predicate(*p)` is true
21324 A `span<T>` refers to zero or more mutable `T`s unless `T` is a `const` type. All accesses to elements of the span, notably via `operator[]`, are guaranteed to be bounds-checked by default.
21326 > Note: GSL's `span` (initially called `array_view`) was proposed for inclusion in the C++ standard library, and was adopted (with changes to its name and interface) except only that `std::span` does not provide for guaranteed bounds checking. Therefore GSL changed `span`'s name and interface to track `std::span` and should be exactly the same as `std::span`, and the only difference should be that GSL `span` is fully bounds-safe by default. If bounds-safety might affect its interface, then those change proposals should be brought back via the ISO C++ committee to keep `gsl::span` interface-compatible with `std::span`. If a future evolution of `std::span` adds bounds checking, `gsl::span` can be removed.
21328 "Pointer arithmetic" is best done within `span`s.
21329 A `char*` that points to more than one `char` but is not a C-style string (e.g., a pointer into an input buffer) should be represented by a `span`.
21331 * `zstring`    // a `char*` supposed to be a C-style string; that is, a zero-terminated sequence of `char` or `nullptr`
21332 * `czstring`   // a `const char*` supposed to be a C-style string; that is, a zero-terminated sequence of `const` `char` or `nullptr`
21334 Logically, those last two aliases are not needed, but we are not always logical, and they make the distinction between a pointer to one `char` and a pointer to a C-style string explicit.
21335 A sequence of characters that is not assumed to be zero-terminated should be a `span<char>`, or if that is impossible because of ABI issues a `char*`, rather than a `zstring`.
21338 Use `not_null<zstring>` for C-style strings that cannot be `nullptr`. ??? Do we need a name for `not_null<zstring>`? or is its ugliness a feature?
21340 ## <a name="SS-ownership"></a>GSL.owner: Ownership pointers
21342 * `unique_ptr<T>`     // unique ownership: `std::unique_ptr<T>`
21343 * `shared_ptr<T>`     // shared ownership: `std::shared_ptr<T>` (a counted pointer)
21344 * `stack_array<T>`    // A stack-allocated array. The number of elements is determined at construction and fixed thereafter. The elements are mutable unless `T` is a `const` type.
21345 * `dyn_array<T>`      // ??? needed ??? A heap-allocated array. The number of elements is determined at construction and fixed thereafter.
21346   The elements are mutable unless `T` is a `const` type. Basically a `span` that allocates and owns its elements.
21348 ## <a name="SS-assertions"></a>GSL.assert: Assertions
21350 * `Expects`     // precondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
21351                 // `Expects(p)` terminates the program unless `p == true`
21352                 // `Expects` is under control of some options (enforcement, error message, alternatives to terminate)
21353 * `Ensures`     // postcondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
21355 These assertions are currently macros (yuck!) and must appear in function definitions (only)
21356 pending standard committee decisions on contracts and assertion syntax.
21357 See [the contract proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf); using the attribute syntax,
21358 for example, `Expects(p)` will become `[[expects: p]]`.
21360 ## <a name="SS-utilities"></a>GSL.util: Utilities
21362 * `finally`        // `finally(f)` makes a `final_action{f}` with a destructor that invokes `f`
21363 * `narrow_cast`    // `narrow_cast<T>(x)` is `static_cast<T>(x)`
21364 * `narrow`         // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` with no signedness promotions, or it throws `narrowing_error` (e.g., `narrow<unsigned>(-42)` throws)
21365 * `[[implicit]]`   // "Marker" to put on single-argument constructors to explicitly make them non-explicit.
21366 * `move_owner`     // `p = move_owner(q)` means `p = q` but ???
21367 * `joining_thread` // a RAII style version of `std::thread` that joins.
21368 * `index`          // a type to use for all container and array indexing (currently an alias for `ptrdiff_t`)
21370 ## <a name="SS-gsl-concepts"></a>GSL.concept: Concepts
21372 These concepts (type predicates) are borrowed from
21373 Andrew Sutton's Origin library,
21374 the Range proposal,
21375 and the ISO WG21 Palo Alto TR.
21376 Many of them are very similar to what became part of the ISO C++ standard in C++20.
21378 * `String`
21379 * `Number`
21380 * `Boolean`
21381 * `Range`              // in C++20, `std::ranges::range`
21382 * `Sortable`           // in C++20, `std::sortable`
21383 * `EqualityComparable` // in C++20, `std::equality_comparable`
21384 * `Convertible`        // in C++20, `std::convertible_to`
21385 * `Common`             // in C++20, `std::common_with`
21386 * `Integral`           // in C++20, `std::integral`
21387 * `SignedIntegral`     // in C++20, `std::signed_integral`
21388 * `SemiRegular`        // in C++20, `std::semiregular`
21389 * `Regular`            // in C++20, `std::regular`
21390 * `TotallyOrdered`     // in C++20, `std::totally_ordered`
21391 * `Function`           // in C++20, `std::invocable`
21392 * `RegularFunction`    // in C++20, `std::regular_invocable`
21393 * `Predicate`          // in C++20, `std::predicate`
21394 * `Relation`           // in C++20, `std::relation`
21395 * ...
21397 ### <a name="SS-gsl-smartptrconcepts"></a>GSL.ptr: Smart pointer concepts
21399 * `Pointer`  // A type with `*`, `->`, `==`, and default construction (default construction is assumed to set the singular "null" value)
21400 * `Unique_pointer`  // A type that matches `Pointer`, is movable, and is not copyable
21401 * `Shared_pointer`   // A type that matches `Pointer`, and is copyable
21403 # <a name="S-naming"></a>NL: Naming and layout suggestions
21405 Consistent naming and layout are helpful.
21406 If for no other reason because it minimizes "my style is better than your style" arguments.
21407 However, there are many, many, different styles around and people are passionate about them (pro and con).
21408 Also, most real-world projects include code from many sources, so standardizing on a single style for all code is often impossible.
21409 After many requests for guidance from users, we present a set of rules that you might use if you have no better ideas, but the real aim is consistency, rather than any particular rule set.
21410 IDEs and tools can help (as well as hinder).
21412 Naming and layout rules:
21414 * [NL.1: Don't say in comments what can be clearly stated in code](#Rl-comments)
21415 * [NL.2: State intent in comments](#Rl-comments-intent)
21416 * [NL.3: Keep comments crisp](#Rl-comments-crisp)
21417 * [NL.4: Maintain a consistent indentation style](#Rl-indent)
21418 * [NL.5: Avoid encoding type information in names](#Rl-name-type)
21419 * [NL.7: Make the length of a name roughly proportional to the length of its scope](#Rl-name-length)
21420 * [NL.8: Use a consistent naming style](#Rl-name)
21421 * [NL.9: Use `ALL_CAPS` for macro names only](#Rl-all-caps)
21422 * [NL.10: Prefer `underscore_style` names](#Rl-camel)
21423 * [NL.11: Make literals readable](#Rl-literals)
21424 * [NL.15: Use spaces sparingly](#Rl-space)
21425 * [NL.16: Use a conventional class member declaration order](#Rl-order)
21426 * [NL.17: Use K&R-derived layout](#Rl-knr)
21427 * [NL.18: Use C++-style declarator layout](#Rl-ptr)
21428 * [NL.19: Avoid names that are easily misread](#Rl-misread)
21429 * [NL.20: Don't place two statements on the same line](#Rl-stmt)
21430 * [NL.21: Declare one name (only) per declaration](#Rl-dcl)
21431 * [NL.25: Don't use `void` as an argument type](#Rl-void)
21432 * [NL.26: Use conventional `const` notation](#Rl-const)
21433 * [NL.27: Use a `.cpp` suffix for code files and `.h` for interface files](#Rl-file-suffix)
21435 Most of these rules are aesthetic and programmers hold strong opinions.
21436 IDEs also tend to have defaults and a range of alternatives.
21437 These rules are suggested defaults to follow unless you have reasons not to.
21439 We have had comments to the effect that naming and layout are so personal and/or arbitrary that we should not try to "legislate" them.
21440 We are not "legislating" (see the previous paragraph).
21441 However, we have had many requests for a set of naming and layout conventions to use when there are no external constraints.
21443 More specific and detailed rules are easier to enforce.
21445 These rules bear a strong resemblance to the recommendations in the [PPP Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
21446 written in support of Stroustrup's [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
21448 ### <a name="Rl-comments"></a>NL.1: Don't say in comments what can be clearly stated in code
21450 ##### Reason
21452 Compilers do not read comments.
21453 Comments are less precise than code.
21454 Comments are not updated as consistently as code.
21456 ##### Example, bad
21458     auto x = m * v1 + vv;   // multiply m with v1 and add the result to vv
21460 ##### Enforcement
21462 Build an AI program that interprets colloquial English text and see if what is said could be better expressed in C++.
21464 ### <a name="Rl-comments-intent"></a>NL.2: State intent in comments
21466 ##### Reason
21468 Code says what is done, not what is supposed to be done. Often intent can be stated more clearly and concisely than the implementation.
21470 ##### Example
21472     void stable_sort(Sortable& c)
21473         // sort c in the order determined by <, keep equal elements (as defined by ==) in
21474         // their original relative order
21475     {
21476         // ... quite a few lines of non-trivial code ...
21477     }
21479 ##### Note
21481 If the comment and the code disagree, both are likely to be wrong.
21483 ### <a name="Rl-comments-crisp"></a>NL.3: Keep comments crisp
21485 ##### Reason
21487 Verbosity slows down understanding and makes the code harder to read by spreading it around in the source file.
21489 ##### Note
21491 Use intelligible English.
21492 I might be fluent in Danish, but most programmers are not; the maintainers of my code might not be.
21493 Avoid SMS lingo and watch your grammar, punctuation, and capitalization.
21494 Aim for professionalism, not "cool."
21496 ##### Enforcement
21498 not possible.
21500 ### <a name="Rl-indent"></a>NL.4: Maintain a consistent indentation style
21502 ##### Reason
21504 Readability. Avoidance of "silly mistakes."
21506 ##### Example, bad
21508     int i;
21509     for (i = 0; i < max; ++i); // bug waiting to happen
21510     if (i == j)
21511         return i;
21513 ##### Note
21515 Always indenting the statement after `if (...)`, `for (...)`, and `while (...)` is usually a good idea:
21517     if (i < 0) error("negative argument");
21519     if (i < 0)
21520         error("negative argument");
21522 ##### Enforcement
21524 Use a tool.
21526 ### <a name="Rl-name-type"></a>NL.5: Avoid encoding type information in names
21528 ##### Rationale
21530 If names reflect types rather than functionality, it becomes hard to change the types used to provide that functionality.
21531 Also, if the type of a variable is changed, code using it will have to be modified.
21532 Minimize unintentional conversions.
21534 ##### Example, bad
21536     void print_int(int i);
21537     void print_string(const char*);
21539     print_int(1);          // repetitive, manual type matching
21540     print_string("xyzzy"); // repetitive, manual type matching
21542 ##### Example, good
21544     void print(int i);
21545     void print(string_view);    // also works on any string-like sequence
21547     print(1);              // clear, automatic type matching
21548     print("xyzzy");        // clear, automatic type matching
21550 ##### Note
21552 Names with types encoded are either verbose or cryptic.
21554     printS  // print a std::string
21555     prints  // print a C-style string
21556     printi  // print an int
21558 Requiring techniques like Hungarian notation to encode a type has been used in untyped languages, but is generally unnecessary and actively harmful in a strongly statically-typed language like C++, because the annotations get out of date (the warts are just like comments and rot just like them) and they interfere with good use of the language (use the same name and overload resolution instead).
21560 ##### Note
21562 Some styles use very general (not type-specific) prefixes to denote the general use of a variable.
21564     auto p = new User();
21565     auto p = make_unique<User>();
21566     // note: "p" is not being used to say "raw pointer to type User,"
21567     //       just generally to say "this is an indirection"
21569     auto cntHits = calc_total_of_hits(/*...*/);
21570     // note: "cnt" is not being used to encode a type,
21571     //       just generally to say "this is a count of something"
21573 This is not harmful and does not fall under this guideline because it does not encode type information.
21575 ##### Note
21577 Some styles distinguish members from local variable, and/or from global variable.
21579     struct S {
21580         int m_;
21581         S(int m) : m_{abs(m)} { }
21582     };
21584 This is not harmful and does not fall under this guideline because it does not encode type information.
21586 ##### Note
21588 Like C++, some styles distinguish types from non-types.
21589 For example, by capitalizing type names, but not the names of functions and variables.
21591     typename<typename T>
21592     class HashTable {   // maps string to T
21593         // ...
21594     };
21596     HashTable<int> index;
21598 This is not harmful and does not fall under this guideline because it does not encode type information.
21600 ### <a name="Rl-name-length"></a>NL.7: Make the length of a name roughly proportional to the length of its scope
21602 **Rationale**: The larger the scope the greater the chance of confusion and of an unintended name clash.
21604 ##### Example
21606     double sqrt(double x);   // return the square root of x; x must be non-negative
21608     int length(const char* p);  // return the number of characters in a zero-terminated C-style string
21610     int length_of_string(const char zero_terminated_array_of_char[])    // bad: verbose
21612     int g;      // bad: global variable with a cryptic name
21614     int open;   // bad: global variable with a short, popular name
21616 The use of `p` for pointer and `x` for a floating-point variable is conventional and non-confusing in a restricted scope.
21618 ##### Enforcement
21622 ### <a name="Rl-name"></a>NL.8: Use a consistent naming style
21624 **Rationale**: Consistency in naming and naming style increases readability.
21626 ##### Note
21628 There are many styles and when you use multiple libraries, you can't follow all their different conventions.
21629 Choose a "house style", but leave "imported" libraries with their original style.
21631 ##### Example
21633 ISO Standard, use lower case only and digits, separate words with underscores:
21635 * `int`
21636 * `vector`
21637 * `my_map`
21639 Avoid identifier names that contain double underscores `__` or that start with an underscore followed by a capital letter (e.g., `_Throws`).
21640 Such identifiers are reserved for the C++ implementation.
21642 ##### Example
21644 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
21645 ISO Standard, but with upper case used for your own types and concepts:
21647 * `int`
21648 * `vector`
21649 * `My_map`
21651 ##### Example
21653 CamelCase: capitalize each word in a multi-word identifier:
21655 * `int`
21656 * `vector`
21657 * `MyMap`
21658 * `myMap`
21660 Some conventions capitalize the first letter, some don't.
21662 ##### Note
21664 Try to be consistent in your use of acronyms and lengths of identifiers:
21666     int mtbf {12};
21667     int mean_time_between_failures {12}; // make up your mind
21669 ##### Enforcement
21671 Would be possible except for the use of libraries with varying conventions.
21673 ### <a name="Rl-all-caps"></a>NL.9: Use `ALL_CAPS` for macro names only
21675 ##### Reason
21677 To avoid confusing macros with names that obey scope and type rules.
21679 ##### Example
21681     void f()
21682     {
21683         const int SIZE{1000};  // Bad, use 'size' instead
21684         int v[SIZE];
21685     }
21687 ##### Note
21689 In particular, this avoids confusing macros with non-macro symbolic constants (see also [Enum.5: Don't use `ALL_CAPS` for enumerators](#Renum-caps))
21691     enum bad { BAD, WORSE, HORRIBLE }; // BAD
21693 ##### Enforcement
21695 * Flag macros with lower-case letters
21696 * Flag `ALL_CAPS` non-macro names
21698 ### <a name="Rl-camel"></a>NL.10: Prefer `underscore_style` names
21700 ##### Reason
21702 The use of underscores to separate parts of a name is the original C and C++ style and used in the C++ Standard Library.
21704 ##### Note
21706 This rule is a default to use only if you have a choice.
21707 Often, you don't have a choice and must follow an established style for [consistency](#Rl-name).
21708 The need for consistency beats personal taste.
21710 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21711 This rule was added after many requests for guidance.
21713 ##### Example
21715 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
21716 ISO Standard, but with upper case used for your own types and concepts:
21718 * `int`
21719 * `vector`
21720 * `My_map`
21722 ##### Enforcement
21724 Impossible.
21726 ### <a name="Rl-literals"></a>NL.11: Make literals readable
21728 ##### Reason
21730 Readability.
21732 ##### Example
21734 Use digit separators to avoid long strings of digits
21736     auto c = 299'792'458; // m/s2
21737     auto q2 = 0b0000'1111'0000'0000;
21738     auto ss_number = 123'456'7890;
21740 ##### Example
21742 Use literal suffixes where clarification is needed
21744     auto hello = "Hello!"s; // a std::string
21745     auto world = "world";   // a C-style string
21746     auto interval = 100ms;  // using <chrono>
21748 ##### Note
21750 Literals should not be sprinkled all over the code as ["magic constants"](#Res-magic),
21751 but it is still a good idea to make them readable where they are defined.
21752 It is easy to make a typo in a long string of integers.
21754 ##### Enforcement
21756 Flag long digit sequences. The trouble is to define "long"; maybe 7.
21758 ### <a name="Rl-space"></a>NL.15: Use spaces sparingly
21760 ##### Reason
21762 Too much space makes the text larger and distracts.
21764 ##### Example, bad
21766     #include < map >
21768     int main(int argc, char * argv [ ])
21769     {
21770         // ...
21771     }
21773 ##### Example
21775     #include <map>
21777     int main(int argc, char* argv[])
21778     {
21779         // ...
21780     }
21782 ##### Note
21784 Some IDEs have their own opinions and add distracting space.
21786 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21787 This rule was added after many requests for guidance.
21789 ##### Note
21791 We value well-placed whitespace as a significant help for readability. Just don't overdo it.
21793 ### <a name="Rl-order"></a>NL.16: Use a conventional class member declaration order
21795 ##### Reason
21797 A conventional order of members improves readability.
21799 When declaring a class use the following order
21801 * types: classes, enums, and aliases (`using`)
21802 * constructors, assignments, destructor
21803 * functions
21804 * data
21806 Use the `public` before `protected` before `private` order.
21808 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21809 This rule was added after many requests for guidance.
21811 ##### Example
21813     class X {
21814     public:
21815         // interface
21816     protected:
21817         // unchecked function for use by derived class implementations
21818     private:
21819         // implementation details
21820     };
21822 ##### Example
21824 Sometimes, the default order of members conflicts with a desire to separate the public interface from implementation details.
21825 In such cases, private types and functions can be placed with private data.
21827     class X {
21828     public:
21829         // interface
21830     protected:
21831         // unchecked function for use by derived class implementations
21832     private:
21833         // implementation details (types, functions, and data)
21834     };
21836 ##### Example, bad
21838 Avoid multiple blocks of declarations of one access (e.g., `public`) dispersed among blocks of declarations with different access (e.g. `private`).
21840     class X {   // bad
21841     public:
21842         void f();
21843     public:
21844         int g();
21845         // ...
21846     };
21848 The use of macros to declare groups of members often leads to violation of any ordering rules.
21849 However, using macros obscures what is being expressed anyway.
21851 ##### Enforcement
21853 Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule.
21855 ### <a name="Rl-knr"></a>NL.17: Use K&R-derived layout
21857 ##### Reason
21859 This is the original C and C++ layout. It preserves vertical space well. It distinguishes different language constructs (such as functions and classes) well.
21861 ##### Note
21863 In the context of C++, this style is often called "Stroustrup".
21865 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21866 This rule was added after many requests for guidance.
21868 ##### Example
21870     struct Cable {
21871         int x;
21872         // ...
21873     };
21875     double foo(int x)
21876     {
21877         if (0 < x) {
21878             // ...
21879         }
21881         switch (x) {
21882         case 0:
21883             // ...
21884             break;
21885         case amazing:
21886             // ...
21887             break;
21888         default:
21889             // ...
21890             break;
21891         }
21893         if (0 < x)
21894             ++x;
21896         if (x < 0)
21897             something();
21898         else
21899             something_else();
21901         return some_value;
21902     }
21904 Note the space between `if` and `(`
21906 ##### Note
21908 Use separate lines for each statement, the branches of an `if`, and the body of a `for`.
21910 ##### Note
21912 The `{` for a `class` and a `struct` is *not* on a separate line, but the `{` for a function is.
21914 ##### Note
21916 Capitalize the names of your user-defined types to distinguish them from standards-library types.
21918 ##### Note
21920 Do not capitalize function names.
21922 ##### Enforcement
21924 If you want enforcement, use an IDE to reformat.
21926 ### <a name="Rl-ptr"></a>NL.18: Use C++-style declarator layout
21928 ##### Reason
21930 The C-style layout emphasizes use in expressions and grammar, whereas the C++-style emphasizes types.
21931 The use in expressions argument doesn't hold for references.
21933 ##### Example
21935     T& operator[](size_t);   // OK
21936     T &operator[](size_t);   // just strange
21937     T & operator[](size_t);   // undecided
21939 ##### Note
21941 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21942 This rule was added after many requests for guidance.
21944 ##### Enforcement
21946 Impossible in the face of history.
21949 ### <a name="Rl-misread"></a>NL.19: Avoid names that are easily misread
21951 ##### Reason
21953 Readability.
21954 Not everyone has screens and printers that make it easy to distinguish all characters.
21955 We easily confuse similarly spelled and slightly misspelled words.
21957 ##### Example
21959     int oO01lL = 6; // bad
21961     int splunk = 7;
21962     int splonk = 8; // bad: splunk and splonk are easily confused
21964 ##### Enforcement
21968 ### <a name="Rl-stmt"></a>NL.20: Don't place two statements on the same line
21970 ##### Reason
21972 Readability.
21973 It is really easy to overlook a statement when there is more on a line.
21975 ##### Example
21977     int x = 7; char* p = 29;    // don't
21978     int x = 7; f(x);  ++x;      // don't
21980 ##### Enforcement
21982 Easy.
21984 ### <a name="Rl-dcl"></a>NL.21: Declare one name (only) per declaration
21986 ##### Reason
21988 Readability.
21989 Minimizing confusion with the declarator syntax.
21991 ##### Note
21993 For details, see [ES.10](#Res-name-one).
21996 ### <a name="Rl-void"></a>NL.25: Don't use `void` as an argument type
21998 ##### Reason
22000 It's verbose and only needed where C compatibility matters.
22002 ##### Example
22004     void f(void);   // bad
22006     void g();       // better
22008 ##### Note
22010 Even Dennis Ritchie deemed `void f(void)` an abomination.
22011 You can make an argument for that abomination in C when function prototypes were rare so that banning:
22013     int f();
22014     f(1, 2, "weird but valid C89");   // hope that f() is defined int f(a, b, c) char* c; { /* ... */ }
22016 would have caused major problems, but not in the 21st century and in C++.
22018 ### <a name="Rl-const"></a>NL.26: Use conventional `const` notation
22020 ##### Reason
22022 Conventional notation is more familiar to more programmers.
22023 Consistency in large code bases.
22025 ##### Example
22027     const int x = 7;    // OK
22028     int const y = 9;    // bad
22030     const int *const p = nullptr;   // OK, constant pointer to constant int
22031     int const *const p = nullptr;   // bad, constant pointer to constant int
22033 ##### Note
22035 We are well aware that you could claim the "bad" examples are more logical than the ones marked "OK",
22036 but they also confuse more people, especially novices relying on teaching material using the far more common, conventional OK style.
22038 As ever, remember that the aim of these naming and layout rules is consistency and that aesthetics vary immensely.
22040 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
22041 This rule was added after many requests for guidance.
22043 ##### Enforcement
22045 Flag `const` used as a suffix for a type.
22047 ### <a name="Rl-file-suffix"></a>NL.27: Use a `.cpp` suffix for code files and `.h` for interface files
22049 ##### Reason
22051 It's a longstanding convention.
22052 But consistency is more important, so if your project uses something else, follow that.
22054 ##### Note
22056 This convention reflects a common use pattern:
22057 Headers are more often shared with C to compile as both C++ and C, which typically uses `.h`,
22058 and it's easier to name all headers `.h` instead of having different extensions for just those headers that are intended to be shared with C.
22059 On the other hand, implementation files are rarely shared with C and so should typically be distinguished from `.c` files,
22060 so it's normally best to name all C++ implementation files something else (such as `.cpp`).
22062 The specific names `.h` and `.cpp` are not required (just recommended as a default) and other names are in widespread use.
22063 Examples are `.hh`, `.C`, and `.cxx`. Use such names equivalently.
22064 In this document, we refer to `.h` and `.cpp` as a shorthand for header and implementation files,
22065 even though the actual extension might be different.
22067 Your IDE (if you use one) might have strong opinions about suffixes.
22069 ##### Example
22071     // foo.h:
22072     extern int a;   // a declaration
22073     extern void foo();
22075     // foo.cpp:
22076     int a;   // a definition
22077     void foo() { ++a; }
22079 `foo.h` provides the interface to `foo.cpp`. Global variables are best avoided.
22081 ##### Example, bad
22083     // foo.h:
22084     int a;   // a definition
22085     void foo() { ++a; }
22087 `#include <foo.h>` twice in a program and you get a linker error for two one-definition-rule violations.
22089 ##### Enforcement
22091 * Flag non-conventional file names.
22092 * Check that `.h` and `.cpp` (and equivalents) follow the rules below.
22094 # <a name="S-faq"></a>FAQ: Answers to frequently asked questions
22096 This section covers answers to frequently asked questions about these guidelines.
22098 ### <a name="Faq-aims"></a>FAQ.1: What do these guidelines aim to achieve?
22100 See the <a href="#S-abstract">top of this page</a>. This is an open-source project to maintain modern authoritative guidelines for writing C++ code using the current C++ Standard. The guidelines are designed to be modern, machine-enforceable wherever possible, and open to contributions and forking so that organizations can easily incorporate them into their own corporate coding guidelines.
22102 ### <a name="Faq-announced"></a>FAQ.2: When and where was this work first announced?
22104 It was announced by [Bjarne Stroustrup in his CppCon 2015 opening keynote, "Writing Good C++14"](https://isocpp.org/blog/2015/09/stroustrup-cppcon15-keynote). See also the [accompanying isocpp.org blog post](https://isocpp.org/blog/2015/09/bjarne-stroustrup-announces-cpp-core-guidelines), and for the rationale of the type and memory safety guidelines see [Herb Sutter's follow-up CppCon 2015 talk, "Writing Good C++14 ... By Default"](https://isocpp.org/blog/2015/09/sutter-cppcon15-day2plenary).
22106 ### <a name="Faq-maintainers"></a>FAQ.3: Who are the authors and maintainers of these guidelines?
22108 The initial primary authors and maintainers are Bjarne Stroustrup and Herb Sutter, and the guidelines so far were developed with contributions from experts at CERN, Microsoft, Morgan Stanley, and several other organizations. At the time of their release, the guidelines are in a "0.6" state, and contributions are welcome. As Stroustrup said in his announcement: "We need help!"
22110 ### <a name="Faq-contribute"></a>FAQ.4: How can I contribute?
22112 See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help!
22114 ### <a name="Faq-maintainer"></a>FAQ.5: How can I become an editor/maintainer?
22116 By contributing a lot first and having the consistent quality of your contributions recognized. See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help!
22118 ### <a name="Faq-iso"></a>FAQ.6: Have these guidelines been approved by the ISO C++ standards committee? Do they represent the consensus of the committee?
22120 No. These guidelines are outside the standard. They are intended to serve the standard, and be maintained as current guidelines about how to use the current Standard C++ effectively. We aim to keep them in sync with the standard as that is evolved by the committee.
22122 ### <a name="Faq-isocpp"></a>FAQ.7: If these guidelines are not approved by the committee, why are they under `github.com/isocpp`?
22124 Because `isocpp` is the Standard C++ Foundation; the committee's repositories are under [github.com/*cplusplus*](https://github.com/cplusplus). Some neutral organization has to own the copyright and license to make it clear this is not being dominated by any one person or vendor. The natural entity is the Foundation, which exists to promote the use and up-to-date understanding of modern Standard C++ and the work of the committee. This follows the same pattern that isocpp.org did for the [C++ FAQ](https://isocpp.org/faq), which was initially the work of Bjarne Stroustrup, Marshall Cline, and Herb Sutter and contributed to the open project in the same way.
22126 ### <a name="Faq-cpp98"></a>FAQ.8: Will there be a C++98 version of these Guidelines? a C++11 version?
22128 No. These guidelines are about how to best use modern standard C++ and write code assuming you have a modern conforming compiler.
22130 ### <a name="Faq-language-extensions"></a>FAQ.9: Do these guidelines propose new language features?
22132 No. These guidelines are about how to best use modern Standard C++, and they limit themselves to recommending only those features.
22134 ### <a name="Faq-markdown"></a>FAQ.10: What version of Markdown do these guidelines use?
22136 These coding standards are written using [CommonMark](http://commonmark.org), and `<a>` HTML anchors.
22138 We are considering the following extensions from [GitHub Flavored Markdown (GFM)](https://help.github.com/articles/github-flavored-markdown/):
22140 * fenced code blocks (consistently using indented vs. fenced is under discussion)
22141 * tables (none yet but we'll likely need them, and this is a GFM extension)
22143 Avoid other HTML tags and other extensions.
22145 Note: We are not yet consistent with this style.
22147 ### <a name="Faq-gsl"></a>FAQ.50: What is the GSL (guidelines support library)?
22149 The GSL is the small set of types and aliases specified in these guidelines. As of this writing, their specification herein is too sparse; we plan to add a WG21-style interface specification to ensure that different implementations agree, and to propose as a contribution for possible standardization, subject as usual to whatever the committee decides to accept/improve/alter/reject.
22151 ### <a name="Faq-msgsl"></a>FAQ.51: Is [github.com/Microsoft/GSL](https://github.com/Microsoft/GSL) the GSL?
22153 No. That is just a first implementation contributed by Microsoft. Other implementations by other vendors are encouraged, as are forks of and contributions to that implementation. As of this writing one week into the public project, at least one GPLv3 open-source implementation already exists. We plan to produce a WG21-style interface specification to ensure that different implementations agree.
22155 ### <a name="Faq-gsl-implementation"></a>FAQ.52: Why not supply an actual GSL implementation in/with these guidelines?
22157 We are reluctant to bless one particular implementation because we do not want to make people think there is only one, and inadvertently stifle parallel implementations. And if these guidelines included an actual implementation, then whoever contributed it could be mistakenly seen as too influential. We prefer to follow the long-standing approach of the committee, namely to specify interfaces, not implementations. But at the same time we want at least one implementation available; we hope for many.
22159 ### <a name="Faq-boost"></a>FAQ.53: Why weren't the GSL types proposed through Boost?
22161 Because we want to use them immediately, and because they are temporary in that we want to retire them as soon as types that fill the same needs exist in the standard library.
22163 ### <a name="Faq-gsl-iso"></a>FAQ.54: Has the GSL (guidelines support library) been approved by the ISO C++ standards committee?
22165 No. The GSL exists only to supply a few types and aliases that are not currently in the standard library. If the committee decides on standardized versions (of these or other types that fill the same need) then they can be removed from the GSL.
22167 ### <a name="Faq-gsl-string-view"></a>FAQ.55: If you're using the standard types where available, why is the GSL `span<char>` different from the `string_view` in the Library Fundamentals 1 Technical Specification and C++17 Working Paper? Why not just use the committee-approved `string_view`?
22169 The consensus on the taxonomy of views for the C++ Standard Library was that "view" means "read-only", and "span" means "read/write". If you only need a read-only view of characters that does not need guaranteed bounds-checking and you have C++17, use C++17 `std::string_view`. Otherwise, if you need a read-write view that does not need guaranteed bounds-checking and you have C++20, use C++20 `std::span<char>`. Otherwise, use `gsl::span<char>`.
22171 ### <a name="Faq-gsl-owner"></a>FAQ.56: Is `owner` the same as the proposed `observer_ptr`?
22173 No. `owner` owns, is an alias, and can be applied to any indirection type. The main intent of `observer_ptr` is to signify a *non*-owning pointer.
22175 ### <a name="Faq-gsl-stack-array"></a>FAQ.57: Is `stack_array` the same as the standard `array`?
22177 No. `stack_array` is guaranteed to be allocated on the stack. Although a `std::array` contains its storage directly inside itself, the `array` object can be put anywhere, including the heap.
22179 ### <a name="Faq-gsl-dyn-array"></a>FAQ.58: Is `dyn_array` the same as `vector` or the proposed `dynarray`?
22181 No. `dyn_array` is not resizable, and is a safe way to refer to a heap-allocated fixed-size array. Unlike `vector`, it is intended to replace array-`new[]`. Unlike the `dynarray` that has been proposed in the committee, this does not anticipate compiler/language magic to somehow allocate it on the stack when it is a member of an object that is allocated on the stack; it simply refers to a "dynamic" or heap-based array.
22183 ### <a name="Faq-gsl-expects"></a>FAQ.59: Is `Expects` the same as `assert`?
22185 No. It is a placeholder for language support for contract preconditions.
22187 ### <a name="Faq-gsl-ensures"></a>FAQ.60: Is `Ensures` the same as `assert`?
22189 No. It is a placeholder for language support for contract postconditions.
22191 # <a name="S-libraries"></a>Appendix A: Libraries
22193 This section lists recommended libraries, and explicitly recommends a few.
22195 ??? Suitable for the general guide? I think not ???
22197 # <a name="S-modernizing"></a>Appendix B: Modernizing code
22199 Ideally, we follow all rules in all code.
22200 Realistically, we have to deal with a lot of old code:
22202 * application code written before the guidelines were formulated or known
22203 * libraries written to older/different standards
22204 * code written under "unusual" constraints
22205 * code that we just haven't gotten around to modernizing
22207 If we have a million lines of new code, the idea of "just changing it all at once" is typically unrealistic.
22208 Thus, we need a way of gradually modernizing a code base.
22210 Upgrading older code to modern style can be a daunting task.
22211 Often, the old code is both a mess (hard to understand) and working correctly (for the current range of uses).
22212 Typically, the original programmer is not around and the test cases incomplete.
22213 The fact that the code is a mess dramatically increases the effort needed to make any change and the risk of introducing errors.
22214 Often, messy old code runs unnecessarily slowly because it requires outdated compilers and cannot take advantage of modern hardware.
22215 In many cases, automated "modernizer"-style tool support would be required for major upgrade efforts.
22217 The purpose of modernizing code is to simplify adding new functionality, to ease maintenance, and to increase performance (throughput or latency), and to better utilize modern hardware.
22218 Making code "look pretty" or "follow modern style" are not by themselves reasons for change.
22219 There are risks implied by every change and costs (including the cost of lost opportunities) implied by having an outdated code base.
22220 The cost reductions must outweigh the risks.
22222 But how?
22224 There is no one approach to modernizing code.
22225 How best to do it depends on the code, the pressure for updates, the backgrounds of the developers, and the available tool.
22226 Here are some (very general) ideas:
22228 * The ideal is "just upgrade everything." That gives the most benefits for the shortest total time.
22229   In most circumstances, it is also impossible.
22230 * We could convert a code base module for module, but any rules that affects interfaces (especially ABIs), such as [use `span`](#SS-views), cannot be done on a per-module basis.
22231 * We could convert code "bottom up" starting with the rules we estimate will give the greatest benefits and/or the least trouble in a given code base.
22232 * We could start by focusing on the interfaces, e.g., make sure that no resources are lost and no pointer is misused.
22233   This would be a set of changes across the whole code base, but would most likely have huge benefits.
22234   Afterwards, code hidden behind those interfaces can be gradually modernized without affecting other code.
22236 Whichever way you choose, please note that the most advantages come with the highest conformance to the guidelines.
22237 The guidelines are not a random set of unrelated rules where you can randomly pick and choose with an expectation of success.
22239 We would dearly love to hear about experience and about tools used.
22240 Modernization can be much faster, simpler, and safer when supported with analysis tools and even code transformation tools.
22242 # <a name="S-discussion"></a>Appendix C: Discussion
22244 This section contains follow-up material on rules and sets of rules.
22245 In particular, here we present further rationale, longer examples, and discussions of alternatives.
22247 ### <a name="Sd-order"></a>Discussion: Define and initialize member variables in the order of member declaration
22249 Member variables are always initialized in the order they are declared in the class definition, so write them in that order in the constructor initialization list. Writing them in a different order just makes the code confusing because it won't run in the order you see, and that can make it hard to see order-dependent bugs.
22251     class Employee {
22252         string email, first, last;
22253     public:
22254         Employee(const char* firstName, const char* lastName);
22255         // ...
22256     };
22258     Employee::Employee(const char* firstName, const char* lastName)
22259       : first(firstName),
22260         last(lastName),
22261         // BAD: first and last not yet constructed
22262         email(first + "." + last + "@acme.com")
22263     {}
22265 In this example, `email` will be constructed before `first` and `last` because it is declared first. That means its constructor will attempt to use `first` and `last` too soon -- not just before they are set to the desired values, but before they are constructed at all.
22267 If the class definition and the constructor body are in separate files, the long-distance influence that the order of member variable declarations has over the constructor's correctness will be even harder to spot.
22269 **References**:
22271 [\[Cline99\]](#Cline99) §22.03-11, [\[Dewhurst03\]](#Dewhurst03) §52-53, [\[Koenig97\]](#Koenig97) §4, [\[Lakos96\]](#Lakos96) §10.3.5, [\[Meyers97\]](#Meyers97) §13, [\[Murray93\]](#Murray93) §2.1.3, [\[Sutter00\]](#Sutter00) §47
22273 ### <a name="Sd-init"></a>Discussion: Use of `=`, `{}`, and `()` as initializers
22277 ### <a name="Sd-factory"></a>Discussion: Use a factory function if you need "virtual behavior" during initialization
22279 If your design wants virtual dispatch into a derived class from a base class constructor or destructor for functions like `f` and `g`, you need other techniques, such as a post-constructor -- a separate member function the caller must invoke to complete initialization, which can safely call `f` and `g` because in member functions virtual calls behave normally. Some techniques for this are shown in the References. Here's a non-exhaustive list of options:
22281 * *Pass the buck:* Just document that user code must call the post-initialization function right after constructing an object.
22282 * *Post-initialize lazily:* Do it during the first call of a member function. A Boolean flag in the base class tells whether or not post-construction has taken place yet.
22283 * *Use virtual base class semantics:* Language rules dictate that the constructor of the most-derived class decides which base constructor will be invoked; you can use that to your advantage. (See [\[Taligent94\]](#Taligent94).)
22284 * *Use a factory function:* This way, you can easily force a mandatory invocation of a post-constructor function.
22286 Here is an example of the last option:
22288     class B {
22289     public:
22290         B()
22291         {
22292             /* ... */
22293             f(); // BAD: C.82: Don't call virtual functions in constructors and destructors
22294             /* ... */
22295         }
22297         virtual void f() = 0;
22298     };
22300     class B {
22301     protected:
22302         class Token {};
22304     public:
22305         // constructor needs to be public so that make_shared can access it.
22306         // protected access level is gained by requiring a Token.
22307         explicit B(Token) { /* ... */ }  // create an imperfectly initialized object
22308         virtual void f() = 0;
22310         template<class T>
22311         static shared_ptr<T> create()    // interface for creating shared objects
22312         {
22313             auto p = make_shared<T>(typename T::Token{});
22314             p->post_initialize();
22315             return p;
22316         }
22318     protected:
22319         virtual void post_initialize()   // called right after construction
22320             { /* ... */ f(); /* ... */ } // GOOD: virtual dispatch is safe
22321         }
22322     };
22325     class D : public B {                 // some derived class
22326     protected:
22327         class Token {};
22329     public:
22330         // constructor needs to be public so that make_shared can access it.
22331         // protected access level is gained by requiring a Token.
22332         explicit D(Token) : B{ B::Token{} } {}
22333         void f() override { /* ...  */ };
22335     protected:
22336         template<class T>
22337         friend shared_ptr<T> B::create();
22338     };
22340     shared_ptr<D> p = D::create<D>();    // creating a D object
22342 This design requires the following discipline:
22344 * Derived classes such as `D` must not expose a publicly callable constructor. Otherwise, `D`'s users could create `D` objects that don't invoke `post_initialize`.
22345 * Allocation is limited to `operator new`. `B` can, however, override `new` (see Items 45 and 46 in [SuttAlex05](#SuttAlex05)).
22346 * `D` must define a constructor with the same parameters that `B` selected. Defining several overloads of `create` can assuage this problem, however; and the overloads can even be templated on the argument types.
22348 If the requirements above are met, the design guarantees that `post_initialize` has been called for any fully constructed `B`-derived object. `post_initialize` doesn't need to be virtual; it can, however, invoke virtual functions freely.
22350 In summary, no post-construction technique is perfect. The worst techniques dodge the whole issue by simply asking the caller to invoke the post-constructor manually. Even the best require a different syntax for constructing objects (easy to check at compile time) and/or cooperation from derived class authors (impossible to check at compile time).
22352 **References**: [\[Alexandrescu01\]](#Alexandrescu01) §3, [\[Boost\]](#Boost), [\[Dewhurst03\]](#Dewhurst03) §75, [\[Meyers97\]](#Meyers97) §46, [\[Stroustrup00\]](#Stroustrup00) §15.4.3, [\[Taligent94\]](#Taligent94)
22354 ### <a name="Sd-dtor"></a>Discussion: Make base class destructors public and virtual, or protected and non-virtual
22356 Should destruction behave virtually? That is, should destruction through a pointer to a `base` class be allowed? If yes, then `base`'s destructor must be public in order to be callable, and virtual otherwise calling it results in undefined behavior. Otherwise, it should be protected so that only derived classes can invoke it in their own destructors, and non-virtual since it doesn't need to behave virtually.
22358 ##### Example
22360 The common case for a base class is that it's intended to have publicly derived classes, and so calling code is just about sure to use something like a `shared_ptr<base>`:
22362     class Base {
22363     public:
22364         ~Base();                   // BAD, not virtual
22365         virtual ~Base();           // GOOD
22366         // ...
22367     };
22369     class Derived : public Base { /* ... */ };
22371     {
22372         unique_ptr<Base> pb = make_unique<Derived>();
22373         // ...
22374     } // ~pb invokes correct destructor only when ~Base is virtual
22376 In rarer cases, such as policy classes, the class is used as a base class for convenience, not for polymorphic behavior. It is recommended to make those destructors protected and non-virtual:
22378     class My_policy {
22379     public:
22380         virtual ~My_policy();      // BAD, public and virtual
22381     protected:
22382         ~My_policy();              // GOOD
22383         // ...
22384     };
22386     template<class Policy>
22387     class customizable : Policy { /* ... */ }; // note: private inheritance
22389 ##### Note
22391 This simple guideline illustrates a subtle issue and reflects modern uses of inheritance and object-oriented design principles.
22393 For a base class `Base`, calling code might try to destroy derived objects through pointers to `Base`, such as when using a `unique_ptr<Base>`. If `Base`'s destructor is public and non-virtual (the default), it can be accidentally called on a pointer that actually points to a derived object, in which case the behavior of the attempted deletion is undefined. This state of affairs has led older coding standards to impose a blanket requirement that all base class destructors must be virtual. This is overkill (even if it is the common case); instead, the rule should be to make base class destructors virtual if and only if they are public.
22395 To write a base class is to define an abstraction (see Items 35 through 37). Recall that for each member function participating in that abstraction, you need to decide:
22397 * Whether it should behave virtually or not.
22398 * Whether it should be publicly available to all callers using a pointer to `Base` or else be a hidden internal implementation detail.
22400 As described in Item 39, for a normal member function, the choice is between allowing it to be called via a pointer to `Base` non-virtually (but possibly with virtual behavior if it invokes virtual functions, such as in the NVI or Template Method patterns), virtually, or not at all. The NVI pattern is a technique to avoid public virtual functions.
22402 Destruction can be viewed as just another operation, albeit with special semantics that make non-virtual calls dangerous or wrong. For a base class destructor, therefore, the choice is between allowing it to be called via a pointer to `Base` virtually or not at all; "non-virtually" is not an option. Hence, a base class destructor is virtual if it can be called (i.e., is public), and non-virtual otherwise.
22404 Note that the NVI pattern cannot be applied to the destructor because constructors and destructors cannot make deep virtual calls. (See Items 39 and 55.)
22406 Corollary: When writing a base class, always write a destructor explicitly, because the implicitly generated one is public and non-virtual. You can always `=default` the implementation if the default body is fine and you're just writing the function to give it the proper visibility and virtuality.
22408 ##### Exception
22410 Some component architectures (e.g., COM and CORBA) don't use a standard deletion mechanism, and foster different protocols for object disposal. Follow the local patterns and idioms, and adapt this guideline as appropriate.
22412 Consider also this rare case:
22414 * `B` is both a base class and a concrete class that can be instantiated by itself, and so the destructor must be public for `B` objects to be created and destroyed.
22415 * Yet `B` also has no virtual functions and is not meant to be used polymorphically, and so although the destructor is public it does not need to be virtual.
22417 Then, even though the destructor has to be public, there can be great pressure to not make it virtual because as the first virtual function it would incur all the run-time type overhead when the added functionality should never be needed.
22419 In this rare case, you could make the destructor public and non-virtual but clearly document that further-derived objects must not be used polymorphically as `B`'s. This is what was done with `std::unary_function`.
22421 In general, however, avoid concrete base classes (see Item 35). For example, `unary_function` is a bundle-of-typedefs that was never intended to be instantiated standalone. It really makes no sense to give it a public destructor; a better design would be to follow this Item's advice and give it a protected non-virtual destructor.
22423 **References**: [\[SuttAlex05\]](#SuttAlex05) Item 50, [\[Cargill92\]](#Cargill92) pp. 77-79, 207, [\[Cline99\]](#Cline99) §21.06, 21.12-13, [\[Henricson97\]](#Henricson97) pp. 110-114, [\[Koenig97\]](#Koenig97) Chapters 4, 11, [\[Meyers97\]](#Meyers97) §14, [\[Stroustrup00\]](#Stroustrup00) §12.4.2, [\[Sutter02\]](#Sutter02) §27, [\[Sutter04\]](#Sutter04) §18
22425 ### <a name="Sd-noexcept"></a>Discussion: Usage of noexcept
22429 ### <a name="Sd-never-fail"></a>Discussion: Destructors, deallocation, and swap must never fail
22431 Never allow an error to be reported from a destructor, a resource deallocation function (e.g., `operator delete`), or a `swap` function using `throw`. It is nearly impossible to write useful code if these operations can fail, and even if something does go wrong it nearly never makes any sense to retry. Specifically, types whose destructors might throw an exception are flatly forbidden from use with the C++ Standard Library. Most destructors are now implicitly `noexcept` by default.
22433 ##### Example
22435     class Nefarious {
22436     public:
22437         Nefarious() { /* code that could throw */ }    // ok
22438         ~Nefarious() { /* code that could throw */ }   // BAD, should not throw
22439         // ...
22440     };
22442 1. `Nefarious` objects are hard to use safely even as local variables:
22445         void test(string& s)
22446         {
22447             Nefarious n;          // trouble brewing
22448             string copy = s;      // copy the string
22449         } // destroy copy and then n
22451     Here, copying `s` could throw, and if that throws and if `n`'s destructor then also throws, the program will exit via `std::terminate` because two exceptions can't be propagated simultaneously.
22453 2. Classes with `Nefarious` members or bases are also hard to use safely, because their destructors must invoke `Nefarious`' destructor, and are similarly poisoned by its bad behavior:
22456         class Innocent_bystander {
22457             Nefarious member;     // oops, poisons the enclosing class's destructor
22458             // ...
22459         };
22461         void test(string& s)
22462         {
22463             Innocent_bystander i;  // more trouble brewing
22464             string copy2 = s;      // copy the string
22465         } // destroy copy and then i
22467     Here, if constructing `copy2` throws, we have the same problem because `i`'s destructor now also can throw, and if so we'll invoke `std::terminate`.
22469 3. You can't reliably create global or static `Nefarious` objects either:
22472         static Nefarious n;       // oops, any destructor exception can't be caught
22474 4. You can't reliably create arrays of `Nefarious`:
22477         void test()
22478         {
22479             std::array<Nefarious, 10> arr; // this line can std::terminate()
22480         }
22482     The behavior of arrays is undefined in the presence of destructors that throw because there is no reasonable rollback behavior that could ever be devised. Just think: What code can the compiler generate for constructing an `arr` where, if the fourth object's constructor throws, the code has to give up and in its cleanup mode tries to call the destructors of the already-constructed objects ... and one or more of those destructors throws? There is no satisfactory answer.
22484 5. You can't use `Nefarious` objects in standard containers:
22487         std::vector<Nefarious> vec(10);   // this line can std::terminate()
22489     The standard library forbids all destructors used with it from throwing. You can't store `Nefarious` objects in standard containers or use them with any other part of the standard library.
22491 ##### Note
22493 These are key functions that must not fail because they are necessary for the two key operations in transactional programming: to back out work if problems are encountered during processing, and to commit work if no problems occur. If there's no way to safely back out using no-fail operations, then no-fail rollback is impossible to implement. If there's no way to safely commit state changes using a no-fail operation (notably, but not limited to, `swap`), then no-fail commit is impossible to implement.
22495 Consider the following advice and requirements found in the C++ Standard:
22497 > If a destructor called during stack unwinding exits with an exception, terminate is called (15.5.1). So destructors should generally catch exceptions and not let them propagate out of the destructor. --[\[C++03\]](#Cplusplus03) §15.2(3)
22499 > No destructor operation defined in the C++ Standard Library (including the destructor of any type that is used to instantiate a standard-library template) will throw an exception. --[\[C++03\]](#Cplusplus03) §17.4.4.8(3)
22501 Deallocation functions, including specifically overloaded `operator delete` and `operator delete[]`, fall into the same category, because they too are used during cleanup in general, and during exception handling in particular, to back out of partial work that needs to be undone.
22502 Besides destructors and deallocation functions, common error-safety techniques rely also on `swap` operations never failing -- in this case, not because they are used to implement a guaranteed rollback, but because they are used to implement a guaranteed commit. For example, here is an idiomatic implementation of `operator=` for a type `T` that performs copy construction followed by a call to a no-fail `swap`:
22504     T& T::operator=(const T& other)
22505     {
22506         auto temp = other;
22507         swap(temp);
22508         return *this;
22509     }
22511 (See also Item 56. ???)
22513 Fortunately, when releasing a resource, the scope for failure is definitely smaller. If using exceptions as the error reporting mechanism, make sure such functions handle all exceptions and other errors that their internal processing might generate. (For exceptions, simply wrap everything sensitive that your destructor does in a `try/catch(...)` block.) This is particularly important because a destructor might be called in a crisis situation, such as failure to allocate a system resource (e.g., memory, files, locks, ports, windows, or other system objects).
22515 When using exceptions as your error handling mechanism, always document this behavior by declaring these functions `noexcept`. (See Item 75.)
22517 **References**: [\[SuttAlex05\]](#SuttAlex05) Item 51; [\[C++03\]](#Cplusplus03) §15.2(3), §17.4.4.8(3), [\[Meyers96\]](#Meyers96) §11, [\[Stroustrup00\]](#Stroustrup00) §14.4.7, §E.2-4, [\[Sutter00\]](#Sutter00) §8, §16, [\[Sutter02\]](#Sutter02) §18-19
22519 ## <a name="Sd-consistent"></a>Define Copy, move, and destroy consistently
22521 ##### Reason
22523  ???
22525 ##### Note
22527 If you define a copy constructor, you must also define a copy assignment operator.
22529 ##### Note
22531 If you define a move constructor, you must also define a move assignment operator.
22533 ##### Example
22535     class X {
22536     public:
22537         X(const X&) { /* stuff */ }
22539         // BAD: failed to also define a copy assignment operator
22541         X(x&&) noexcept { /* stuff */ }
22543         // BAD: failed to also define a move assignment operator
22545         // ...
22546     };
22548     X x1;
22549     X x2 = x1; // ok
22550     x2 = x1;   // pitfall: either fails to compile, or does something suspicious
22552 If you define a destructor, you should not use the compiler-generated copy or move operation; you probably need to define or suppress copy and/or move.
22554     class X {
22555         HANDLE hnd;
22556         // ...
22557     public:
22558         ~X() { /* custom stuff, such as closing hnd */ }
22559         // suspicious: no mention of copying or moving -- what happens to hnd?
22560     };
22562     X x1;
22563     X x2 = x1; // pitfall: either fails to compile, or does something suspicious
22564     x2 = x1;   // pitfall: either fails to compile, or does something suspicious
22566 If you define copying, and any base or member has a type that defines a move operation, you should also define a move operation.
22568     class X {
22569         string s; // defines more efficient move operations
22570         // ... other data members ...
22571     public:
22572         X(const X&) { /* stuff */ }
22573         X& operator=(const X&) { /* stuff */ }
22575         // BAD: failed to also define a move construction and move assignment
22576         // (why wasn't the custom "stuff" repeated here?)
22577     };
22579     X test()
22580     {
22581         X local;
22582         // ...
22583         return local;  // pitfall: will be inefficient and/or do the wrong thing
22584     }
22586 If you define any of the copy constructor, copy assignment operator, or destructor, you probably should define the others.
22588 ##### Note
22590 If you need to define any of these five functions, it means you need it to do more than its default behavior -- and the five are asymmetrically interrelated. Here's how:
22592 * If you write/disable either of the copy constructor or the copy assignment operator, you probably need to do the same for the other: If one does "special" work, probably so should the other because the two functions should have similar effects. (See Item 53, which expands on this point in isolation.)
22593 * If you explicitly write the copying functions, you probably need to write the destructor: If the "special" work in the copy constructor is to allocate or duplicate some resource (e.g., memory, file, socket), you need to deallocate it in the destructor.
22594 * If you explicitly write the destructor, you probably need to explicitly write or disable copying: If you have to write a non-trivial destructor, it's often because you need to manually release a resource that the object held. If so, it is likely that those resources require careful duplication, and then you need to pay attention to the way objects are copied and assigned, or disable copying completely.
22596 In many cases, holding properly encapsulated resources using RAII "owning" objects can eliminate the need to write these operations yourself. (See Item 13.)
22598 Prefer compiler-generated (including `=default`) special members; only these can be classified as "trivial", and at least one major standard library vendor heavily optimizes for classes having trivial special members. This is likely to become common practice.
22600 **Exceptions**: When any of the special functions are declared only to make them non-public or virtual, but without special semantics, it doesn't imply that the others are needed.
22601 In rare cases, classes that have members of strange types (such as reference members) are an exception because they have peculiar copy semantics.
22602 In a class holding a reference, you likely need to write the copy constructor and the assignment operator, but the default destructor already does the right thing. (Note that using a reference member is almost always wrong.)
22604 **References**: [\[SuttAlex05\]](#SuttAlex05) Item 52; [\[Cline99\]](#Cline99) §30.01-14, [\[Koenig97\]](#Koenig97) §4, [\[Stroustrup00\]](#Stroustrup00) §5.5, §10.4, [\[SuttHysl04b\]](#SuttHysl04b)
22606 Resource management rule summary:
22608 * [Provide strong resource safety; that is, never leak anything that you think of as a resource](#Cr-safety)
22609 * [Never return or throw while holding a resource not owned by a handle](#Cr-never)
22610 * [A "raw" pointer or reference is never a resource handle](#Cr-raw)
22611 * [Never let a pointer outlive the object it points to](#Cr-outlive)
22612 * [Use templates to express containers (and other resource handles)](#Cr-templates)
22613 * [Return containers by value (relying on move or copy elision for efficiency)](#Cr-value-return)
22614 * [If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations](#Cr-handle)
22615 * [If a class is a container, give it an initializer-list constructor](#Cr-list)
22617 ### <a name="Cr-safety"></a>Discussion: Provide strong resource safety; that is, never leak anything that you think of as a resource
22619 ##### Reason
22621 Prevent leaks. Leaks can lead to performance degradation, mysterious error, system crashes, and security violations.
22623 **Alternative formulation**: Have every resource represented as an object of some class managing its lifetime.
22625 ##### Example
22627     template<class T>
22628     class Vector {
22629     private:
22630         T* elem;   // sz elements on the free store, owned by the class object
22631         int sz;
22632         // ...
22633     };
22635 This class is a resource handle. It manages the lifetime of the `T`s. To do so, `Vector` must define or delete [the set of special operations](???) (constructors, a destructor, etc.).
22637 ##### Example
22639     ??? "odd" non-memory resource ???
22641 ##### Enforcement
22643 The basic technique for preventing leaks is to have every resource owned by a resource handle with a suitable destructor. A checker can find "naked `new`s". Given a list of C-style allocation functions (e.g., `fopen()`), a checker can also find uses that are not managed by a resource handle. In general, "naked pointers" can be viewed with suspicion, flagged, and/or analyzed. A complete list of resources cannot be generated without human input (the definition of "a resource" is necessarily too general), but a tool can be "parameterized" with a resource list.
22645 ### <a name="Cr-never"></a>Discussion: Never return or throw while holding a resource not owned by a handle
22647 ##### Reason
22649 That would be a leak.
22651 ##### Example
22653     void f(int i)
22654     {
22655         FILE* f = fopen("a file", "r");
22656         ifstream is { "another file" };
22657         // ...
22658         if (i == 0) return;
22659         // ...
22660         fclose(f);
22661     }
22663 If `i == 0` the file handle for `a file` is leaked. On the other hand, the `ifstream` for `another file` will correctly close its file (upon destruction). If you must use an explicit pointer, rather than a resource handle with specific semantics, use a `unique_ptr` or a `shared_ptr` with a custom deleter:
22665     void f(int i)
22666     {
22667         unique_ptr<FILE, int(*)(FILE*)> f(fopen("a file", "r"), fclose);
22668         // ...
22669         if (i == 0) return;
22670         // ...
22671     }
22673 Better:
22675     void f(int i)
22676     {
22677         ifstream input {"a file"};
22678         // ...
22679         if (i == 0) return;
22680         // ...
22681     }
22683 ##### Enforcement
22685 A checker must consider all "naked pointers" suspicious.
22686 A checker probably must rely on a human-provided list of resources.
22687 For starters, we know about the standard-library containers, `string`, and smart pointers.
22688 The use of `span` and `string_view` should help a lot (they are not resource handles).
22690 ### <a name="Cr-raw"></a>Discussion: A "raw" pointer or reference is never a resource handle
22692 ##### Reason
22694 To be able to distinguish owners from views.
22696 ##### Note
22698 This is independent of how you "spell" pointer: `T*`, `T&`, `Ptr<T>` and `Range<T>` are not owners.
22700 ### <a name="Cr-outlive"></a>Discussion: Never let a pointer outlive the object it points to
22702 ##### Reason
22704 To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system.
22706 ##### Example
22708     string* bad()   // really bad
22709     {
22710         vector<string> v = { "This", "will", "cause", "trouble", "!" };
22711         // leaking a pointer into a destroyed member of a destroyed object (v)
22712         return &v[0];
22713     }
22715     void use()
22716     {
22717         string* p = bad();
22718         vector<int> xx = {7, 8, 9};
22719         // undefined behavior: x might not be the string "This"
22720         string x = *p;
22721         // undefined behavior: we don't know what (if anything) is allocated a location p
22722         *p = "Evil!";
22723     }
22725 The `string`s of `v` are destroyed upon exit from `bad()` and so is `v` itself. The returned pointer points to unallocated memory on the free store. This memory (pointed into by `p`) might have been reallocated by the time `*p` is executed. There might be no `string` to read and a write through `p` could easily corrupt objects of unrelated types.
22727 ##### Enforcement
22729 Most compilers already warn about simple cases and have the information to do more. Consider any pointer returned from a function suspect. Use containers, resource handles, and views (e.g., `span` known not to be resource handles) to lower the number of cases to be examined. For starters, consider every class with a destructor as resource handle.
22731 ### <a name="Cr-templates"></a>Discussion: Use templates to express containers (and other resource handles)
22733 ##### Reason
22735 To provide statically type-safe manipulation of elements.
22737 ##### Example
22739     template<typename T> class Vector {
22740         // ...
22741         T* elem;   // point to sz elements of type T
22742         int sz;
22743     };
22745 ### <a name="Cr-value-return"></a>Discussion: Return containers by value (relying on move or copy elision for efficiency)
22747 ##### Reason
22749 To simplify code and eliminate a need for explicit memory management. To bring an object into a surrounding scope, thereby extending its lifetime.
22751 **See also**: [F.20, the general item about "out" output values](#Rf-out)
22753 ##### Example
22755     vector<int> get_large_vector()
22756     {
22757         return ...;
22758     }
22760     auto v = get_large_vector(); //  return by value is ok, most modern compilers will do copy elision
22762 ##### Exception
22764 See the Exceptions in [F.20](#Rf-out).
22766 ##### Enforcement
22768 Check for pointers and references returned from functions and see if they are assigned to resource handles (e.g., to a `unique_ptr`).
22770 ### <a name="Cr-handle"></a>Discussion: If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations
22772 ##### Reason
22774 To provide complete control of the lifetime of the resource. To provide a coherent set of operations on the resource.
22776 ##### Example
22778     ??? Messing with pointers
22780 ##### Note
22782 If all members are resource handles, rely on the default special operations where possible.
22784     template<typename T> struct Named {
22785         string name;
22786         T value;
22787     };
22789 Now `Named` has a default constructor, a destructor, and efficient copy and move operations, provided `T` has.
22791 ##### Enforcement
22793 In general, a tool cannot know if a class is a resource handle. However, if a class has some of [the default operations](#SS-ctor), it should have all, and if a class has a member that is a resource handle, it should be considered as resource handle.
22795 ### <a name="Cr-list"></a>Discussion: If a class is a container, give it an initializer-list constructor
22797 ##### Reason
22799 It is common to need an initial set of elements.
22801 ##### Example
22803     template<typename T> class Vector {
22804     public:
22805         Vector(std::initializer_list<T>);
22806         // ...
22807     };
22809     Vector<string> vs { "Nygaard", "Ritchie" };
22811 ##### Enforcement
22813 When is a class a container? ???
22815 # <a name="S-tools"></a>Appendix D: Supporting tools
22817 This section contains a list of tools that directly support adoption of the C++ Core Guidelines. This list is not intended to be an exhaustive list of tools
22818 that are helpful in writing good C++ code. If a tool is designed specifically to support and links to the C++ Core Guidelines it is a candidate for inclusion.
22820 ### <a name="St-clangtidy"></a>Tools: [Clang-tidy](http://clang.llvm.org/extra/clang-tidy/checks/list.html)
22822 Clang-tidy has a set of rules that specifically enforce the C++ Core Guidelines. These rules are named in the pattern `cppcoreguidelines-*`.
22824 ### <a name="St-cppcorecheck"></a>Tools: [CppCoreCheck](https://docs.microsoft.com/en-us/visualstudio/code-quality/using-the-cpp-core-guidelines-checkers)
22826 The Microsoft compiler's C++ code analysis contains a set of rules specifically aimed at enforcement of the C++ Core Guidelines.
22828 # <a name="S-glossary"></a>Glossary
22830 A relatively informal definition of terms used in the guidelines
22831 (based off the glossary in [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html))
22833 More information on many topics about C++ can be found on the [Standard C++ Foundation](https://isocpp.org)'s site.
22835 * *ABI*: Application Binary Interface, a specification for a specific hardware platform combined with the operating system. Contrast with API.
22836 * *abstract class*: a class that cannot be directly used to create objects; often used to define an interface to derived classes.
22837   A class is made abstract by having a pure virtual function or only protected constructors.
22838 * *abstraction*: a description of something that selectively and deliberately ignores (hides) details (e.g., implementation details); selective ignorance.
22839 * *address*: a value that allows us to find an object in a computer's memory.
22840 * *algorithm*: a procedure or formula for solving a problem; a finite series of computational steps to produce a result.
22841 * *alias*: an alternative way of referring to an object; often a name, pointer, or reference.
22842 * *API*: Application Programming Interface, a set of functions that form the communication between various software components. Contrast with ABI.
22843 * *application*: a program or a collection of programs that is considered an entity by its users.
22844 * *approximation*: something (e.g., a value or a design) that is close to the perfect or ideal (value or design).
22845   Often an approximation is a result of trade-offs among ideals.
22846 * *argument*: a value passed to a function or a template, in which it is accessed through a parameter.
22847 * *array*: a homogeneous sequence of elements, usually numbered, e.g., `[0:max)`.
22848 * *assertion*: a statement inserted into a program to state (assert) that something must always be true at this point in the program.
22849 * *base class*: a type that is intended to be derived from (e.g., has a non-`final` virtual function), and objects of the type are intended to be used only indirectly (e.g., by pointer). \[In strict terms, "base class" could be defined as "something we derived from" but we are specifying in terms of the class designer's intent.\] Typically a base class has one or more virtual functions.
22850 * *bit*: the basic unit of information in a computer. A bit can have the value 0 or the value 1.
22851 * *bug*: an error in a program.
22852 * *byte*: the basic unit of addressing in most computers. Typically, a byte holds 8 bits.
22853 * *class*: a user-defined type that can contain data members, function members, and member types.
22854 * *code*: a program or a part of a program; ambiguously used for both source code and object code.
22855 * *compiler*: a program that turns source code into object code.
22856 * *complexity*: a hard-to-precisely-define notion or measure of the difficulty of constructing a solution to a problem or of the solution itself.
22857   Sometimes complexity is used to (simply) mean an estimate of the number of operations needed to execute an algorithm.
22858 * *computation*: the execution of some code, usually taking some input and producing some output.
22859 * *concept*: (1) a notion, and idea; (2) a set of requirements, usually for a template argument.
22860 * *concrete type*: a type that is not a base class, and objects of the type are intended to be used directly (not only by pointer/indirection), its size is known, it can typically be allocated anywhere the programmer wants (e.g., stack or statically).
22861 * *constant*: a value that cannot be changed (in a given scope); not mutable.
22862 * *constructor*: an operation that initializes ("constructs") an object.
22863   Typically a constructor establishes an invariant and often acquires resources needed for an object to be used (which are then typically released by a destructor).
22864 * *container*: an object that holds elements (other objects).
22865 * *copy*: an operation that makes two objects have values that compare equal. See also move.
22866 * *correctness*: a program or a piece of a program is correct if it meets its specification.
22867   Unfortunately, a specification can be incomplete or inconsistent, or can fail to meet users' reasonable expectations.
22868   Thus, to produce acceptable code, we sometimes have to do more than just follow the formal specification.
22869 * *cost*: the expense (e.g., in programmer time, run time, or space) of producing a program or of executing it.
22870   Ideally, cost should be a function of complexity.
22871 * *customization point*: ???
22872 * *data*: values used in a computation.
22873 * *debugging*: the act of searching for and removing errors from a program; usually far less systematic than testing.
22874 * *declaration*: the specification of a name with its type in a program.
22875 * *definition*: a declaration of an entity that supplies all information necessary to complete a program using the entity.
22876   Simplified definition: a declaration that allocates memory.
22877 * *derived class*: a class derived from one or more base classes.
22878 * *design*: an overall description of how a piece of software should operate to meet its specification.
22879 * *destructor*: an operation that is implicitly invoked (called) when an object is destroyed (e.g., at the end of a scope). Often, it releases resources.
22880 * *encapsulation*: protecting something meant to be private (e.g., implementation details) from unauthorized access.
22881 * *error*: a mismatch between reasonable expectations of program behavior (often expressed as a requirement or a users' guide) and what a program actually does.
22882 * *executable*: a program ready to be run (executed) on a computer.
22883 * *feature creep*: a tendency to add excess functionality to a program "just in case."
22884 * *file*: a container of permanent information in a computer.
22885 * *floating-point number*: a computer's approximation of a real number, such as 7.93 and 10.78e-3.
22886 * *function*: a named unit of code that can be invoked (called) from different parts of a program; a logical unit of computation.
22887 * *generic programming*: a style of programming focused on the design and efficient implementation of algorithms.
22888   A generic algorithm will work for all argument types that meet its requirements. In C++, generic programming typically uses templates.
22889 * *global variable*: technically, a named object in namespace scope.
22890 * *handle*: a class that allows access to another through a member pointer or reference. See also resource, copy, move.
22891 * *header*: a file containing declarations used to share interfaces between parts of a program.
22892 * *hiding*: the act of preventing a piece of information from being directly seen or accessed.
22893   For example, a name from a nested (inner) scope can prevent that same name from an outer (enclosing) scope from being directly used.
22894 * *ideal*: the perfect version of something we are striving for. Usually we have to make trade-offs and settle for an approximation.
22895 * *implementation*: (1) the act of writing and testing code; (2) the code that implements a program.
22896 * *infinite loop*: a loop where the termination condition never becomes true. See iteration.
22897 * *infinite recursion*: a recursion that doesn't end until the machine runs out of memory to hold the calls.
22898   In reality, such recursion is never infinite but is terminated by some hardware error.
22899 * *information hiding*: the act of separating interface and implementation, thus hiding implementation details not meant for the user's attention and providing an abstraction.
22900 * *initialize*: giving an object its first (initial) value.
22901 * *input*: values used by a computation (e.g., function arguments and characters typed on a keyboard).
22902 * *integer*: a whole number, such as 42 and -99.
22903 * *interface*: a declaration or a set of declarations specifying how a piece of code (such as a function or a class) can be called.
22904 * *invariant*: something that must be always true at a given point (or points) of a program; typically used to describe the state (set of values) of an object or the state of a loop before entry into the repeated statement.
22905 * *iteration*: the act of repeatedly executing a piece of code; see recursion.
22906 * *iterator*: an object that identifies an element of a sequence.
22907 * *ISO*: International Organization for Standardization. The C++ language is an ISO standard, ISO/IEC 14882. More information at [iso.org](http://iso.org).
22908 * *library*: a collection of types, functions, classes, etc. implementing a set of facilities (abstractions) meant to be potentially used as part of more than one program.
22909 * *lifetime*: the time from the initialization of an object until it becomes unusable (goes out of scope, is deleted, or the program terminates).
22910 * *linker*: a program that combines object code files and libraries into an executable program.
22911 * *literal*: a notation that directly specifies a value, such as 12 specifying the integer value "twelve."
22912 * *loop*: a piece of code executed repeatedly; in C++, typically a for-statement or a `while`-statement.
22913 * *move*: an operation that transfers a value from one object to another leaving behind a value representing "empty." See also copy.
22914 * *move-only type*: a concrete type that is movable but not copyable.
22915 * *mutable*: changeable; the opposite of immutable, constant, and invariable.
22916 * *object*: (1) an initialized region of memory of a known type which holds a value of that type; (2) a region of memory.
22917 * *object code*: output from a compiler intended as input for a linker (for the linker to produce executable code).
22918 * *object file*: a file containing object code.
22919 * *object-oriented programming*: (OOP) a style of programming focused on the design and use of classes and class hierarchies.
22920 * *operation*: something that can perform some action, such as a function and an operator.
22921 * *output*: values produced by a computation (e.g., a function result or lines of characters written on a screen).
22922 * *overflow*: producing a value that cannot be stored in its intended target.
22923 * *overload*: defining two functions or operators with the same name but different argument (operand) types.
22924 * *override*: defining a function in a derived class with the same name and argument types as a virtual function in the base class, thus making the function callable through the interface defined by the base class.
22925 * *owner*: an object responsible for releasing a resource.
22926 * *paradigm*: a somewhat pretentious term for design or programming style; often used with the (erroneous) implication that there exists a paradigm that is superior to all others.
22927 * *parameter*: a declaration of an explicit input to a function or a template. When called, a function can access the arguments passed through the names of its parameters.
22928 * *pointer*: (1) a value used to identify a typed object in memory; (2) a variable holding such a value.
22929 * *post-condition*: a condition that must hold upon exit from a piece of code, such as a function or a loop.
22930 * *pre-condition*: a condition that must hold upon entry into a piece of code, such as a function or a loop.
22931 * *program*: code (possibly with associated data) that is sufficiently complete to be executed by a computer.
22932 * *programming*: the art of expressing solutions to problems as code.
22933 * *programming language*: a language for expressing programs.
22934 * *pseudo code*: a description of a computation written in an informal notation rather than a programming language.
22935 * *pure virtual function*: a virtual function that must be overridden in a derived class.
22936 * *RAII*: ("Resource Acquisition Is Initialization") a basic technique for resource management based on scopes.
22937 * *range*: a sequence of values that can be described by a start point and an end point. For example, `[0:5)` means the values 0, 1, 2, 3, and 4.
22938 * *recursion*: the act of a function calling itself; see also iteration.
22939 * *reference*: (1) a value describing the location of a typed value in memory; (2) a variable holding such a value.
22940 * *regular expression*: a notation for patterns in character strings.
22941 * *regular*: a semiregular type that is equality-comparable (see `std::regular` concept). After a copy, the copied object compares equal to the original object. A regular type behaves similarly to built-in types like `int` and can be compared with `==`.
22942 In particular, an object of a regular type can be copied and the result of a copy is a separate object that compares equal to the original. See also *semiregular type*.
22943 * *requirement*: (1) a description of the desired behavior of a program or part of a program; (2) a description of the assumptions a function or template makes of its arguments.
22944 * *resource*: something that is acquired and must later be released, such as a file handle, a lock, or memory. See also handle, owner.
22945 * *rounding*: conversion of a value to the mathematically nearest value of a less precise type.
22946 * *RTTI*: Run-Time Type Information. ???
22947 * *scope*: the region of program text (source code) in which a name can be referred to.
22948 * *semiregular*: a concrete type that is copyable (including movable) and default-constructible (see `std::semiregular` concept). The result of a copy is an independent object with the same value as the original. A semiregular type behaves roughly like a built-in type like `int`, but possibly without a `==` operator. See also *regular type*.
22949 * *sequence*: elements that can be visited in a linear order.
22950 * *software*: a collection of pieces of code and associated data; often used interchangeably with program.
22951 * *source code*: code as produced by a programmer and (in principle) readable by other programmers.
22952 * *source file*: a file containing source code.
22953 * *specification*: a description of what a piece of code should do.
22954 * *standard*: an officially agreed upon definition of something, such as a programming language.
22955 * *state*: a set of values.
22956 * *STL*: the containers, iterators, and algorithms part of the standard library.
22957 * *string*: a sequence of characters.
22958 * *style*: a set of techniques for programming leading to a consistent use of language features; sometimes used in a very restricted sense to refer just to low-level rules for naming and appearance of code.
22959 * *subtype*: derived type; a type that has all the properties of a type and possibly more.
22960 * *supertype*: base type; a type that has a subset of the properties of a type.
22961 * *system*: (1) a program or a set of programs for performing a task on a computer; (2) a shorthand for "operating system", that is, the fundamental execution environment and tools for a computer.
22962 * *TS*: [Technical Specification](https://www.iso.org/deliverables-all.html?type=ts), A Technical Specification addresses work still under technical development, or where it is believed that there will be a future, but not immediate, possibility of agreement on an International Standard. A Technical Specification is published for immediate use, but it also provides a means to obtain feedback. The aim is that it will eventually be transformed and republished as an International Standard.
22963 * *template*: a class or a function parameterized by one or more types or (compile-time) values; the basic C++ language construct supporting generic programming.
22964 * *testing*: a systematic search for errors in a program.
22965 * *trade-off*: the result of balancing several design and implementation criteria.
22966 * *truncation*: loss of information in a conversion from a type into another that cannot exactly represent the value to be converted.
22967 * *type*: something that defines a set of possible values and a set of operations for an object.
22968 * *uninitialized*: the (undefined) state of an object before it is initialized.
22969 * *unit*: (1) a standard measure that gives meaning to a value (e.g., km for a distance); (2) a distinguished (e.g., named) part of a larger whole.
22970 * *use case*: a specific (typically simple) use of a program meant to test its functionality and demonstrate its purpose.
22971 * *value*: a set of bits in memory interpreted according to a type.
22972 * *value type*: a term some people use to mean a regular or semiregular type.
22973 * *variable*: a named object of a given type; contains a value unless uninitialized.
22974 * *virtual function*: a member function that can be overridden in a derived class.
22975 * *word*: a basic unit of memory in a computer, often the unit used to hold an integer.
22977 # <a name="S-unclassified"></a>To-do: Unclassified proto-rules
22979 This is our to-do list.
22980 Eventually, the entries will become rules or parts of rules.
22981 Alternatively, we will decide that no change is needed and delete the entry.
22983 * No long-distance friendship
22984 * Should physical design (what's in a file) and large-scale design (libraries, groups of libraries) be addressed?
22985 * Namespaces
22986 * Avoid using directives in the global scope (except for std, and other "fundamental" namespaces (e.g. experimental))
22987 * How granular should namespaces be? All classes/functions designed to work together and released together (as defined in Sutter/Alexandrescu) or something narrower or wider?
22988 * Should there be inline namespaces (à la `std::literals::*_literals`)?
22989 * Avoid implicit conversions
22990 * Const member functions should be thread safe ... aka, but I don't really change the variable, just assign it a value the first time it's called ... argh
22991 * Always initialize variables, use initialization lists for member variables.
22992 * Anyone writing a public interface which takes or returns `void*` should have their toes set on fire. That one has been a personal favorite of mine for a number of years. :)
22993 * Use `const`-ness wherever possible: member functions, variables and (yippee) `const_iterators`
22994 * Use `auto`
22995 * `(size)` vs. `{initializers}` vs. `{Extent{size}}`
22996 * Don't overabstract
22997 * Never pass a pointer down the call stack
22998 * falling through a function bottom
22999 * Should there be guidelines to choose between polymorphisms? YES. classic (virtual functions, reference semantics) vs. Sean Parent style (value semantics, type-erased, kind of like `std::function`)  vs. CRTP/static? YES Perhaps even vs. tag dispatch?
23000 * should virtual calls be banned from ctors/dtors in your guidelines? YES. A lot of people ban them, even though I think it's a big strength of C++ that they are ??? -preserving (D disappointed me so much when it went the Java way). WHAT WOULD BE A GOOD EXAMPLE?
23001 * Speaking of lambdas, what would weigh in on the decision between lambdas and (local?) classes in algorithm calls and other callback scenarios?
23002 * And speaking of `std::bind`, Stephen T. Lavavej criticizes it so much I'm starting to wonder if it is indeed going to fade away in future. Should lambdas be recommended instead?
23003 * What to do with leaks out of temporaries? : `p = (s1 + s2).c_str();`
23004 * pointer/iterator invalidation leading to dangling pointers:
23006         void bad()
23007         {
23008             int* p = new int[700];
23009             int* q = &p[7];
23010             delete p;
23012             vector<int> v(700);
23013             int* q2 = &v[7];
23014             v.resize(900);
23016             // ... use q and q2 ...
23017         }
23019 * LSP
23020 * private inheritance vs/and membership
23021 * avoid static class members variables (race conditions, almost-global variables)
23023 * Use RAII lock guards (`lock_guard`, `unique_lock`, `shared_lock`), never call `mutex.lock` and `mutex.unlock` directly (RAII)
23024 * Prefer non-recursive locks (often used to work around bad reasoning, overhead)
23025 * Join your threads! (because of `std::terminate` in destructor if not joined or detached ... is there a good reason to detach threads?) -- ??? could support library provide a RAII wrapper for `std::thread`?
23026 * If two or more mutexes must be acquired at the same time, use `std::lock` (or another deadlock avoidance algorithm?)
23027 * When using a `condition_variable`, always protect the condition by a mutex (atomic bool whose value is set outside of the mutex is wrong!), and use the same mutex for the condition variable itself.
23028 * Never use `atomic_compare_exchange_strong` with `std::atomic<user-defined-struct>` (differences in padding matter, while `compare_exchange_weak` in a loop converges to stable padding)
23029 * individual `shared_future` objects are not thread-safe: two threads cannot wait on the same `shared_future` object (they can wait on copies of a `shared_future` that refer to the same shared state)
23030 * individual `shared_ptr` objects are not thread-safe: different threads can call non-`const` member functions on *different* `shared_ptr`s that refer to the same shared object, but one thread cannot call a non-`const` member function of a `shared_ptr` object while another thread accesses that same `shared_ptr` object (if you need that, consider `atomic_shared_ptr` instead)
23032 * rules for arithmetic
23034 # Bibliography
23036 * <a name="Abrahams01"></a>
23037   \[Abrahams01]:  D. Abrahams. [Exception-Safety in Generic Components](http://www.boost.org/community/exception_safety.html).
23038 * <a name="Alexandrescu01"></a>
23039   \[Alexandrescu01]:  A. Alexandrescu. Modern C++ Design (Addison-Wesley, 2001).
23040 * <a name="Cplusplus03"></a>
23041   \[C++03]:           ISO/IEC 14882:2003(E), Programming Languages — C++ (updated ISO and ANSI C++ Standard including the contents of (C++98) plus errata corrections).
23042 * <a name="Cargill92"></a>
23043   \[Cargill92]:       T. Cargill. C++ Programming Style (Addison-Wesley, 1992).
23044 * <a name="Cline99"></a>
23045   \[Cline99]:         M. Cline, G. Lomow, and M. Girou. C++ FAQs (2ndEdition) (Addison-Wesley, 1999).
23046 * <a name="Dewhurst03"></a>
23047   \[Dewhurst03]:      S. Dewhurst. C++ Gotchas (Addison-Wesley, 2003).
23048 * <a name="Henricson97"></a>
23049   \[Henricson97]:     M. Henricson and E. Nyquist. Industrial Strength C++ (Prentice Hall, 1997).
23050 * <a name="Koenig97"></a>
23051   \[Koenig97]:        A. Koenig and B. Moo. Ruminations on C++ (Addison-Wesley, 1997).
23052 * <a name="Lakos96"></a>
23053   \[Lakos96]:         J. Lakos. Large-Scale C++ Software Design (Addison-Wesley, 1996).
23054 * <a name="Meyers96"></a>
23055   \[Meyers96]:        S. Meyers. More Effective C++ (Addison-Wesley, 1996).
23056 * <a name="Meyers97"></a>
23057   \[Meyers97]:        S. Meyers. Effective C++ (2nd Edition) (Addison-Wesley, 1997).
23058 * <a name="Meyers01"></a>
23059   \[Meyers01]:        S. Meyers. Effective STL (Addison-Wesley, 2001).
23060 * <a name="Meyers05"></a>
23061   \[Meyers05]:        S. Meyers. Effective C++ (3rd Edition) (Addison-Wesley, 2005).
23062 * <a name="Meyers15"></a>
23063   \[Meyers15]:        S. Meyers. Effective Modern C++ (O'Reilly, 2015).
23064 * <a name="Murray93"></a>
23065   \[Murray93]:        R. Murray. C++ Strategies and Tactics (Addison-Wesley, 1993).
23066 * <a name="Stroustrup94"></a>
23067   \[Stroustrup94]:    B. Stroustrup. The Design and Evolution of C++ (Addison-Wesley, 1994).
23068 * <a name="Stroustrup00"></a>
23069   \[Stroustrup00]:    B. Stroustrup. The C++ Programming Language (Special 3rdEdition) (Addison-Wesley, 2000).
23070 * <a name="Stroustrup05"></a>
23071   \[Stroustrup05]:    B. Stroustrup. [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
23072 * <a name="Stroustrup13"></a>
23073   \[Stroustrup13]:    B. Stroustrup. [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html). Addison Wesley 2013.
23074 * <a name="Stroustrup14"></a>
23075   \[Stroustrup14]:    B. Stroustrup. [A Tour of C++](http://www.stroustrup.com/Tour.html).
23076   Addison Wesley 2014.
23077 * <a name="Stroustrup15"></a>
23078   \[Stroustrup15]:    B. Stroustrup, Herb Sutter, and G. Dos Reis: [A brief introduction to C++'s model for type- and resource-safety](https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/Introduction%20to%20type%20and%20resource%20safety.pdf).
23079 * <a name="SuttHysl04b"></a>
23080   \[SuttHysl04b]:     H. Sutter and J. Hyslop. [Collecting Shared Objects](https://web.archive.org/web/20120926011837/http://www.drdobbs.com/collecting-shared-objects/184401839) (C/C++ Users Journal, 22(8), August 2004).
23081 * <a name="SuttAlex05"></a>
23082   \[SuttAlex05]:      H. Sutter and  A. Alexandrescu. C++ Coding Standards. Addison-Wesley 2005.
23083 * <a name="Sutter00"></a>
23084   \[Sutter00]:        H. Sutter. Exceptional C++ (Addison-Wesley, 2000).
23085 * <a name="Sutter02"></a>
23086   \[Sutter02]:        H. Sutter. More Exceptional C++ (Addison-Wesley, 2002).
23087 * <a name="Sutter04"></a>
23088   \[Sutter04]:        H. Sutter. Exceptional C++ Style (Addison-Wesley, 2004).
23089 * <a name="Taligent94"></a>
23090   \[Taligent94]: Taligent's Guide to Designing Programs (Addison-Wesley, 1994).