Travis CI: (#1469)
[CppCoreGuidelines.git] / CppCoreGuidelines.md
blob83d8ce895ace8780f1733485172ab17d02886d32
1 # <a name="main"></a>C++ Core Guidelines
3 May 2, 2019
6 Editors:
8 * [Bjarne Stroustrup](http://www.stroustrup.com)
9 * [Herb Sutter](http://herbsutter.com/)
11 This is a living document under continuous improvement.
12 Had it been an open-source (code) project, this would have been release 0.8.
13 Copying, use, modification, and creation of derivative works from this project is licensed under an MIT-style license.
14 Contributing to this project requires agreeing to a Contributor License. See the accompanying [LICENSE](LICENSE) file for details.
15 We make this project available to "friendly users" to use, copy, modify, and derive from, hoping for constructive input.
17 Comments and suggestions for improvements are most welcome.
18 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
19 When commenting, please note [the introduction](#S-introduction) that outlines our aims and general approach.
20 The list of contributors is [here](#SS-ack).
22 Problems:
24 * The sets of rules have not been completely checked for completeness, consistency, or enforceability.
25 * Triple question marks (???) mark known missing information
26 * Update reference sections; many pre-C++11 sources are too old.
27 * For a more-or-less up-to-date to-do list see: [To-do: Unclassified proto-rules](#S-unclassified)
29 You can [read an explanation of the scope and structure of this Guide](#S-abstract) or just jump straight in:
31 * [In: Introduction](#S-introduction)
32 * [P: Philosophy](#S-philosophy)
33 * [I: Interfaces](#S-interfaces)
34 * [F: Functions](#S-functions)
35 * [C: Classes and class hierarchies](#S-class)
36 * [Enum: Enumerations](#S-enum)
37 * [R: Resource management](#S-resource)
38 * [ES: Expressions and statements](#S-expr)
39 * [Per: Performance](#S-performance)
40 * [CP: Concurrency and parallelism](#S-concurrency)
41 * [E: Error handling](#S-errors)
42 * [Con: Constants and immutability](#S-const)
43 * [T: Templates and generic programming](#S-templates)
44 * [CPL: C-style programming](#S-cpl)
45 * [SF: Source files](#S-source)
46 * [SL: The Standard Library](#S-stdlib)
48 Supporting sections:
50 * [A: Architectural ideas](#S-A)
51 * [NR: Non-Rules and myths](#S-not)
52 * [RF: References](#S-references)
53 * [Pro: Profiles](#S-profile)
54 * [GSL: Guidelines support library](#S-gsl)
55 * [NL: Naming and layout rules](#S-naming)
56 * [FAQ: Answers to frequently asked questions](#S-faq)
57 * [Appendix A: Libraries](#S-libraries)
58 * [Appendix B: Modernizing code](#S-modernizing)
59 * [Appendix C: Discussion](#S-discussion)
60 * [Appendix D: Supporting tools](#S-tools)
61 * [Glossary](#S-glossary)
62 * [To-do: Unclassified proto-rules](#S-unclassified)
64 You can sample rules for specific language features:
66 * assignment:
67 [regular types](#Rc-regular) --
68 [prefer initialization](#Rc-initialize) --
69 [copy](#Rc-copy-semantic) --
70 [move](#Rc-move-semantic) --
71 [other operations](#Rc-matched) --
72 [default](#Rc-eqdefault)
73 * `class`:
74 [data](#Rc-org) --
75 [invariant](#Rc-struct) --
76 [members](#Rc-member) --
77 [helpers](#Rc-helper) --
78 [concrete types](#SS-concrete) --
79 [ctors, =, and dtors](#S-ctor) --
80 [hierarchy](#SS-hier) --
81 [operators](#SS-overload)
82 * `concept`:
83 [rules](#SS-concepts) --
84 [in generic programming](#Rt-raise) --
85 [template arguments](#Rt-concepts) --
86 [semantics](#Rt-low)
87 * constructor:
88 [invariant](#Rc-struct) --
89 [establish invariant](#Rc-ctor) --
90 [`throw`](#Rc-throw) --
91 [default](#Rc-default0) --
92 [not needed](#Rc-default) --
93 [`explicit`](#Rc-explicit) --
94 [delegating](#Rc-delegating) --
95 [`virtual`](#Rc-ctor-virtual)
96 * derived `class`:
97 [when to use](#Rh-domain) --
98 [as interface](#Rh-abstract) --
99 [destructors](#Rh-dtor) --
100 [copy](#Rh-copy) --
101 [getters and setters](#Rh-get) --
102 [multiple inheritance](#Rh-mi-interface) --
103 [overloading](#Rh-using) --
104 [slicing](#Rc-copy-virtual) --
105 [`dynamic_cast`](#Rh-dynamic_cast)
106 * destructor:
107 [and constructors](#Rc-matched) --
108 [when needed?](#Rc-dtor) --
109 [may not fail](#Rc-dtor-fail)
110 * exception:
111 [errors](#S-errors) --
112 [`throw`](#Re-throw) --
113 [for errors only](#Re-errors) --
114 [`noexcept`](#Re-noexcept) --
115 [minimize `try`](#Re-catch) --
116 [what if no exceptions?](#Re-no-throw-codes)
117 * `for`:
118 [range-for and for](#Res-for-range) --
119 [for and while](#Res-for-while) --
120 [for-initializer](#Res-for-init) --
121 [empty body](#Res-empty) --
122 [loop variable](#Res-loop-counter) --
123 [loop variable type ???](#Res-???)
124 * function:
125 [naming](#Rf-package) --
126 [single operation](#Rf-logical) --
127 [no throw](#Rf-noexcept) --
128 [arguments](#Rf-smart) --
129 [argument passing](#Rf-conventional) --
130 [multiple return values](#Rf-out-multi) --
131 [pointers](#Rf-return-ptr) --
132 [lambdas](#Rf-capture-vs-overload)
133 * `inline`:
134 [small functions](#Rf-inline) --
135 [in headers](#Rs-inline)
136 * initialization:
137 [always](#Res-always) --
138 [prefer `{}`](#Res-list) --
139 [lambdas](#Res-lambda-init) --
140 [in-class initializers](#Rc-in-class-initializer) --
141 [class members](#Rc-initialize) --
142 [factory functions](#Rc-factory)
143 * lambda expression:
144 [when to use](#SS-lambdas)
145 * operator:
146 [conventional](#Ro-conventional) --
147 [avoid conversion operators](#Ro-conversion) --
148 [and lambdas](#Ro-lambda)
149 * `public`, `private`, and `protected`:
150 [information hiding](#Rc-private) --
151 [consistency](#Rh-public) --
152 [`protected`](#Rh-protected)
153 * `static_assert`:
154 [compile-time checking](#Rp-compile-time) --
155 [and concepts](#Rt-check-class)
156 * `struct`:
157 [for organizing data](#Rc-org) --
158 [use if no invariant](#Rc-struct) --
159 [no private members](#Rc-class)
160 * `template`:
161 [abstraction](#Rt-raise) --
162 [containers](#Rt-cont) --
163 [concepts](#Rt-concepts)
164 * `unsigned`:
165 [and signed](#Res-mix) --
166 [bit manipulation](#Res-unsigned)
167 * `virtual`:
168 [interfaces](#Ri-abstract) --
169 [not `virtual`](#Rc-concrete) --
170 [destructor](#Rc-dtor-virtual) --
171 [never fail](#Rc-dtor-fail)
173 You can look at design concepts used to express the rules:
175 * assertion: ???
176 * error: ???
177 * exception: exception guarantee (???)
178 * failure: ???
179 * invariant: ???
180 * leak: ???
181 * library: ???
182 * precondition: ???
183 * postcondition: ???
184 * resource: ???
186 # <a name="S-abstract"></a>Abstract
188 This document is a set of guidelines for using C++ well.
189 The aim of this document is to help people to use modern C++ effectively.
190 By "modern C++" we mean effective use of the ISO C++ standard (currently C++17, but almost all of our recommendations also apply to C++14 and C++11).
191 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?
193 The guidelines are focused on relatively high-level issues, such as interfaces, resource management, memory management, and concurrency.
194 Such rules affect application architecture and library design.
195 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.
196 And it will run fast -- you can afford to do things right.
198 We are less concerned with low-level issues, such as naming conventions and indentation style.
199 However, no topic that can help a programmer is out of bounds.
201 Our initial set of rules emphasizes safety (of various forms) and simplicity.
202 They may very well be too strict.
203 We expect to have to introduce more exceptions to better accommodate real-world needs.
204 We also need more rules.
206 You will find some of the rules contrary to your expectations or even contrary to your experience.
207 If we haven't suggested you change your coding style in any way, we have failed!
208 Please try to verify or disprove rules!
209 In particular, we'd really like to have some of our rules backed up with measurements or better examples.
211 You will find some of the rules obvious or even trivial.
212 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.
214 Many of the rules are designed to be supported by an analysis tool.
215 Violations of rules will be flagged with references (or links) to the relevant rule.
216 We do not expect you to memorize all the rules before trying to write code.
217 One way of thinking about these guidelines is as a specification for tools that happens to be readable by humans.
219 The rules are meant for gradual introduction into a code base.
220 We plan to build tools for that and hope others will too.
222 Comments and suggestions for improvements are most welcome.
223 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
225 # <a name="S-introduction"></a>In: Introduction
227 This is a set of core guidelines for modern C++ (currently C++17) taking likely future enhancements and ISO Technical Specifications (TSs) into account.
228 The aim is to help C++ programmers to write simpler, more efficient, more maintainable code.
230 Introduction summary:
232 * [In.target: Target readership](#SS-readers)
233 * [In.aims: Aims](#SS-aims)
234 * [In.not: Non-aims](#SS-non)
235 * [In.force: Enforcement](#SS-force)
236 * [In.struct: The structure of this document](#SS-struct)
237 * [In.sec: Major sections](#SS-sec)
239 ## <a name="SS-readers"></a>In.target: Target readership
241 All C++ programmers. This includes [programmers who might consider C](#S-cpl).
243 ## <a name="SS-aims"></a>In.aims: Aims
245 The purpose of this document is to help developers to adopt modern C++ (currently C++17) and to achieve a more uniform style across code bases.
247 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.
248 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").
249 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.
250 Remember:
252 ### <a name="R0"></a>In.0: Don't panic!
254 Take the time to understand the implications of a guideline rule on your program.
256 These guidelines are designed according to the "subset of superset" principle ([Stroustrup05](#Stroustrup05)).
257 They do not simply define a subset of C++ to be used (for reliability, safety, performance, or whatever).
258 Instead, they strongly recommend the use of a few simple "extensions" ([library components](#S-gsl))
259 that make the use of the most error-prone features of C++ redundant, so that they can be banned (in our set of rules).
261 The rules emphasize static type safety and resource safety.
262 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).
263 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.
265 Many of the rules are prescriptive.
266 We are uncomfortable with rules that simply state "don't do that!" without offering an alternative.
267 One consequence of that is that some rules can be supported only by heuristics, rather than precise and mechanically verifiable checks.
268 Other rules articulate general principles. For these more general rules, more detailed and specific rules provide partial checking.
270 These guidelines address the core of C++ and its use.
271 We expect that most large organizations, specific application areas, and even large projects will need further rules, possibly further restrictions, and further library support.
272 For example, hard-real-time programmers typically can't use free store (dynamic memory) freely and will be restricted in their choice of libraries.
273 We encourage the development of such more specific rules as addenda to these core guidelines.
274 Build your ideal small foundation library and use that, rather than lowering your level of programming to glorified assembly code.
276 The rules are designed to allow [gradual adoption](#S-modernizing).
278 Some rules aim to increase various forms of safety while others aim to reduce the likelihood of accidents, many do both.
279 The guidelines aimed at preventing accidents often ban perfectly legal C++.
280 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.
282 ## <a name="SS-non"></a>In.not: Non-aims
284 The rules are not intended to be minimal or orthogonal.
285 In particular, general rules can be simple, but unenforceable.
286 Also, it is often hard to understand the implications of a general rule.
287 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.
288 We provide rules aimed at helping novices as well as rules supporting expert use.
289 Some rules can be completely enforced, but others are based on heuristics.
291 These rules are not meant to be read serially, like a book.
292 You can browse through them using the links.
293 However, their main intended use is to be targets for tools.
294 That is, a tool looks for violations and the tool returns links to violated rules.
295 The rules then provide reasons, examples of potential consequences of the violation, and suggested remedies.
297 These guidelines are not intended to be a substitute for a tutorial treatment of C++.
298 If you need a tutorial for some given level of experience, see [the references](#S-references).
300 This is not a guide on how to convert old C++ code to more modern code.
301 It is meant to articulate ideas for new code in a concrete fashion.
302 However, see [the modernization section](#S-modernizing) for some possible approaches to modernizing/rejuvenating/upgrading.
303 Importantly, the rules support gradual adoption: It is typically infeasible to completely convert a large code base all at once.
305 These guidelines are not meant to be complete or exact in every language-technical detail.
306 For the final word on language definition issues, including every exception to general rules and every feature, see the ISO C++ standard.
308 The rules are not intended to force you to write in an impoverished subset of C++.
309 They are *emphatically* not meant to define a, say, Java-like subset of C++.
310 They are not meant to define a single "one true C++" language.
311 We value expressiveness and uncompromised performance.
313 The rules are not value-neutral.
314 They are meant to make code simpler and more correct/safer than most existing C++ code, without loss of performance.
315 They are meant to inhibit perfectly valid C++ code that correlates with errors, spurious complexity, and poor performance.
317 The rules are not precise to the point where a person (or machine) can follow them blindly.
318 The enforcement parts try to be that, but we would rather leave a rule or a definition a bit vague
319 and open to interpretation than specify something precisely and wrong.
320 Sometimes, precision comes only with time and experience.
321 Design is not (yet) a form of Math.
323 The rules are not perfect.
324 A rule can do harm by prohibiting something that is useful in a given situation.
325 A rule can do harm by failing to prohibit something that enables a serious error in a given situation.
326 A rule can do a lot of harm by being vague, ambiguous, unenforceable, or by enabling every solution to a problem.
327 It is impossible to completely meet the "do no harm" criteria.
328 Instead, our aim is the less ambitious: "Do the most good for most programmers";
329 if you cannot live with a rule, object to it, ignore it, but don't water it down until it becomes meaningless.
330 Also, suggest an improvement.
332 ## <a name="SS-force"></a>In.force: Enforcement
334 Rules with no enforcement are unmanageable for large code bases.
335 Enforcement of all rules is possible only for a small weak set of rules or for a specific user community.
337 * But we want lots of rules, and we want rules that everybody can use.
338 * But different people have different needs.
339 * But people don't like to read lots of rules.
340 * But people can't remember many rules.
342 So, we need subsetting to meet a variety of needs.
344 * But arbitrary subsetting leads to chaos.
346 We want guidelines that help a lot of people, make code more uniform, and strongly encourage people to modernize their code.
347 We want to encourage best practices, rather than leave all to individual choices and management pressures.
348 The ideal is to use all rules; that gives the greatest benefits.
350 This adds up to quite a few dilemmas.
351 We try to resolve those using tools.
352 Each rule has an **Enforcement** section listing ideas for enforcement.
353 Enforcement might be done by code review, by static analysis, by compiler, or by run-time checks.
354 Wherever possible, we prefer "mechanical" checking (humans are slow, inaccurate, and bore easily) and static checking.
355 Run-time checks are suggested only rarely where no alternative exists; we do not want to introduce "distributed fat".
356 Where appropriate, we label a rule (in the **Enforcement** sections) with the name of groups of related rules (called "profiles").
357 A rule can be part of several profiles, or none.
358 For a start, we have a few profiles corresponding to common needs (desires, ideals):
360 * **type**: No type violations (reinterpreting a `T` as a `U` through casts, unions, or varargs)
361 * **bounds**: No bounds violations (accessing beyond the range of an array)
362 * **lifetime**: No leaks (failing to `delete` or multiple `delete`) and no access to invalid objects (dereferencing `nullptr`, using a dangling reference).
364 The profiles are intended to be used by tools, but also serve as an aid to the human reader.
365 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.
367 Tools that implement these rules shall respect the following syntax to explicitly suppress a rule:
369     [[gsl::suppress(tag)]]
371 where "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
372 name of a profile group-of-rules ("type", "bounds", or "lifetime"),
373 or a specific rule in a profile ([type.4](#Pro-type-cstylecast), or [bounds.2](#Pro-bounds-arrayindex)).
375 ## <a name="SS-struct"></a>In.struct: The structure of this document
377 Each rule (guideline, suggestion) can have several parts:
379 * The rule itself -- e.g., **no naked `new`**
380 * A rule reference number -- e.g., **C.7** (the 7th rule related to classes).
381   Since the major sections are not inherently ordered, we use letters as the first part of a rule reference "number".
382   We leave gaps in the numbering to minimize "disruption" when we add or remove rules.
383 * **Reason**s (rationales) -- because programmers find it hard to follow rules they don't understand
384 * **Example**s -- because rules are hard to understand in the abstract; can be positive or negative
385 * **Alternative**s -- for "don't do this" rules
386 * **Exception**s -- we prefer simple general rules. However, many rules apply widely, but not universally, so exceptions must be listed
387 * **Enforcement** -- ideas about how the rule might be checked "mechanically"
388 * **See also**s -- references to related rules and/or further discussion (in this document or elsewhere)
389 * **Note**s (comments) -- something that needs saying that doesn't fit the other classifications
390 * **Discussion** -- references to more extensive rationale and/or examples placed outside the main lists of rules
392 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.
393 We hope that "mechanical" tools will improve with time to approximate what such an expert programmer notices.
394 Also, we assume that the rules will be refined over time to make them more precise and checkable.
396 A rule is aimed at being simple, rather than carefully phrased to mention every alternative and special case.
397 Such information is found in the **Alternative** paragraphs and the [Discussion](#S-discussion) sections.
398 If you don't understand a rule or disagree with it, please visit its **Discussion**.
399 If you feel that a discussion is missing or incomplete, enter an [Issue](https://github.com/isocpp/CppCoreGuidelines/issues)
400 explaining your concerns and possibly a corresponding PR.
402 This is not a language manual.
403 It is meant to be helpful, rather than complete, fully accurate on technical details, or a guide to existing code.
404 Recommended information sources can be found in [the references](#S-references).
406 ## <a name="SS-sec"></a>In.sec: Major sections
408 * [In: Introduction](#S-introduction)
409 * [P: Philosophy](#S-philosophy)
410 * [I: Interfaces](#S-interfaces)
411 * [F: Functions](#S-functions)
412 * [C: Classes and class hierarchies](#S-class)
413 * [Enum: Enumerations](#S-enum)
414 * [R: Resource management](#S-resource)
415 * [ES: Expressions and statements](#S-expr)
416 * [Per: Performance](#S-performance)
417 * [CP: Concurrency and parallelism](#S-concurrency)
418 * [E: Error handling](#S-errors)
419 * [Con: Constants and immutability](#S-const)
420 * [T: Templates and generic programming](#S-templates)
421 * [CPL: C-style programming](#S-cpl)
422 * [SF: Source files](#S-source)
423 * [SL: The Standard Library](#S-stdlib)
425 Supporting sections:
427 * [A: Architectural ideas](#S-A)
428 * [NR: Non-Rules and myths](#S-not)
429 * [RF: References](#S-references)
430 * [Pro: Profiles](#S-profile)
431 * [GSL: Guidelines support library](#S-gsl)
432 * [NL: Naming and layout rules](#S-naming)
433 * [FAQ: Answers to frequently asked questions](#S-faq)
434 * [Appendix A: Libraries](#S-libraries)
435 * [Appendix B: Modernizing code](#S-modernizing)
436 * [Appendix C: Discussion](#S-discussion)
437 * [Appendix D: Supporting tools](#S-tools)
438 * [Glossary](#S-glossary)
439 * [To-do: Unclassified proto-rules](#S-unclassified)
441 These sections are not orthogonal.
443 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.
444 The main section abbreviations are also used in rule numbers (e.g., "C.11" for "Make concrete types regular").
446 # <a name="S-philosophy"></a>P: Philosophy
448 The rules in this section are very general.
450 Philosophy rules summary:
452 * [P.1: Express ideas directly in code](#Rp-direct)
453 * [P.2: Write in ISO Standard C++](#Rp-Cplusplus)
454 * [P.3: Express intent](#Rp-what)
455 * [P.4: Ideally, a program should be statically type safe](#Rp-typesafe)
456 * [P.5: Prefer compile-time checking to run-time checking](#Rp-compile-time)
457 * [P.6: What cannot be checked at compile time should be checkable at run time](#Rp-run-time)
458 * [P.7: Catch run-time errors early](#Rp-early)
459 * [P.8: Don't leak any resources](#Rp-leak)
460 * [P.9: Don't waste time or space](#Rp-waste)
461 * [P.10: Prefer immutable data to mutable data](#Rp-mutable)
462 * [P.11: Encapsulate messy constructs, rather than spreading through the code](#Rp-library)
463 * [P.12: Use supporting tools as appropriate](#Rp-tools)
464 * [P.13: Use support libraries as appropriate](#Rp-lib)
466 Philosophical rules are generally not mechanically checkable.
467 However, individual rules reflecting these philosophical themes are.
468 Without a philosophical basis, the more concrete/specific/checkable rules lack rationale.
470 ### <a name="Rp-direct"></a>P.1: Express ideas directly in code
472 ##### Reason
474 Compilers don't read comments (or design documents) and neither do many programmers (consistently).
475 What is expressed in code has defined semantics and can (in principle) be checked by compilers and other tools.
477 ##### Example
479     class Date {
480         // ...
481     public:
482         Month month() const;  // do
483         int month();          // don't
484         // ...
485     };
487 The first declaration of `month` is explicit about returning a `Month` and about not modifying the state of the `Date` object.
488 The second version leaves the reader guessing and opens more possibilities for uncaught bugs.
490 ##### Example, bad
492 This loop is a restricted form of `std::find`:
494     void f(vector<string>& v)
495     {
496         string val;
497         cin >> val;
498         // ...
499         int index = -1;                    // bad, plus should use gsl::index
500         for (int i = 0; i < v.size(); ++i) {
501             if (v[i] == val) {
502                 index = i;
503                 break;
504             }
505         }
506         // ...
507     }
509 ##### Example, good
511 A much clearer expression of intent would be:
513     void f(vector<string>& v)
514     {
515         string val;
516         cin >> val;
517         // ...
518         auto p = find(begin(v), end(v), val);  // better
519         // ...
520     }
522 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.
524 A C++ programmer should know the basics of the standard library, and use it where appropriate.
525 Any programmer should know the basics of the foundation libraries of the project being worked on, and use them appropriately.
526 Any programmer using these guidelines should know the [guidelines support library](#S-gsl), and use it appropriately.
528 ##### Example
530     change_speed(double s);   // bad: what does s signify?
531     // ...
532     change_speed(2.3);
534 A better approach is to be explicit about the meaning of the double (new speed or delta on old speed?) and the unit used:
536     change_speed(Speed s);    // better: the meaning of s is specified
537     // ...
538     change_speed(2.3);        // error: no unit
539     change_speed(23m / 10s);  // meters per second
541 We could have accepted a plain (unit-less) `double` as a delta, but that would have been error-prone.
542 If we wanted both absolute speed and deltas, we would have defined a `Delta` type.
544 ##### Enforcement
546 Very hard in general.
548 * use `const` consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference)
549 * flag uses of casts (casts neuter the type system)
550 * detect code that mimics the standard library (hard)
552 ### <a name="Rp-Cplusplus"></a>P.2: Write in ISO Standard C++
554 ##### Reason
556 This is a set of guidelines for writing ISO Standard C++.
558 ##### Note
560 There are environments where extensions are necessary, e.g., to access system resources.
561 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.
563 Extensions often do not have rigorously defined semantics.  Even extensions that
564 are common and implemented by multiple compilers may have slightly different
565 behaviors and edge case behavior as a direct result of *not* having a rigorous
566 standard definition.  With sufficient use of any such extension, expected
567 portability will be impacted.
569 ##### Note
571 Using valid ISO C++ does not guarantee portability (let alone correctness).
572 Avoid dependence on undefined behavior (e.g., [undefined order of evaluation](#Res-order))
573 and be aware of constructs with implementation defined meaning (e.g., `sizeof(int)`).
575 ##### Note
577 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.
578 In such cases, control their (dis)use with an extension of these Coding Guidelines customized to the specific environment.
580 ##### Enforcement
582 Use an up-to-date C++ compiler (currently C++17, C++14, or C++11) with a set of options that do not accept extensions.
584 ### <a name="Rp-what"></a>P.3: Express intent
586 ##### Reason
588 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.
590 ##### Example
592     gsl::index i = 0;
593     while (i < v.size()) {
594         // ... do something with v[i] ...
595     }
597 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 may or may not be intended. The reader cannot know from just this section of code.
599 Better:
601     for (const auto& x : v) { /* do something with the value of x */ }
603 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:
605     for (auto& x : v) { /* modify x */ }
607 For more details about for-statements, see [ES.71](#Res-for-range).
608 Sometimes better still, use a named algorithm. This example uses the `for_each` from the Ranges TS because it directly expresses the intent:
610     for_each(v, [](int x) { /* do something with the value of x */ });
611     for_each(par, v, [](int x) { /* do something with the value of x */ });
613 The last variant makes it clear that we are not interested in the order in which the elements of `v` are handled.
615 A programmer should be familiar with
617 * [The guidelines support library](#S-gsl)
618 * [The ISO C++ Standard Library](#S-stdlib)
619 * Whatever foundation libraries are used for the current project(s)
621 ##### Note
623 Alternative formulation: Say what should be done, rather than just how it should be done.
625 ##### Note
627 Some language constructs express intent better than others.
629 ##### Example
631 If two `int`s are meant to be the coordinates of a 2D point, say so:
633     draw_line(int, int, int, int);  // obscure
634     draw_line(Point, Point);        // clearer
636 ##### Enforcement
638 Look for common patterns for which there are better alternatives
640 * simple `for` loops vs. range-`for` loops
641 * `f(T*, int)` interfaces vs. `f(span<T>)` interfaces
642 * loop variables in too large a scope
643 * naked `new` and `delete`
644 * functions with many parameters of built-in types
646 There is a huge scope for cleverness and semi-automated program transformation.
648 ### <a name="Rp-typesafe"></a>P.4: Ideally, a program should be statically type safe
650 ##### Reason
652 Ideally, a program would be completely statically (compile-time) type safe.
653 Unfortunately, that is not possible. Problem areas:
655 * unions
656 * casts
657 * array decay
658 * range errors
659 * narrowing conversions
661 ##### Note
663 These areas are sources of serious problems (e.g., crashes and security violations).
664 We try to provide alternative techniques.
666 ##### Enforcement
668 We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs.
669 Always suggest an alternative.
670 For example:
672 * unions -- use `variant` (in C++17)
673 * casts -- minimize their use; templates can help
674 * array decay -- use `span` (from the GSL)
675 * range errors -- use `span`
676 * narrowing conversions -- minimize their use and use `narrow` or `narrow_cast` (from the GSL) where they are necessary
678 ### <a name="Rp-compile-time"></a>P.5: Prefer compile-time checking to run-time checking
680 ##### Reason
682 Code clarity and performance.
683 You don't need to write error handlers for errors caught at compile time.
685 ##### Example
687     // Int is an alias used for integers
688     int bits = 0;         // don't: avoidable code
689     for (Int i = 1; i; i <<= 1)
690         ++bits;
691     if (bits < 32)
692         cerr << "Int too small\n";
694 This example fails to achieve what it is trying to achieve (because overflow is undefined) and should be replaced with a simple `static_assert`:
696     // Int is an alias used for integers
697     static_assert(sizeof(Int) >= 4);    // do: compile-time check
699 Or better still just use the type system and replace `Int` with `int32_t`.
701 ##### Example
703     void read(int* p, int n);   // read max n integers into *p
705     int a[100];
706     read(a, 1000);    // bad, off the end
708 better
710     void read(span<int> r); // read into the range of integers r
712     int a[100];
713     read(a);        // better: let the compiler figure out the number of elements
715 **Alternative formulation**: Don't postpone to run time what can be done well at compile time.
717 ##### Enforcement
719 * Look for pointer arguments.
720 * Look for run-time checks for range violations.
722 ### <a name="Rp-run-time"></a>P.6: What cannot be checked at compile time should be checkable at run time
724 ##### Reason
726 Leaving hard-to-detect errors in a program is asking for crashes and bad results.
728 ##### Note
730 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).
732 ##### Example, bad
734     // separately compiled, possibly dynamically loaded
735     extern void f(int* p);
737     void g(int n)
738     {
739         // bad: the number of elements is not passed to f()
740         f(new int[n]);
741     }
743 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.
745 ##### Example, bad
747 We can of course pass the number of elements along with the pointer:
749     // separately compiled, possibly dynamically loaded
750     extern void f2(int* p, int n);
752     void g2(int n)
753     {
754         f2(new int[n], m);  // bad: a wrong number of elements can be passed to f()
755     }
757 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.
759 Also, it is implicit that `f2()` is supposed to `delete` its argument (or did the caller make a second mistake?).
761 ##### Example, bad
763 The standard library resource management pointers fail to pass the size when they point to an object:
765     // separately compiled, possibly dynamically loaded
766     // NB: this assumes the calling code is ABI-compatible, using a
767     // compatible C++ compiler and the same stdlib implementation
768     extern void f3(unique_ptr<int[]>, int n);
770     void g3(int n)
771     {
772         f3(make_unique<int[]>(n), m);    // bad: pass ownership and size separately
773     }
775 ##### Example
777 We need to pass the pointer and the number of elements as an integral object:
779     extern void f4(vector<int>&);   // separately compiled, possibly dynamically loaded
780     extern void f4(span<int>);      // separately compiled, possibly dynamically loaded
781                                     // NB: this assumes the calling code is ABI-compatible, using a
782                                     // compatible C++ compiler and the same stdlib implementation
784     void g3(int n)
785     {
786         vector<int> v(n);
787         f4(v);                     // pass a reference, retain ownership
788         f4(span<int>{v});          // pass a view, retain ownership
789     }
791 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.
793 ##### Example
795 How do we transfer both ownership and all information needed for validating use?
797     vector<int> f5(int n)    // OK: move
798     {
799         vector<int> v(n);
800         // ... initialize v ...
801         return v;
802     }
804     unique_ptr<int[]> f6(int n)    // bad: loses n
805     {
806         auto p = make_unique<int[]>(n);
807         // ... initialize *p ...
808         return p;
809     }
811     owner<int*> f7(int n)    // bad: loses n and we might forget to delete
812     {
813         owner<int*> p = new int[n];
814         // ... initialize *p ...
815         return p;
816     }
818 ##### Example
820 * ???
821 * show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
822   Or strings as "free-style" options
824 ##### Enforcement
826 * Flag (pointer, count)-style interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons)
827 * ???
829 ### <a name="Rp-early"></a>P.7: Catch run-time errors early
831 ##### Reason
833 Avoid "mysterious" crashes.
834 Avoid errors leading to (possibly unrecognized) wrong results.
836 ##### Example
838     void increment1(int* p, int n)    // bad: error-prone
839     {
840         for (int i = 0; i < n; ++i) ++p[i];
841     }
843     void use1(int m)
844     {
845         const int n = 10;
846         int a[n] = {};
847         // ...
848         increment1(a, m);   // maybe typo, maybe m <= n is supposed
849                             // but assume that m == 20
850         // ...
851     }
853 Here we made a small error in `use1` that will lead to corrupted data or a crash.
854 The (pointer, count)-style interface leaves `increment1()` with no realistic way of defending itself against out-of-range errors.
855 If we could check subscripts for out of range access, then the error would not be discovered until `p[10]` was accessed.
856 We could check earlier and improve the code:
858     void increment2(span<int> p)
859     {
860         for (int& x : p) ++x;
861     }
863     void use2(int m)
864     {
865         const int n = 10;
866         int a[n] = {};
867         // ...
868         increment2({a, m});    // maybe typo, maybe m <= n is supposed
869         // ...
870     }
872 Now, `m <= n` can be checked at the point of call (early) rather than later.
873 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):
875     void use3(int m)
876     {
877         const int n = 10;
878         int a[n] = {};
879         // ...
880         increment2(a);   // the number of elements of a need not be repeated
881         // ...
882     }
884 ##### Example, bad
886 Don't repeatedly check the same value. Don't pass structured data as strings:
888     Date read_date(istream& is);    // read date from istream
890     Date extract_date(const string& s);    // extract date from string
892     void user1(const string& date)    // manipulate date
893     {
894         auto d = extract_date(date);
895         // ...
896     }
898     void user2()
899     {
900         Date d = read_date(cin);
901         // ...
902         user1(d.to_string());
903         // ...
904     }
906 The date is validated twice (by the `Date` constructor) and passed as a character string (unstructured data).
908 ##### Example
910 Excess checking can be costly.
911 There are cases where checking early is dumb because you may not ever need the value, or may 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)`).
913     class Jet {    // Physics says: e * e < x * x + y * y + z * z
914         float x;
915         float y;
916         float z;
917         float e;
918     public:
919         Jet(float x, float y, float z, float e)
920             :x(x), y(y), z(z), e(e)
921         {
922             // Should I check here that the values are physically meaningful?
923         }
925         float m() const
926         {
927             // Should I handle the degenerate case here?
928             return sqrt(x * x + y * y + z * z - e * e);
929         }
931         ???
932     };
934 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.
938 ##### Enforcement
940 * Look at pointers and arrays: Do range-checking early and not repeatedly
941 * Look at conversions: Eliminate or mark narrowing conversions
942 * Look for unchecked values coming from input
943 * Look for structured data (objects of classes with invariants) being converted into strings
944 * ???
946 ### <a name="Rp-leak"></a>P.8: Don't leak any resources
948 ##### Reason
950 Even a slow growth in resources will, over time, exhaust the availability of those resources.
951 This is particularly important for long-running programs, but is an essential piece of responsible programming behavior.
953 ##### Example, bad
955     void f(char* name)
956     {
957         FILE* input = fopen(name, "r");
958         // ...
959         if (something) return;   // bad: if something == true, a file handle is leaked
960         // ...
961         fclose(input);
962     }
964 Prefer [RAII](#Rr-raii):
966     void f(char* name)
967     {
968         ifstream input {name};
969         // ...
970         if (something) return;   // OK: no leak
971         // ...
972     }
974 **See also**: [The resource management section](#S-resource)
976 ##### Note
978 A leak is colloquially "anything that isn't cleaned up."
979 The more important classification is "anything that can no longer be cleaned up."
980 For example, allocating an object on the heap and then losing the last pointer that points to that allocation.
981 This rule should not be taken as requiring that allocations within long-lived objects must be returned during program shutdown.
982 For example, relying on system guaranteed cleanup such as file closing and memory deallocation upon process shutdown can simplify code.
983 However, relying on abstractions that implicitly clean up can be as simple, and often safer.
985 ##### Note
987 Enforcing [the lifetime safety profile](#SS-lifetime) eliminates leaks.
988 When combined with resource safety provided by [RAII](#Rr-raii), it eliminates the need for "garbage collection" (by generating no garbage).
989 Combine this with enforcement of [the type and bounds profiles](#SS-force) and you get complete type- and resource-safety, guaranteed by tools.
991 ##### Enforcement
993 * Look at pointers: Classify them into non-owners (the default) and owners.
994   Where feasible, replace owners with standard-library resource handles (as in the example above).
995   Alternatively, mark an owner as such using `owner` from [the GSL](#S-gsl).
996 * Look for naked `new` and `delete`
997 * Look for known resource allocating functions returning raw pointers (such as `fopen`, `malloc`, and `strdup`)
999 ### <a name="Rp-waste"></a>P.9: Don't waste time or space
1001 ##### Reason
1003 This is C++.
1005 ##### Note
1007 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.
1008 "Another benefit of striving for efficiency is that the process forces you to understand the problem in more depth." - Alex Stepanov
1010 ##### Example, bad
1012     struct X {
1013         char ch;
1014         int i;
1015         string s;
1016         char ch2;
1018         X& operator=(const X& a);
1019         X(const X&);
1020     };
1022     X waste(const char* p)
1023     {
1024         if (!p) throw Nullptr_error{};
1025         int n = strlen(p);
1026         auto buf = new char[n];
1027         if (!buf) throw Allocation_error{};
1028         for (int i = 0; i < n; ++i) buf[i] = p[i];
1029         // ... manipulate buffer ...
1030         X x;
1031         x.ch = 'a';
1032         x.s = string(n);    // give x.s space for *p
1033         for (gsl::index i = 0; i < x.s.size(); ++i) x.s[i] = buf[i];  // copy buf into x.s
1034         delete[] buf;
1035         return x;
1036     }
1038     void driver()
1039     {
1040         X x = waste("Typical argument");
1041         // ...
1042     }
1044 Yes, this is a caricature, but we have seen every individual mistake in production code, and worse.
1045 Note that the layout of `X` guarantees that at least 6 bytes (and most likely more) are wasted.
1046 The spurious definition of copy operations disables move semantics so that the return operation is slow
1047 (please note that the Return Value Optimization, RVO, is not guaranteed here).
1048 The use of `new` and `delete` for `buf` is redundant; if we really needed a local string, we should use a local `string`.
1049 There are several more performance bugs and gratuitous complication.
1051 ##### Example, bad
1053     void lower(zstring s)
1054     {
1055         for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
1056     }
1058 This is actually an example from production code.
1059 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.
1061 ##### Note
1063 An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert.
1064 However, waste spread liberally across a code base can easily be significant and experts are not always as available as we would like.
1065 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.
1066 After that, we can look at waste related to algorithms and requirements, but that is beyond the scope of these guidelines.
1068 ##### Enforcement
1070 Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste.
1072 * 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.)
1075 ### <a name="Rp-mutable"></a>P.10: Prefer immutable data to mutable data
1077 ##### Reason
1079 It is easier to reason about constants than about variables.
1080 Something immutable cannot change unexpectedly.
1081 Sometimes immutability enables better optimization.
1082 You can't have a data race on a constant.
1084 See [Con: Constants and immutability](#S-const)
1086 ### <a name="Rp-library"></a>P.11: Encapsulate messy constructs, rather than spreading through the code
1088 ##### Reason
1090 Messy code is more likely to hide bugs and harder to write.
1091 A good interface is easier and safer to use.
1092 Messy, low-level code breeds more such code.
1094 ##### Example
1096     int sz = 100;
1097     int* p = (int*) malloc(sizeof(int) * sz);
1098     int count = 0;
1099     // ...
1100     for (;;) {
1101         // ... read an int into x, exit loop if end of file is reached ...
1102         // ... check that x is valid ...
1103         if (count == sz)
1104             p = (int*) realloc(p, sizeof(int) * sz * 2);
1105         p[count++] = x;
1106         // ...
1107     }
1109 This is low-level, verbose, and error-prone.
1110 For example, we "forgot" to test for memory exhaustion.
1111 Instead, we could use `vector`:
1113     vector<int> v;
1114     v.reserve(100);
1115     // ...
1116     for (int x; cin >> x; ) {
1117         // ... check that x is valid ...
1118         v.push_back(x);
1119     }
1121 ##### Note
1123 The standards library and the GSL are examples of this philosophy.
1124 For example, instead of messing with the arrays, unions, cast, tricky lifetime issues, `gsl::owner`, etc.,
1125 that are needed to implement key abstractions, such as `vector`, `span`, `lock_guard`, and `future`, we use the libraries
1126 designed and implemented by people with more time and expertise than we usually have.
1127 Similarly, we can and should design and implement more specialized libraries, rather than leaving the users (often ourselves)
1128 with the challenge of repeatedly getting low-level code well.
1129 This is a variant of the [subset of superset principle](#R0) that underlies these guidelines.
1131 ##### Enforcement
1133 * Look for "messy code" such as complex pointer manipulation and casting outside the implementation of abstractions.
1136 ### <a name="Rp-tools"></a>P.12: Use supporting tools as appropriate
1138 ##### Reason
1140 There are many things that are done better "by machine".
1141 Computers don't tire or get bored by repetitive tasks.
1142 We typically have better things to do than repeatedly do routine tasks.
1144 ##### Example
1146 Run a static analyzer to verify that your code follows the guidelines you want it to follow.
1148 ##### Note
1152 * [Static analysis tools](???)
1153 * [Concurrency tools](#Rconc-tools)
1154 * [Testing tools](???)
1156 There are many other kinds of tools, such as source code repositories, build tools, etc.,
1157 but those are beyond the scope of these guidelines.
1159 ##### Note
1161 Be careful not to become dependent on over-elaborate or over-specialized tool chains.
1162 Those can make your otherwise portable code non-portable.
1165 ### <a name="Rp-lib"></a>P.13: Use support libraries as appropriate
1167 ##### Reason
1169 Using a well-designed, well-documented, and well-supported library saves time and effort;
1170 its quality and documentation are likely to be greater than what you could do
1171 if the majority of your time must be spent on an implementation.
1172 The cost (time, effort, money, etc.) of a library can be shared over many users.
1173 A widely used library is more likely to be kept up-to-date and ported to new systems than an individual application.
1174 Knowledge of a widely-used library can save time on other/future projects.
1175 So, if a suitable library exists for your application domain, use it.
1177 ##### Example
1179     std::sort(begin(v), end(v), std::greater<>());
1181 Unless you are an expert in sorting algorithms and have plenty of time,
1182 this is more likely to be correct and to run faster than anything you write for a specific application.
1183 You need a reason not to use the standard library (or whatever foundational libraries your application uses) rather than a reason to use it.
1185 ##### Note
1187 By default use
1189 * The [ISO C++ Standard Library](#S-stdlib)
1190 * The [Guidelines Support Library](#S-gsl)
1192 ##### Note
1194 If no well-designed, well-documented, and well-supported library exists for an important domain,
1195 maybe you should design and implement it, and then use it.
1198 # <a name="S-interfaces"></a>I: Interfaces
1200 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.
1201 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.
1203 Interface rule summary:
1205 * [I.1: Make interfaces explicit](#Ri-explicit)
1206 * [I.2: Avoid non-`const` global variables](#Ri-global)
1207 * [I.3: Avoid singletons](#Ri-singleton)
1208 * [I.4: Make interfaces precisely and strongly typed](#Ri-typed)
1209 * [I.5: State preconditions (if any)](#Ri-pre)
1210 * [I.6: Prefer `Expects()` for expressing preconditions](#Ri-expects)
1211 * [I.7: State postconditions](#Ri-post)
1212 * [I.8: Prefer `Ensures()` for expressing postconditions](#Ri-ensures)
1213 * [I.9: If an interface is a template, document its parameters using concepts](#Ri-concepts)
1214 * [I.10: Use exceptions to signal a failure to perform a required task](#Ri-except)
1215 * [I.11: Never transfer ownership by a raw pointer (`T*`) or reference (`T&`)](#Ri-raw)
1216 * [I.12: Declare a pointer that must not be null as `not_null`](#Ri-nullptr)
1217 * [I.13: Do not pass an array as a single pointer](#Ri-array)
1218 * [I.22: Avoid complex initialization of global objects](#Ri-global-init)
1219 * [I.23: Keep the number of function arguments low](#Ri-nargs)
1220 * [I.24: Avoid adjacent unrelated parameters of the same type](#Ri-unrelated)
1221 * [I.25: Prefer abstract classes as interfaces to class hierarchies](#Ri-abstract)
1222 * [I.26: If you want a cross-compiler ABI, use a C-style subset](#Ri-abi)
1223 * [I.27: For stable library ABI, consider the Pimpl idiom](#Ri-pimpl)
1224 * [I.30: Encapsulate rule violations](#Ri-encapsulate)
1226 **See also**:
1228 * [F: Functions](#S-functions)
1229 * [C.concrete: Concrete types](#SS-concrete)
1230 * [C.hier: Class hierarchies](#SS-hier)
1231 * [C.over: Overloading and overloaded operators](#SS-overload)
1232 * [C.con: Containers and other resource handles](#SS-containers)
1233 * [E: Error handling](#S-errors)
1234 * [T: Templates and generic programming](#S-templates)
1236 ### <a name="Ri-explicit"></a>I.1: Make interfaces explicit
1238 ##### Reason
1240 Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.
1242 ##### Example, bad
1244 Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:
1246     int round(double d)
1247     {
1248         return (round_up) ? ceil(d) : d;    // don't: "invisible" dependency
1249     }
1251 It will not be obvious to a caller that the meaning of two calls of `round(7.2)` might give different results.
1253 ##### Exception
1255 Sometimes we control the details of a set of operations by an environment variable, e.g., normal vs. verbose output or debug vs. optimized.
1256 The use of a non-local control is potentially confusing, but controls only implementation details of otherwise fixed semantics.
1258 ##### Example, bad
1260 Reporting through non-local variables (e.g., `errno`) is easily ignored. For example:
1262     // don't: no test of printf's return value
1263     fprintf(connection, "logging: %d %d %d\n", x, y, s);
1265 What if the connection goes down so that no logging output is produced? See I.???.
1267 **Alternative**: Throw an exception. An exception cannot be ignored.
1269 **Alternative formulation**: Avoid passing information across an interface through non-local or implicit state.
1270 Note that non-`const` member functions pass information to other member functions through their object's state.
1272 **Alternative formulation**: An interface should be a function or a set of functions.
1273 Functions can be template functions and sets of functions can be classes or class templates.
1275 ##### Enforcement
1277 * (Simple) A function should not make control-flow decisions based on the values of variables declared at namespace scope.
1278 * (Simple) A function should not write to variables declared at namespace scope.
1280 ### <a name="Ri-global"></a>I.2: Avoid non-`const` global variables
1282 ##### Reason
1284 Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes.
1286 ##### Example
1288     struct Data {
1289         // ... lots of stuff ...
1290     } data;            // non-const data
1292     void compute()     // don't
1293     {
1294         // ... use data ...
1295     }
1297     void output()     // don't
1298     {
1299         // ... use data ...
1300     }
1302 Who else might modify `data`?
1304 ##### Note
1306 Global constants are useful.
1308 ##### Note
1310 The rule against global variables applies to namespace scope variables as well.
1312 **Alternative**: If you use global (more generally namespace scope) data to avoid copying, consider passing the data as an object by reference to `const`.
1313 Another solution is to define the data as the state of some object and the operations as member functions.
1315 **Warning**: Beware of data races: If one thread can access nonlocal data (or data passed by reference) while another thread executes the callee, we can have a data race.
1316 Every pointer or reference to mutable data is a potential data race.
1318 ##### Note
1320 You cannot have a race condition on immutable data.
1322 **References**: See the [rules for calling functions](#SS-call).
1324 ##### Note
1326 The rule is "avoid", not "don't use." Of course there will be (rare) exceptions, such as `cin`, `cout`, and `cerr`.
1328 ##### Enforcement
1330 (Simple) Report all non-`const` variables declared at namespace scope.
1332 ### <a name="Ri-singleton"></a>I.3: Avoid singletons
1334 ##### Reason
1336 Singletons are basically complicated global objects in disguise.
1338 ##### Example
1340     class Singleton {
1341         // ... lots of stuff to ensure that only one Singleton object is created,
1342         // that it is initialized properly, etc.
1343     };
1345 There are many variants of the singleton idea.
1346 That's part of the problem.
1348 ##### Note
1350 If you don't want a global object to change, declare it `const` or `constexpr`.
1352 ##### Exception
1354 You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any:
1356     X& myX()
1357     {
1358         static X my_x {3};
1359         return my_x;
1360     }
1362 This is one of the most effective solutions to problems related to initialization order.
1363 In a multi-threaded environment, the initialization of the static object does not introduce a race condition
1364 (unless you carelessly access a shared object from within its constructor).
1366 Note that the initialization of a local `static` does not imply a race condition.
1367 However, if the destruction of `X` involves an operation that needs to be synchronized we must use a less simple solution.
1368 For example:
1370     X& myX()
1371     {
1372         static auto p = new X {3};
1373         return *p;  // potential leak
1374     }
1376 Now someone must `delete` that object in some suitably thread-safe way.
1377 That's error-prone, so we don't use that technique unless
1379 * `myX` is in multi-threaded code,
1380 * that `X` object needs to be destroyed (e.g., because it releases a resource), and
1381 * `X`'s destructor's code needs to be synchronized.
1383 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.
1385 ##### Enforcement
1387 Very hard in general.
1389 * Look for classes with names that include `singleton`.
1390 * Look for classes for which only a single object is created (by counting objects or by examining constructors).
1391 * 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.
1393 ### <a name="Ri-typed"></a>I.4: Make interfaces precisely and strongly typed
1395 ##### Reason
1397 Types are the simplest and best documentation, improve legibility due to their well-defined meaning, and are checked at compile time.
1398 Also, precisely typed code is often optimized better.
1400 ##### Example, don't
1402 Consider:
1404     void pass(void* data);    // weak and under qualified type void* is suspicious
1406 Callers are unsure what types are allowed and if the data may
1407 be mutated as `const` is not specified. Note all pointer types
1408 implicitly convert to void*, so it is easy for callers to provide this value.
1410 The callee must `static_cast` data to an unverified type to use it.
1411 That is error-prone and verbose.
1413 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.
1415 **Alternative**: Often, a template parameter can eliminate the `void*` turning it into a `T*` or `T&`.
1416 For generic code these `T`s can be general or concept constrained template parameters.
1418 ##### Example, bad
1420 Consider:
1422     draw_rect(100, 200, 100, 500); // what do the numbers specify?
1424     draw_rect(p.x, p.y, 10, 20); // what units are 10 and 20 in?
1426 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?
1428 Comments and parameter names can help, but we could be explicit:
1430     void draw_rectangle(Point top_left, Point bottom_right);
1431     void draw_rectangle(Point top_left, Size height_width);
1433     draw_rectangle(p, Point{10, 20});  // two corners
1434     draw_rectangle(p, Size{10, 20});   // one corner and a (height, width) pair
1436 Obviously, we cannot catch all errors through the static type system
1437 (e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)).
1439 ##### Example, bad
1441 Consider:
1443     set_settings(true, false, 42); // what do the numbers specify?
1445 The parameter types and their values do not communicate what settings are being specified or what those values mean.
1447 This design is more explicit, safe and legible:
1449     alarm_settings s{};
1450     s.enabled = true;
1451     s.displayMode = alarm_settings::mode::spinning_light;
1452     s.frequency = alarm_settings::every_10_seconds;
1453     set_settings(s);
1455 For the case of a set of boolean values consider using a flags enum; a pattern that expresses a set of boolean values.
1457     enable_lamp_options(lamp_option::on | lamp_option::animate_state_transitions);
1459 ##### Example, bad
1461 In the following example, it is not clear from the interface what `time_to_blink` means: Seconds? Milliseconds?
1463     void blink_led(int time_to_blink) // bad -- the unit is ambiguous
1464     {
1465         // ...
1466         // do something with time_to_blink
1467         // ...
1468     }
1470     void use()
1471     {
1472         blink_led(2);
1473     }
1475 ##### Example, good
1477 `std::chrono::duration` types (C++11) helps making the unit of time duration explicit.
1479     void blink_led(milliseconds time_to_blink) // good -- the unit is explicit
1480     {
1481         // ...
1482         // do something with time_to_blink
1483         // ...
1484     }
1486     void use()
1487     {
1488         blink_led(1500ms);
1489     }
1491 The function can also be written in such a way that it will accept any time duration unit.
1493     template<class rep, class period>
1494     void blink_led(duration<rep, period> time_to_blink) // good -- accepts any unit
1495     {
1496         // assuming that millisecond is the smallest relevant unit
1497         auto milliseconds_to_blink = duration_cast<milliseconds>(time_to_blink);
1498         // ...
1499         // do something with milliseconds_to_blink
1500         // ...
1501     }
1503     void use()
1504     {
1505         blink_led(2s);
1506         blink_led(1500ms);
1507     }
1509 ##### Enforcement
1511 * (Simple) Report the use of `void*` as a parameter or return type.
1512 * (Simple) Report the use of more than one `bool` parameter.
1513 * (Hard to do well) Look for functions that use too many primitive type arguments.
1515 ### <a name="Ri-pre"></a>I.5: State preconditions (if any)
1517 ##### Reason
1519 Arguments have meaning that may constrain their proper use in the callee.
1521 ##### Example
1523 Consider:
1525     double sqrt(double x);
1527 Here `x` must be nonnegative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
1529     double sqrt(double x); // x must be nonnegative
1531 Some preconditions can be expressed as assertions. For example:
1533     double sqrt(double x) { Expects(x >= 0); /* ... */ }
1535 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).
1537 **References**: `Expects()` is described in [GSL](#S-gsl).
1539 ##### Note
1541 Prefer a formal specification of requirements, such as `Expects(p);`.
1542 If that is infeasible, use English text in comments, such as `// the sequence [p:q) is ordered using <`.
1544 ##### Note
1546 Most member functions have as a precondition that some class invariant holds.
1547 That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class.
1548 We don't need to mention it for each member function.
1550 ##### Enforcement
1552 (Not enforceable)
1554 **See also**: The rules for passing pointers. ???
1556 ### <a name="Ri-expects"></a>I.6: Prefer `Expects()` for expressing preconditions
1558 ##### Reason
1560 To make it clear that the condition is a precondition and to enable tool use.
1562 ##### Example
1564     int area(int height, int width)
1565     {
1566         Expects(height > 0 && width > 0);            // good
1567         if (height <= 0 || width <= 0) my_error();   // obscure
1568         // ...
1569     }
1571 ##### Note
1573 Preconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
1574 This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics (do you always want to abort in debug mode and check nothing in productions runs?).
1576 ##### Note
1578 Preconditions should be part of the interface rather than part of the implementation,
1579 but we don't yet have the language facilities to do that.
1580 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.
1582 ##### Note
1584 `Expects()` can also be used to check a condition in the middle of an algorithm.
1586 ##### Note
1588 No, using `unsigned` is not a good way to sidestep the problem of [ensuring that a value is nonnegative](#Res-nonnegative).
1590 ##### Enforcement
1592 (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.
1594 ### <a name="Ri-post"></a>I.7: State postconditions
1596 ##### Reason
1598 To detect misunderstandings about the result and possibly catch erroneous implementations.
1600 ##### Example, bad
1602 Consider:
1604     int area(int height, int width) { return height * width; }  // bad
1606 Here, we (incautiously) left out the precondition specification, so it is not explicit that height and width must be positive.
1607 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.
1608 Overflow can happen.
1609 Consider using:
1611     int area(int height, int width)
1612     {
1613         auto res = height * width;
1614         Ensures(res > 0);
1615         return res;
1616     }
1618 ##### Example, bad
1620 Consider a famous security bug:
1622     void f()    // problematic
1623     {
1624         char buffer[MAX];
1625         // ...
1626         memset(buffer, 0, sizeof(buffer));
1627     }
1629 There was no postcondition stating that the buffer should be cleared and the optimizer eliminated the apparently redundant `memset()` call:
1631     void f()    // better
1632     {
1633         char buffer[MAX];
1634         // ...
1635         memset(buffer, 0, sizeof(buffer));
1636         Ensures(buffer[0] == 0);
1637     }
1639 ##### Note
1641 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.
1643 ##### Note
1645 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.
1647 ##### Example
1649 Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions:
1651     mutex m;
1653     void manipulate(Record& r)    // don't
1654     {
1655         m.lock();
1656         // ... no m.unlock() ...
1657     }
1659 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.
1660 Stating the postcondition would have made it clear:
1662     void manipulate(Record& r)    // postcondition: m is unlocked upon exit
1663     {
1664         m.lock();
1665         // ... no m.unlock() ...
1666     }
1668 The bug is now obvious (but only to a human reading comments).
1670 Better still, use [RAII](#Rr-raii) to ensure that the postcondition ("the lock must be released") is enforced in code:
1672     void manipulate(Record& r)    // best
1673     {
1674         lock_guard<mutex> _ {m};
1675         // ...
1676     }
1678 ##### Note
1680 Ideally, postconditions are stated in the interface/declaration so that users can easily see them.
1681 Only postconditions related to the users can be stated in the interface.
1682 Postconditions related only to internal state belongs in the definition/implementation.
1684 ##### Enforcement
1686 (Not enforceable) This is a philosophical guideline that is infeasible to check
1687 directly in the general case. Domain specific checkers (like lock-holding
1688 checkers) exist for many toolchains.
1690 ### <a name="Ri-ensures"></a>I.8: Prefer `Ensures()` for expressing postconditions
1692 ##### Reason
1694 To make it clear that the condition is a postcondition and to enable tool use.
1696 ##### Example
1698     void f()
1699     {
1700         char buffer[MAX];
1701         // ...
1702         memset(buffer, 0, MAX);
1703         Ensures(buffer[0] == 0);
1704     }
1706 ##### Note
1708 Postconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
1709 This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics.
1711 **Alternative**: Postconditions of the form "this resource must be released" are best expressed by [RAII](#Rr-raii).
1713 ##### Note
1715 Ideally, that `Ensures` should be part of the interface, but that's not easily done.
1716 For now, we place it in the definition (function body).
1717 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.
1719 ##### Enforcement
1721 (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.
1723 ### <a name="Ri-concepts"></a>I.9: If an interface is a template, document its parameters using concepts
1725 ##### Reason
1727 Make the interface precisely specified and compile-time checkable in the (not so distant) future.
1729 ##### Example
1731 Use the ISO Concepts TS style of requirements specification. For example:
1733     template<typename Iter, typename Val>
1734     // requires InputIterator<Iter> && EqualityComparable<ValueType<Iter>>, Val>
1735     Iter find(Iter first, Iter last, Val v)
1736     {
1737         // ...
1738     }
1740 ##### Note
1742 Soon (maybe in 2018), most compilers will be able to check `requires` clauses once the `//` is removed.
1743 Concepts are supported in GCC 6.1 and later.
1745 **See also**: [Generic programming](#SS-GP) and [concepts](#SS-concepts).
1747 ##### Enforcement
1749 (Not yet enforceable) A language facility is under specification. When the language facility is available, warn if any non-variadic template parameter is not constrained by a concept (in its declaration or mentioned in a `requires` clause).
1751 ### <a name="Ri-except"></a>I.10: Use exceptions to signal a failure to perform a required task
1753 ##### Reason
1755 It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state.
1756 This is a major source of errors.
1758 ##### Example
1760     int printf(const char* ...);    // bad: return negative number if output fails
1762     template <class F, class ...Args>
1763     // good: throw system_error if unable to start the new thread
1764     explicit thread(F&& f, Args&&... args);
1766 ##### Note
1768 What is an error?
1770 An error means that the function cannot achieve its advertised purpose (including establishing postconditions).
1771 Calling code that ignores an error could lead to wrong results or undefined systems state.
1772 For example, not being able to connect to a remote server is not by itself an error:
1773 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.
1774 However, if failing to make a connection is considered an error, then a failure should throw an exception.
1776 ##### Exception
1778 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.
1780 ##### Alternative
1782 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:
1784     int val;
1785     int error_code;
1786     tie(val, error_code) = do_something();
1787     if (error_code) {
1788         // ... handle the error or exit ...
1789     }
1790     // ... use val ...
1792 This style unfortunately leads to uninitialized variables.
1793 Since C++17 the "structured bindings" feature can be used to initialize variables directly from the return value:
1795     auto [val, error_code] = do_something();
1796     if (error_code) {
1797         // ... handle the error or exit ...
1798     }
1799     // ... use val ...
1801 ##### Note
1803 We don't consider "performance" a valid reason not to use exceptions.
1805 * Often, explicit error checking and handling consume as much time and space as exception handling.
1806 * Often, cleaner code yields better performance with exceptions (simplifying the tracing of paths through the program and their optimization).
1807 * A good rule for performance critical code is to move checking outside the critical part of the code ([checking](#Rper-checking)).
1808 * In the longer term, more regular code gets better optimized.
1809 * Always carefully [measure](#Rper-measure) before making performance claims.
1811 **See also**: [I.5](#Ri-pre) and [I.7](#Ri-post) for reporting precondition and postcondition violations.
1813 ##### Enforcement
1815 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
1816 * Look for `errno`.
1818 ### <a name="Ri-raw"></a>I.11: Never transfer ownership by a raw pointer (`T*`) or reference (`T&`)
1820 ##### Reason
1822 If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.
1824 ##### Example
1826 Consider:
1828     X* compute(args)    // don't
1829     {
1830         X* res = new X{};
1831         // ...
1832         return res;
1833     }
1835 Who deletes the returned `X`? The problem would be harder to spot if `compute` returned a reference.
1836 Consider returning the result by value (use move semantics if the result is large):
1838     vector<double> compute(args)  // good
1839     {
1840         vector<double> res(10000);
1841         // ...
1842         return res;
1843     }
1845 **Alternative**: [Pass ownership](#Rr-smartptrparam) using a "smart pointer", such as `unique_ptr` (for exclusive ownership) and `shared_ptr` (for shared ownership).
1846 However, that is less elegant and often less efficient than returning the object itself,
1847 so use smart pointers only if reference semantics are needed.
1849 **Alternative**: Sometimes older code can't be modified because of ABI compatibility requirements or lack of resources.
1850 In that case, mark owning pointers using `owner` from the [guidelines support library](#S-gsl):
1852     owner<X*> compute(args)    // It is now clear that ownership is transferred
1853     {
1854         owner<X*> res = new X{};
1855         // ...
1856         return res;
1857     }
1859 This tells analysis tools that `res` is an owner.
1860 That is, its value must be `delete`d or transferred to another owner, as is done here by the `return`.
1862 `owner` is used similarly in the implementation of resource handles.
1864 ##### Note
1866 Every object passed as a raw pointer (or iterator) is assumed to be owned by the
1867 caller, so that its lifetime is handled by the caller. Viewed another way:
1868 ownership transferring APIs are relatively rare compared to pointer-passing APIs,
1869 so the default is "no ownership transfer."
1871 **See also**: [Argument passing](#Rf-conventional), [use of smart pointer arguments](#Rr-smartptrparam), and [value return](#Rf-value-return).
1873 ##### Enforcement
1875 * (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>`.
1876 * (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path.
1877 * (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.
1879 ### <a name="Ri-nullptr"></a>I.12: Declare a pointer that must not be null as `not_null`
1881 ##### Reason
1883 To help avoid dereferencing `nullptr` errors.
1884 To improve performance by avoiding redundant checks for `nullptr`.
1886 ##### Example
1888     int length(const char* p);            // it is not clear whether length(nullptr) is valid
1890     length(nullptr);                      // OK?
1892     int length(not_null<const char*> p);  // better: we can assume that p cannot be nullptr
1894     int length(const char* p);            // we must assume that p can be nullptr
1896 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.
1898 ##### Note
1900 `not_null` is defined in the [guidelines support library](#S-gsl).
1902 ##### Note
1904 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*`.
1906     // we can assume that p cannot be nullptr
1907     // we can assume that p points to a zero-terminated array of characters
1908     int length(not_null<zstring> p);
1910 Note: `length()` is, of course, `std::strlen()` in disguise.
1912 ##### Enforcement
1914 * (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`.
1915 * (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`.
1917 ### <a name="Ri-array"></a>I.13: Do not pass an array as a single pointer
1919 ##### Reason
1921  (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.
1923 ##### Example
1925 Consider:
1927     void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
1929 What if there are fewer than `n` elements in the array pointed to by `q`? Then, we overwrite some probably unrelated memory.
1930 What if there are fewer than `n` elements in the array pointed to by `p`? Then, we read some probably unrelated memory.
1931 Either is undefined behavior and a potentially very nasty bug.
1933 ##### Alternative
1935 Consider using explicit spans:
1937     void copy(span<const T> r, span<T> r2); // copy r to r2
1939 ##### Example, bad
1941 Consider:
1943     void draw(Shape* p, int n);  // poor interface; poor code
1944     Circle arr[10];
1945     // ...
1946     draw(arr, 10);
1948 Passing `10` as the `n` argument may 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.
1950 **Alternative**: Use a support class that ensures that the number of elements is correct and prevents dangerous implicit conversions. For example:
1952     void draw2(span<Circle>);
1953     Circle arr[10];
1954     // ...
1955     draw2(span<Circle>(arr));  // deduce the number of elements
1956     draw2(arr);    // deduce the element type and array size
1958     void draw3(span<Shape>);
1959     draw3(arr);    // error: cannot convert Circle[10] to span<Shape>
1961 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 ???.
1963 ##### Exception
1965 Use `zstring` and `czstring` to represent C-style, zero-terminated strings.
1966 But when doing so, use `std::string_view` or `string_span` from the [GSL](#GSL) to prevent range errors.
1968 ##### Enforcement
1970 * (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.
1971 * (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.
1973 ### <a name="Ri-global-init"></a>I.22: Avoid complex initialization of global objects
1975 ##### Reason
1977 Complex initialization can lead to undefined order of execution.
1979 ##### Example
1981     // file1.c
1983     extern const X x;
1985     const Y y = f(x);   // read x; write y
1987     // file2.c
1989     extern const Y y;
1991     const X x = g(y);   // read y; write x
1993 Since `x` and `y` are in different translation units the order of calls to `f()` and `g()` is undefined;
1994 one will access an uninitialized `const`.
1995 This shows that the order-of-initialization problem for global (namespace scope) objects is not limited to global *variables*.
1997 ##### Note
1999 Order of initialization problems become particularly difficult to handle in concurrent code.
2000 It is usually best to avoid global (namespace scope) objects altogether.
2002 ##### Enforcement
2004 * Flag initializers of globals that call non-`constexpr` functions
2005 * Flag initializers of globals that access `extern` objects
2007 ### <a name="Ri-nargs"></a>I.23: Keep the number of function arguments low
2009 ##### Reason
2011 Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.
2013 ##### Discussion
2015 The two most common reasons why functions have too many parameters are:
2017 1. *Missing an abstraction.*
2018    There is an abstraction missing, so that a compound value is being
2019    passed as individual elements instead of as a single object that enforces an invariant.
2020    This not only expands the parameter list, but it leads to errors because the component values
2021    are no longer protected by an enforced invariant.
2023 2. *Violating "one function, one responsibility."*
2024    The function is trying to do more than one job and should probably be refactored.
2026 ##### Example
2028 The standard-library `merge()` is at the limit of what we can comfortably handle:
2030     template<class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
2031     OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
2032                          InputIterator2 first2, InputIterator2 last2,
2033                          OutputIterator result, Compare comp);
2035 Note that this is because of problem 1 above -- missing abstraction. Instead of passing a range (abstraction), STL passed iterator pairs (unencapsulated component values).
2037 Here, we have four template arguments and six function arguments.
2038 To simplify the most frequent and simplest uses, the comparison argument can be defaulted to `<`:
2040     template<class InputIterator1, class InputIterator2, class OutputIterator>
2041     OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
2042                          InputIterator2 first2, InputIterator2 last2,
2043                          OutputIterator result);
2045 This doesn't reduce the total complexity, but it reduces the surface complexity presented to many users.
2046 To really reduce the number of arguments, we need to bundle the arguments into higher-level abstractions:
2048     template<class InputRange1, class InputRange2, class OutputIterator>
2049     OutputIterator merge(InputRange1 r1, InputRange2 r2, OutputIterator result);
2051 Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking.
2053 Alternatively, we could use concepts (as defined by the ISO TS) to define the notion of three types that must be usable for merging:
2055     Mergeable{In1, In2, Out}
2056     OutputIterator merge(In1 r1, In2 r2, Out result);
2058 ##### Example
2060 The safety Profiles recommend replacing
2062     void f(int* some_ints, int some_ints_length);  // BAD: C style, unsafe
2064 with
2066     void f(gsl::span<int> some_ints);              // GOOD: safe, bounds-checked
2068 Here, using an abstraction has safety and robustness benefits, and naturally also reduces the number of parameters.
2070 ##### Note
2072 How many parameters are too many? Try to use fewer than four (4) parameters.
2073 There are functions that are best expressed with four individual parameters, but not many.
2075 **Alternative**: Use better abstraction: Group arguments into meaningful objects and pass the objects (by value or by reference).
2077 **Alternative**: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments.
2079 ##### Enforcement
2081 * Warn when a function declares two iterators (including pointers) of the same type instead of a range or a view.
2082 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
2084 ### <a name="Ri-unrelated"></a>I.24: Avoid adjacent unrelated parameters of the same type
2086 ##### Reason
2088 Adjacent arguments of the same type are easily swapped by mistake.
2090 ##### Example, bad
2092 Consider:
2094     void copy_n(T* p, T* q, int n);  // copy from [p:p + n) to [q:q + n)
2096 This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.
2098 Use `const` for the "from" argument:
2100     void copy_n(const T* p, T* q, int n);  // copy from [p:p + n) to [q:q + n)
2102 ##### Exception
2104 If the order of the parameters is not important, there is no problem:
2106     int max(int a, int b);
2108 ##### Alternative
2110 Don't pass arrays as pointers, pass an object representing a range (e.g., a `span`):
2112     void copy_n(span<const T> p, span<T> q);  // copy from p to q
2114 ##### Alternative
2116 Define a `struct` as the parameter type and name the fields for those parameters accordingly:
2118     struct SystemParams {
2119         string config_file;
2120         string output_path;
2121         seconds timeout;
2122     };
2123     void initialize(SystemParams p);
2125 This tends to make invocations of this clear to future readers, as the parameters
2126 are often filled in by name at the call site.
2128 ##### Enforcement
2130 (Simple) Warn if two consecutive parameters share the same type.
2132 ### <a name="Ri-abstract"></a>I.25: Prefer abstract classes as interfaces to class hierarchies
2134 ##### Reason
2136 Abstract classes are more likely to be stable than base classes with state.
2138 ##### Example, bad
2140 You just knew that `Shape` would turn up somewhere :-)
2142     class Shape {  // bad: interface class loaded with data
2143     public:
2144         Point center() const { return c; }
2145         virtual void draw() const;
2146         virtual void rotate(int);
2147         // ...
2148     private:
2149         Point c;
2150         vector<Point> outline;
2151         Color col;
2152     };
2154 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. Abstract classes were invented to discourage users from writing such classes:
2156     class Shape {    // better: Shape is a pure interface
2157     public:
2158         virtual Point center() const = 0;   // pure virtual functions
2159         virtual void draw() const = 0;
2160         virtual void rotate(int) = 0;
2161         // ...
2162         // ... no data members ...
2163         // ...
2164         virtual ~Shape() = default;
2165     };
2167 ##### Enforcement
2169 (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.
2171 ### <a name="Ri-abi"></a>I.26: If you want a cross-compiler ABI, use a C-style subset
2173 ##### Reason
2175 Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.
2177 ##### Exception
2179 Common ABIs are emerging on some platforms freeing you from the more draconian restrictions.
2181 ##### Note
2183 If you use a single compiler, you can use full C++ in interfaces. That may require recompilation after an upgrade to a new compiler version.
2185 ##### Enforcement
2187 (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
2189 ### <a name="Ri-pimpl"></a>I.27: For stable library ABI, consider the Pimpl idiom
2191 ##### Reason
2193 Because private data members participate in class layout and private member functions participate in overload resolution, changes to those
2194 implementation details require recompilation of all users of a class that uses them. A non-polymorphic interface class holding a pointer to
2195 implementation (Pimpl) can isolate the users of a class from changes in its implementation at the cost of an indirection.
2197 ##### Example
2199 interface (widget.h)
2201     class widget {
2202         class impl;
2203         std::unique_ptr<impl> pimpl;
2204     public:
2205         void draw(); // public API that will be forwarded to the implementation
2206         widget(int); // defined in the implementation file
2207         ~widget();   // defined in the implementation file, where impl is a complete type
2208         widget(widget&&) = default;
2209         widget(const widget&) = delete;
2210         widget& operator=(widget&&); // defined in the implementation file
2211         widget& operator=(const widget&) = delete;
2212     };
2215 implementation (widget.cpp)
2217     class widget::impl {
2218         int n; // private data
2219     public:
2220         void draw(const widget& w) { /* ... */ }
2221         impl(int n) : n(n) {}
2222     };
2223     void widget::draw() { pimpl->draw(*this); }
2224     widget::widget(int n) : pimpl{std::make_unique<impl>(n)} {}
2225     widget::~widget() = default;
2226     widget& widget::operator=(widget&&) = default;
2228 ##### Notes
2230 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.
2232 ##### Enforcement
2234 (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
2236 ### <a name="Ri-encapsulate"></a>I.30: Encapsulate rule violations
2238 ##### Reason
2240 To keep code simple and safe.
2241 Sometimes, ugly, unsafe, or error-prone techniques are necessary for logical or performance reasons.
2242 If so, keep them local, rather than "infecting" interfaces so that larger groups of programmers have to be aware of the
2243 subtleties.
2244 Implementation complexity should, if at all possible, not leak through interfaces into user code.
2246 ##### Example
2248 Consider a program that, depending on some form of input (e.g., arguments to `main`), should consume input
2249 from a file, from the command line, or from standard input.
2250 We might write
2252     bool owned;
2253     owner<istream*> inp;
2254     switch (source) {
2255     case std_in:        owned = false; inp = &cin;                       break;
2256     case command_line:  owned = true;  inp = new istringstream{argv[2]}; break;
2257     case file:          owned = true;  inp = new ifstream{argv[2]};      break;
2258     }
2259     istream& in = *inp;
2261 This violated the rule [against uninitialized variables](#Res-always),
2262 the rule against [ignoring ownership](#Ri-raw),
2263 and the rule [against magic constants](#Res-magic).
2264 In particular, someone has to remember to somewhere write
2266     if (owned) delete inp;
2268 We could handle this particular example by using `unique_ptr` with a special deleter that does nothing for `cin`,
2269 but that's complicated for novices (who can easily encounter this problem) and the example is an example of a more general
2270 problem where a property that we would like to consider static (here, ownership) needs infrequently be addressed
2271 at run time.
2272 The common, most frequent, and safest examples can be handled statically, so we don't want to add cost and complexity to those.
2273 But we must also cope with the uncommon, less-safe, and necessarily more expensive cases.
2274 Such examples are discussed in [[Str15]](http://www.stroustrup.com/resource-model.pdf).
2276 So, we write a class
2278     class Istream { [[gsl::suppress(lifetime)]]
2279     public:
2280         enum Opt { from_line = 1 };
2281         Istream() { }
2282         Istream(zstring p) :owned{true}, inp{new ifstream{p}} {}            // read from file
2283         Istream(zstring p, Opt) :owned{true}, inp{new istringstream{p}} {}  // read from command line
2284         ~Istream() { if (owned) delete inp; }
2285         operator istream& () { return *inp; }
2286     private:
2287         bool owned = false;
2288         istream* inp = &cin;
2289     };
2291 Now, the dynamic nature of `istream` ownership has been encapsulated.
2292 Presumably, a bit of checking for potential errors would be added in real code.
2294 ##### Enforcement
2296 * Hard, it is hard to decide what rule-breaking code is essential
2297 * Flag rule suppression that enable rule-violations to cross interfaces
2299 # <a name="S-functions"></a>F: Functions
2301 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.
2303 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.
2304 Functions are the most critical part in most interfaces, so see the interface rules.
2306 Function rule summary:
2308 Function definition rules:
2310 * [F.1: "Package" meaningful operations as carefully named functions](#Rf-package)
2311 * [F.2: A function should perform a single logical operation](#Rf-logical)
2312 * [F.3: Keep functions short and simple](#Rf-single)
2313 * [F.4: If a function may have to be evaluated at compile time, declare it `constexpr`](#Rf-constexpr)
2314 * [F.5: If a function is very small and time-critical, declare it inline](#Rf-inline)
2315 * [F.6: If your function may not throw, declare it `noexcept`](#Rf-noexcept)
2316 * [F.7: For general use, take `T*` or `T&` arguments rather than smart pointers](#Rf-smart)
2317 * [F.8: Prefer pure functions](#Rf-pure)
2318 * [F.9: Unused parameters should be unnamed](#Rf-unused)
2320 Parameter passing expression rules:
2322 * [F.15: Prefer simple and conventional ways of passing information](#Rf-conventional)
2323 * [F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`](#Rf-in)
2324 * [F.17: For "in-out" parameters, pass by reference to non-`const`](#Rf-inout)
2325 * [F.18: For "will-move-from" parameters, pass by `X&&` and `std::move` the parameter](#Rf-consume)
2326 * [F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter](#Rf-forward)
2327 * [F.20: For "out" output values, prefer return values to output parameters](#Rf-out)
2328 * [F.21: To return multiple "out" values, prefer returning a struct or tuple](#Rf-out-multi)
2329 * [F.60: Prefer `T*` over `T&` when "no argument" is a valid option](#Rf-ptr-ref)
2331 Parameter passing semantic rules:
2333 * [F.22: Use `T*` or `owner<T*>` to designate a single object](#Rf-ptr)
2334 * [F.23: Use a `not_null<T>` to indicate that "null" is not a valid value](#Rf-nullptr)
2335 * [F.24: Use a `span<T>` or a `span_p<T>` to designate a half-open sequence](#Rf-range)
2336 * [F.25: Use a `zstring` or a `not_null<zstring>` to designate a C-style string](#Rf-zstring)
2337 * [F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed](#Rf-unique_ptr)
2338 * [F.27: Use a `shared_ptr<T>` to share ownership](#Rf-shared_ptr)
2340 <a name="Rf-value-return"></a>Value return semantic rules:
2342 * [F.42: Return a `T*` to indicate a position (only)](#Rf-return-ptr)
2343 * [F.43: Never (directly or indirectly) return a pointer or a reference to a local object](#Rf-dangle)
2344 * [F.44: Return a `T&` when copy is undesirable and "returning no object" isn't needed](#Rf-return-ref)
2345 * [F.45: Don't return a `T&&`](#Rf-return-ref-ref)
2346 * [F.46: `int` is the return type for `main()`](#Rf-main)
2347 * [F.47: Return `T&` from assignment operators](#Rf-assignment-op)
2348 * [F.48: Don't `return std::move(local)`](#Rf-return-move-local)
2350 Other function rules:
2352 * [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)
2353 * [F.51: Where there is a choice, prefer default arguments over overloading](#Rf-default-args)
2354 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
2355 * [F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread](#Rf-value-capture)
2356 * [F.54: If you capture `this`, capture all variables explicitly (no default capture)](#Rf-this-capture)
2357 * [F.55: Don't use `va_arg` arguments](#F-varargs)
2359 Functions have strong similarities to lambdas and function objects.
2361 **See also**: [C.lambdas: Function objects and lambdas](#SS-lambdas)
2363 ## <a name="SS-fct-def"></a>F.def: Function definitions
2365 A function definition is a function declaration that also specifies the function's implementation, the function body.
2367 ### <a name="Rf-package"></a>F.1: "Package" meaningful operations as carefully named functions
2369 ##### Reason
2371 Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code.
2372 If something is a well-specified action, separate it out from its surrounding code and give it a name.
2374 ##### Example, don't
2376     void read_and_print(istream& is)    // read and print an int
2377     {
2378         int x;
2379         if (is >> x)
2380             cout << "the int is " << x << '\n';
2381         else
2382             cerr << "no int on input\n";
2383     }
2385 Almost everything is wrong with `read_and_print`.
2386 It reads, it writes (to a fixed `ostream`), it writes error messages (to a fixed `ostream`), it handles only `int`s.
2387 There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use.
2388 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
2389 mess could become hard to understand.
2391 ##### Note
2393 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.
2395 ##### Example
2397     sort(a, b, [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); });
2399 Naming that lambda breaks up the expression into its logical parts and provides a strong hint to the meaning of the lambda.
2401     auto lessT = [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); };
2403     sort(a, b, lessT);
2404     find_if(a, b, lessT);
2406 The shortest code is not always the best for performance or maintainability.
2408 ##### Exception
2410 Loop bodies, including lambdas used as loop bodies, rarely need to be named.
2411 However, large loop bodies (e.g., dozens of lines or dozens of pages) can be a problem.
2412 The rule [Keep functions short and simple](#Rf-single) implies "Keep loop bodies short."
2413 Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unlikely to be reusable.
2415 ##### Enforcement
2417 * See [Keep functions short and simple](#Rf-single)
2418 * Flag identical and very similar lambdas used in different places.
2420 ### <a name="Rf-logical"></a>F.2: A function should perform a single logical operation
2422 ##### Reason
2424 A function that performs a single operation is simpler to understand, test, and reuse.
2426 ##### Example
2428 Consider:
2430     void read_and_print()    // bad
2431     {
2432         int x;
2433         cin >> x;
2434         // check for errors
2435         cout << x << "\n";
2436     }
2438 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:
2440     int read(istream& is)    // better
2441     {
2442         int x;
2443         is >> x;
2444         // check for errors
2445         return x;
2446     }
2448     void print(ostream& os, int x)
2449     {
2450         os << x << "\n";
2451     }
2453 These can now be combined where needed:
2455     void read_and_print()
2456     {
2457         auto x = read(cin);
2458         print(cout, x);
2459     }
2461 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:
2463     auto read = [](auto& input, auto& value)    // better
2464     {
2465         input >> value;
2466         // check for errors
2467     };
2469     auto print(auto& output, const auto& value)
2470     {
2471         output << value << "\n";
2472     }
2474 ##### Enforcement
2476 * Consider functions with more than one "out" parameter suspicious. Use return values instead, including `tuple` for multiple return values.
2477 * Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
2478 * Consider functions with 7 or more parameters suspicious.
2480 ### <a name="Rf-single"></a>F.3: Keep functions short and simple
2482 ##### Reason
2484 Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes.
2485 Functions with complex control structures are more likely to be long and more likely to hide logical errors
2487 ##### Example
2489 Consider:
2491     double simple_func(double val, int flag1, int flag2)
2492         // simple_func: takes a value and calculates the expected ASIC output,
2493         // given the two mode flags.
2494     {
2495         double intermediate;
2496         if (flag1 > 0) {
2497             intermediate = func1(val);
2498             if (flag2 % 2)
2499                  intermediate = sqrt(intermediate);
2500         }
2501         else if (flag1 == -1) {
2502             intermediate = func1(-val);
2503             if (flag2 % 2)
2504                  intermediate = sqrt(-intermediate);
2505             flag1 = -flag1;
2506         }
2507         if (abs(flag2) > 10) {
2508             intermediate = func2(intermediate);
2509         }
2510         switch (flag2 / 10) {
2511         case 1: if (flag1 == -1) return finalize(intermediate, 1.171);
2512                 break;
2513         case 2: return finalize(intermediate, 13.1);
2514         default: break;
2515         }
2516         return finalize(intermediate, 0.);
2517     }
2519 This is too complex.
2520 How would you know if all possible alternatives have been correctly handled?
2521 Yes, it breaks other rules also.
2523 We can refactor:
2525     double func1_muon(double val, int flag)
2526     {
2527         // ???
2528     }
2530     double func1_tau(double val, int flag1, int flag2)
2531     {
2532         // ???
2533     }
2535     double simple_func(double val, int flag1, int flag2)
2536         // simple_func: takes a value and calculates the expected ASIC output,
2537         // given the two mode flags.
2538     {
2539         if (flag1 > 0)
2540             return func1_muon(val, flag2);
2541         if (flag1 == -1)
2542             // handled by func1_tau: flag1 = -flag1;
2543             return func1_tau(-val, flag1, flag2);
2544         return 0.;
2545     }
2547 ##### Note
2549 "It doesn't fit on a screen" is often a good practical definition of "far too large."
2550 One-to-five-line functions should be considered normal.
2552 ##### Note
2554 Break large functions up into smaller cohesive and named functions.
2555 Small simple functions are easily inlined where the cost of a function call is significant.
2557 ##### Enforcement
2559 * Flag functions that do not "fit on a screen."
2560   How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
2561 * Flag functions that are too complex. How complex is too complex?
2562   You could use cyclomatic complexity. Try "more than 10 logical path through." Count a simple switch as one path.
2564 ### <a name="Rf-constexpr"></a>F.4: If a function may have to be evaluated at compile time, declare it `constexpr`
2566 ##### Reason
2568  `constexpr` is needed to tell the compiler to allow compile-time evaluation.
2570 ##### Example
2572 The (in)famous factorial:
2574     constexpr int fac(int n)
2575     {
2576         constexpr int max_exp = 17;      // constexpr enables max_exp to be used in Expects
2577         Expects(0 <= n && n < max_exp);  // prevent silliness and overflow
2578         int x = 1;
2579         for (int i = 2; i <= n; ++i) x *= i;
2580         return x;
2581     }
2583 This is C++14.
2584 For C++11, use a recursive formulation of `fac()`.
2586 ##### Note
2588 `constexpr` does not guarantee compile-time evaluation;
2589 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.
2591     constexpr int min(int x, int y) { return x < y ? x : y; }
2593     void test(int v)
2594     {
2595         int m1 = min(-1, 2);            // probably compile-time evaluation
2596         constexpr int m2 = min(-1, 2);  // compile-time evaluation
2597         int m3 = min(-1, v);            // run-time evaluation
2598         constexpr int m4 = min(-1, v);  // error: cannot evaluate at compile time
2599     }
2601 ##### Note
2603 Don't try to make all functions `constexpr`.
2604 Most computation is best done at run time.
2606 ##### Note
2608 Any API that may eventually depend on high-level run-time configuration or
2609 business logic should not be made `constexpr`. Such customization can not be
2610 evaluated by the compiler, and any `constexpr` functions that depended upon
2611 that API would have to be refactored or drop `constexpr`.
2613 ##### Enforcement
2615 Impossible and unnecessary.
2616 The compiler gives an error if a non-`constexpr` function is called where a constant is required.
2618 ### <a name="Rf-inline"></a>F.5: If a function is very small and time-critical, declare it `inline`
2620 ##### Reason
2622 Some optimizers are good at inlining without hints from the programmer, but don't rely on it.
2623 Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans.
2624 We are still waiting.
2625 Specifying `inline` encourages the compiler to do a better job.
2627 ##### Example
2629     inline string cat(const string& s, const string& s2) { return s + s2; }
2631 ##### Exception
2633 Do not put an `inline` function in what is meant to be a stable interface unless you are certain that it will not change.
2634 An inline function is part of the ABI.
2636 ##### Note
2638 `constexpr` implies `inline`.
2640 ##### Note
2642 Member functions defined in-class are `inline` by default.
2644 ##### Exception
2646 Template functions (incl. template member functions) are normally defined in headers and therefore inline.
2648 ##### Enforcement
2650 Flag `inline` functions that are more than three statements and could have been declared out of line (such as class member functions).
2652 ### <a name="Rf-noexcept"></a>F.6: If your function may not throw, declare it `noexcept`
2654 ##### Reason
2656 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.
2658 ##### Example
2660 Put `noexcept` on every function written completely in C or in any other language without exceptions.
2661 The C++ Standard Library does that implicitly for all functions in the C Standard Library.
2663 ##### Note
2665 `constexpr` functions can throw when evaluated at run time, so you may need `noexcept` for some of those.
2667 ##### Example
2669 You can use `noexcept` even on functions that can throw:
2671     vector<string> collect(istream& is) noexcept
2672     {
2673         vector<string> res;
2674         for (string s; is >> s;)
2675             res.push_back(s);
2676         return res;
2677     }
2679 If `collect()` runs out of memory, the program crashes.
2680 Unless the program is crafted to survive memory exhaustion, that may be just the right thing to do;
2681 `terminate()` may generate suitable error log information (but after memory runs out it is hard to do anything clever).
2683 ##### Note
2685 You must be aware of the execution environment that your code is running when
2686 deciding whether to tag a function `noexcept`, especially because of the issue
2687 of throwing and allocation.  Code that is intended to be perfectly general (like
2688 the standard library and other utility code of that sort) needs to support
2689 environments where a `bad_alloc` exception may be handled meaningfully.
2690 However, most programs and execution environments cannot meaningfully
2691 handle a failure to allocate, and aborting the program is the cleanest and
2692 simplest response to an allocation failure in those cases.  If you know that
2693 your application code cannot respond to an allocation failure, it may be
2694 appropriate to add `noexcept` even on functions that allocate.
2696 Put another way: In most programs, most functions can throw (e.g., because they
2697 use `new`, call functions that do, or use library functions that reports failure
2698 by throwing), so don't just sprinkle `noexcept` all over the place without
2699 considering whether the possible exceptions can be handled.
2701 `noexcept` is most useful (and most clearly correct) for frequently used,
2702 low-level functions.
2704 ##### Note
2706 Destructors, `swap` functions, move operations, and default constructors should never throw.
2707 See also [C.44](#Rc-default00).
2709 ##### Enforcement
2711 * Flag functions that are not `noexcept`, yet cannot throw.
2712 * Flag throwing `swap`, `move`, destructors, and default constructors.
2714 ### <a name="Rf-smart"></a>F.7: For general use, take `T*` or `T&` arguments rather than smart pointers
2716 ##### Reason
2718 Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended (see [R.30](#Rr-smartptrparam)).
2719 Passing by smart pointer restricts the use of a function to callers that use smart pointers.
2720 Passing a shared smart pointer (e.g., `std::shared_ptr`) implies a run-time cost.
2722 ##### Example
2724     // accepts any int*
2725     void f(int*);
2727     // can only accept ints for which you want to transfer ownership
2728     void g(unique_ptr<int>);
2730     // can only accept ints for which you are willing to share ownership
2731     void g(shared_ptr<int>);
2733     // doesn't change ownership, but requires a particular ownership of the caller
2734     void h(const unique_ptr<int>&);
2736     // accepts any int
2737     void h(int&);
2739 ##### Example, bad
2741     // callee
2742     void f(shared_ptr<widget>& w)
2743     {
2744         // ...
2745         use(*w); // only use of w -- the lifetime is not used at all
2746         // ...
2747     };
2749 See further in [R.30](#Rr-smartptrparam).
2751 ##### Note
2753 We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers.
2755 **See also**:
2757 * [Prefer `T*` over `T&` when "no argument" is a valid option](#Rf-ptr-ref)
2758 * [Smart pointer rule summary](#Rr-summary-smartptrs)
2760 ##### Enforcement
2762 Flag a parameter of a smart pointer type (a type that overloads `operator->` or `operator*`) for which the ownership semantics are not used;
2763 that is
2765 * copyable but never copied/moved from or movable but never moved
2766 * and that is never modified or passed along to another function that could do so.
2768 ### <a name="Rf-pure"></a>F.8: Prefer pure functions
2770 ##### Reason
2772 Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.
2774 ##### Example
2776     template<class T>
2777     auto square(T t) { return t * t; }
2779 ##### Enforcement
2781 Not possible.
2783 ### <a name="Rf-unused"></a>F.9: Unused parameters should be unnamed
2785 ##### Reason
2787 Readability.
2788 Suppression of unused parameter warnings.
2790 ##### Example
2792     X* find(map<Blob>& m, const string& s, Hint);   // once upon a time, a hint was used
2794 ##### Note
2796 Allowing parameters to be unnamed was introduced in the early 1980 to address this problem.
2798 ##### Enforcement
2800 Flag named unused parameters.
2802 ## <a name="SS-call"></a>F.call: Parameter passing
2804 There are a variety of ways to pass parameters to a function and to return values.
2806 ### <a name="Rf-conventional"></a>F.15: Prefer simple and conventional ways of passing information
2808 ##### Reason
2810 Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs.
2811 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 may not be portable.
2813 The following tables summarize the advice in the following Guidelines, F.16-21.
2815 Normal parameter passing:
2817 ![Normal parameter passing table](./param-passing-normal.png "Normal parameter passing")
2819 Advanced parameter passing:
2821 ![Advanced parameter passing table](./param-passing-advanced.png "Advanced parameter passing")
2823 Use the advanced techniques only after demonstrating need, and document that need in a comment.
2825 ### <a name="Rf-in"></a>F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`
2827 ##### Reason
2829 Both let the caller know that a function will not modify the argument, and both allow initialization by rvalues.
2831 What is "cheap to copy" depends on the machine architecture, but two or three words (doubles, pointers, references) are usually best passed by value.
2832 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.
2834 ##### Example
2836     void f1(const string& s);  // OK: pass by reference to const; always cheap
2838     void f2(string s);         // bad: potentially expensive
2840     void f3(int x);            // OK: Unbeatable
2842     void f4(const int& x);     // bad: overhead on access in f4()
2844 For advanced uses (only), where you really need to optimize for rvalues passed to "input-only" parameters:
2846 * If the function is going to unconditionally move from the argument, take it by `&&`. See [F.18](#Rf-consume).
2847 * If the function is going to keep a copy of the argument, in addition to passing by `const&` (for lvalues),
2848   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).
2849 * In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. See [F.19](#Rf-forward).
2851 ##### Example
2853     int multiply(int, int); // just input ints, pass by value
2855     // suffix is input-only but not as cheap as an int, pass by const&
2856     string& concatenate(string&, const string& suffix);
2858     void sink(unique_ptr<widget>);  // input only, and moves ownership of the widget
2860 Avoid "esoteric techniques" such as:
2862 * Passing arguments as `T&&` "for efficiency".
2863   Most rumors about performance advantages from passing by `&&` are false or brittle (but see [F.18](#Rf-consume) and [F.19](#Rf-forward)).
2864 * Returning `const T&` from assignments and similar operations (see [F.47](#Rf-assignment-op).)
2866 ##### Example
2868 Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`):
2870     Matrix operator+(const Matrix& a, const Matrix& b)
2871     {
2872         Matrix res;
2873         // ... fill res with the sum ...
2874         return res;
2875     }
2877     Matrix x = m1 + m2;  // move constructor
2879     y = m3 + m3;         // move assignment
2881 ##### Notes
2883 The return value optimization doesn't handle the assignment case, but the move assignment does.
2885 A reference may be assumed to refer to a valid object (language rule).
2886 There is no (legitimate) "null reference."
2887 If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value."
2889 ##### Enforcement
2891 * (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than `2 * sizeof(void*)`.
2892   Suggest using a reference to `const` instead.
2893 * (Simple) ((Foundation)) Warn when a parameter passed by reference to `const` has a size less than `2 * sizeof(void*)`. Suggest passing by value instead.
2894 * (Simple) ((Foundation)) Warn when a parameter passed by reference to `const` is `move`d.
2896 ### <a name="Rf-inout"></a>F.17: For "in-out" parameters, pass by reference to non-`const`
2898 ##### Reason
2900 This makes it clear to callers that the object is assumed to be modified.
2902 ##### Example
2904     void update(Record& r);  // assume that update writes to r
2906 ##### Note
2908 A `T&` argument can pass information into a function as well as out of it.
2909 Thus `T&` could be an in-out-parameter. That can in itself be a problem and a source of errors:
2911     void f(string& s)
2912     {
2913         s = "New York";  // non-obvious error
2914     }
2916     void g()
2917     {
2918         string buffer = ".................................";
2919         f(buffer);
2920         // ...
2921     }
2923 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).
2924 A bad logic error can happen if the writer of `g()` incorrectly assumes the size of the `buffer`.
2926 ##### Enforcement
2928 * (Moderate) ((Foundation)) Warn about functions regarding reference to non-`const` parameters that do *not* write to them.
2929 * (Simple) ((Foundation)) Warn when a non-`const` parameter being passed by reference is `move`d.
2931 ### <a name="Rf-consume"></a>F.18: For "will-move-from" parameters, pass by `X&&` and `std::move` the parameter
2933 ##### Reason
2935 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.
2937 ##### Example
2939     void sink(vector<int>&& v) {   // sink takes ownership of whatever the argument owned
2940         // usually there might be const accesses of v here
2941         store_somewhere(std::move(v));
2942         // usually no more use of v here; it is moved-from
2943     }
2945 Note that the `std::move(v)` makes it possible for `store_somewhere()` to leave `v` in a moved-from state.
2946 [That could be dangerous](#Rc-move-semantic).
2949 ##### Exception
2951 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.
2953 For example:
2955     template <class T>
2956     void sink(std::unique_ptr<T> p) {
2957         // use p ... possibly std::move(p) onward somewhere else
2958     }   // p gets destroyed
2960 ##### Enforcement
2962 * Flag all `X&&` parameters (where `X` is not a template type parameter name) where the function body uses them without `std::move`.
2963 * Flag access to moved-from objects.
2964 * Don't conditionally move from objects
2966 ### <a name="Rf-forward"></a>F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter
2968 ##### Reason
2970 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.
2972 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.
2974 ##### Example
2976     template <class F, class... Args>
2977     inline auto invoke(F f, Args&&... args) {
2978         return f(forward<Args>(args)...);
2979     }
2981     ??? calls ???
2983 ##### Enforcement
2985 * 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.
2987 ### <a name="Rf-out"></a>F.20: For "out" output values, prefer return values to output parameters
2989 ##### Reason
2991 A return value is self-documenting, whereas a `&` could be either in-out or out-only and is liable to be misused.
2993 This includes large objects like standard containers that use implicit move operations for performance and to avoid explicit memory management.
2995 If you have multiple values to return, [use a tuple](#Rf-out-multi) or similar multi-member type.
2997 ##### Example
2999     // OK: return pointers to elements with the value x
3000     vector<const int*> find_all(const vector<int>&, int x);
3002     // Bad: place pointers to elements with value x in-out
3003     void find_all(const vector<int>&, vector<const int*>& out, int x);
3005 ##### Note
3007 A `struct` of many (individually cheap-to-move) elements may be in aggregate expensive to move.
3009 It is not recommended to return a `const` value.
3010 Such older advice is now obsolete; it does not add value, and it interferes with move semantics.
3012     const vector<int> fct();    // bad: that "const" is more trouble than it is worth
3014     vector<int> g(const vector<int>& vx)
3015     {
3016         // ...
3017         fct() = vx;   // prevented by the "const"
3018         // ...
3019         return fct(); // expensive copy: move semantics suppressed by the "const"
3020     }
3022 The argument for adding `const` to a return value is that it prevents (very rare) accidental access to a temporary.
3023 The argument against is prevents (very frequent) use of move semantics.
3025 ##### Exceptions
3027 * For non-value types, such as types in an inheritance hierarchy, return the object by `unique_ptr` or `shared_ptr`.
3028 * If a type is expensive to move (e.g., `array<BigPOD>`), 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).
3029 * 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).
3031 ##### Example
3033     struct Package {      // exceptional case: expensive-to-move object
3034         char header[16];
3035         char load[2024 - 16];
3036     };
3038     Package fill();       // Bad: large return value
3039     void fill(Package&);  // OK
3041     int val();            // OK
3042     void val(int&);       // Bad: Is val reading its argument
3044 ##### Enforcement
3046 * 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.
3047 * Flag returning a `const` value. To fix: Remove `const` to return a non-`const` value instead.
3049 ### <a name="Rf-out-multi"></a>F.21: To return multiple "out" values, prefer returning a struct or tuple
3051 ##### Reason
3053 A return value is self-documenting as an "output-only" value.
3054 Note that C++ does have multiple return values, by convention of using a `tuple` (including `pair`),
3055 possibly with the extra convenience of `tie` at the call site.
3056 Prefer using a named struct where there are semantics to the returned value. Otherwise, a nameless `tuple` is useful in generic code.
3058 ##### Example
3060     // BAD: output-only parameter documented in a comment
3061     int f(const string& input, /*output only*/ string& output_data)
3062     {
3063         // ...
3064         output_data = something();
3065         return status;
3066     }
3068     // GOOD: self-documenting
3069     tuple<int, string> f(const string& input)
3070     {
3071         // ...
3072         return make_tuple(status, something());
3073     }
3075 C++98's standard library already used this style, because a `pair` is like a two-element `tuple`.
3076 For example, given a `set<string> my_set`, consider:
3078     // C++98
3079     result = my_set.insert("Hello");
3080     if (result.second) do_something_with(result.first);    // workaround
3082 With C++11 we can write this, putting the results directly in existing local variables:
3084     Sometype iter;                                // default initialize if we haven't already
3085     Someothertype success;                        // used these variables for some other purpose
3087     tie(iter, success) = my_set.insert("Hello");   // normal return value
3088     if (success) do_something_with(iter);
3090 With C++17 we are able to use "structured bindings" to declare and initialize the multiple variables:
3092     if (auto [ iter, success ] = my_set.insert("Hello"); success) do_something_with(iter);
3094 ##### Exception
3096 Sometimes, we need to pass an object to a function to manipulate its state.
3097 In such cases, passing the object by reference [`T&`](#Rf-inout) is usually the right technique.
3098 Explicitly passing an in-out parameter back out again as a return value is often not necessary.
3099 For example:
3101     istream& operator>>(istream& is, string& s);    // much like std::operator>>()
3103     for (string s; cin >> s; ) {
3104         // do something with line
3105     }
3107 Here, both `s` and `cin` are used as in-out parameters.
3108 We pass `cin` by (non-`const`) reference to be able to manipulate its state.
3109 We pass `s` to avoid repeated allocations.
3110 By reusing `s` (passed by reference), we allocate new memory only when we need to expand `s`'s capacity.
3111 This technique is sometimes called the "caller-allocated out" pattern and is particularly useful for types,
3112 such as `string` and `vector`, that needs to do free store allocations.
3114 To compare, if we passed out all values as return values, we would something like this:
3116     pair<istream&, string> get_string(istream& is);  // not recommended
3117     {
3118         string s;
3119         is >> s;
3120         return {is, s};
3121     }
3123     for (auto p = get_string(cin); p.first; ) {
3124         // do something with p.second
3125     }
3127 We consider that significantly less elegant with significantly less performance.
3129 For a truly strict reading of this rule (F.21), the exception isn't really an exception because it relies on in-out parameters,
3130 rather than the plain out parameters mentioned in the rule.
3131 However, we prefer to be explicit, rather than subtle.
3133 ##### Note
3135 In many cases, it may be useful to return a specific, user-defined type.
3136 For example:
3138     struct Distance {
3139         int value;
3140         int unit = 1;   // 1 means meters
3141     };
3143     Distance d1 = measure(obj1);        // access d1.value and d1.unit
3144     auto d2 = measure(obj2);            // access d2.value and d2.unit
3145     auto [value, unit] = measure(obj3); // access value and unit; somewhat redundant
3146                                         // to people who know measure()
3147     auto [x, y] = measure(obj4);        // don't; it's likely to be confusing
3149 The overly-generic `pair` and `tuple` should be used only when the value returned represents independent entities rather than an abstraction.
3151 Another example, use a specific type along the lines of `variant<T, error_code>`, rather than using the generic `tuple`.
3153 ##### Enforcement
3155 * Output parameters should be replaced by return values.
3156   An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`.
3158 ### <a name="Rf-ptr"></a>F.22: Use `T*` or `owner<T*>` to designate a single object
3160 ##### Reason
3162 Readability: it makes the meaning of a plain pointer clear.
3163 Enables significant tool support.
3165 ##### Note
3167 In traditional C and C++ code, plain `T*` is used for many weakly-related purposes, such as:
3169 * Identify a (single) object (not to be deleted by this function)
3170 * Point to an object allocated on the free store (and delete it later)
3171 * Hold the `nullptr`
3172 * Identify a C-style string (zero-terminated array of characters)
3173 * Identify an array with a length specified separately
3174 * Identify a location in an array
3176 This makes it hard to understand what the code does and is supposed to do.
3177 It complicates checking and tool support.
3179 ##### Example
3181     void use(int* p, int n, char* s, int* q)
3182     {
3183         p[n - 1] = 666; // Bad: we don't know if p points to n elements;
3184                         // assume it does not or use span<int>
3185         cout << s;      // Bad: we don't know if that s points to a zero-terminated array of char;
3186                         // assume it does not or use zstring
3187         delete q;       // Bad: we don't know if *q is allocated on the free store;
3188                         // assume it does not or use owner
3189     }
3191 better
3193     void use2(span<int> p, zstring s, owner<int*> q)
3194     {
3195         p[p.size() - 1] = 666; // OK, a range error can be caught
3196         cout << s; // OK
3197         delete q;  // OK
3198     }
3200 ##### Note
3202 `owner<T*>` represents ownership, `zstring` represents a C-style string.
3204 **Also**: Assume that a `T*` obtained from a smart pointer to `T` (e.g., `unique_ptr<T>`) points to a single element.
3206 **See also**: [Support library](#S-gsl)
3208 **See also**: [Do not pass an array as a single pointer](#Ri-array)
3210 ##### Enforcement
3212 * (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
3214 ### <a name="Rf-nullptr"></a>F.23: Use a `not_null<T>` to indicate that "null" is not a valid value
3216 ##### Reason
3218 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 may be necessary.
3219 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`.
3221 ##### Example
3223 `not_null<T*>` makes it obvious to a reader (human or machine) that a test for `nullptr` is not necessary before dereference.
3224 Additionally, when debugging, `owner<T*>` and `not_null<T>` can be instrumented to check for correctness.
3226 Consider:
3228     int length(Record* p);
3230 When I call `length(p)` should I check if `p` is `nullptr` first? Should the implementation of `length()` check if `p` is `nullptr`?
3232     // it is the caller's job to make sure p != nullptr
3233     int length(not_null<Record*> p);
3235     // the implementor of length() must assume that p == nullptr is possible
3236     int length(Record* p);
3238 ##### Note
3240 A `not_null<T*>` is assumed not to be the `nullptr`; a `T*` may be the `nullptr`; both can be represented in memory as a `T*` (so no run-time overhead is implied).
3242 ##### Note
3244 `not_null` is not just for built-in pointers. It works for `unique_ptr`, `shared_ptr`, and other pointer-like types.
3246 ##### Enforcement
3248 * (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.
3249 * (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against `nullptr` (or equivalent) within the function and sometimes is not.
3250 * (Simple) Warn if a `not_null` pointer is tested against `nullptr` within a function.
3252 ### <a name="Rf-range"></a>F.24: Use a `span<T>` or a `span_p<T>` to designate a half-open sequence
3254 ##### Reason
3256 Informal/non-explicit ranges are a source of errors.
3258 ##### Example
3260     X* find(span<X> r, const X& v);    // find v in r
3262     vector<X> vec;
3263     // ...
3264     auto p = find({vec.begin(), vec.end()}, X{});  // find X{} in vec
3266 ##### Note
3268 Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure.
3269 In particular, given a pair of arguments `(p, n)` designating an array `[p:p+n)`,
3270 it is in general impossible to know if there really are `n` elements to access following `*p`.
3271 `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.
3273 ##### Example
3275 A `span` represents a range of elements, but how do we manipulate elements of that range?
3277     void f(span<int> s)
3278     {
3279         // range traversal (guaranteed correct)
3280         for (int x : s) cout << x << '\n';
3282         // C-style traversal (potentially checked)
3283         for (gsl::index i = 0; i < s.size(); ++i) cout << s[i] << '\n';
3285         // random access (potentially checked)
3286         s[7] = 9;
3288         // extract pointers (potentially checked)
3289         std::sort(&s[0], &s[s.size() / 2]);
3290     }
3292 ##### Note
3294 A `span<T>` object does not own its elements and is so small that it can be passed by value.
3296 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.
3298 **See also**: [Support library](#S-gsl)
3300 ##### Enforcement
3302 (Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `span` instead.
3304 ### <a name="Rf-zstring"></a>F.25: Use a `zstring` or a `not_null<zstring>` to designate a C-style string
3306 ##### Reason
3308 C-style strings are ubiquitous. They are defined by convention: zero-terminated arrays of characters.
3309 We must distinguish C-style strings from a pointer to a single character or an old-fashioned pointer to an array of characters.
3311 If you don't need null termination, use `string_view`.
3313 ##### Example
3315 Consider:
3317     int length(const char* p);
3319 When I call `length(s)` should I check if `s` is `nullptr` first? Should the implementation of `length()` check if `p` is `nullptr`?
3321     // the implementor of length() must assume that p == nullptr is possible
3322     int length(zstring p);
3324     // it is the caller's job to make sure p != nullptr
3325     int length(not_null<zstring> p);
3327 ##### Note
3329 `zstring` does not represent ownership.
3331 **See also**: [Support library](#S-gsl)
3333 ### <a name="Rf-unique_ptr"></a>F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed
3335 ##### Reason
3337 Using `unique_ptr` is the cheapest way to pass a pointer safely.
3339 **See also**: [C.50](#Rc-factory) regarding when to return a `shared_ptr` from a factory.
3341 ##### Example
3343     unique_ptr<Shape> get_shape(istream& is)  // assemble shape from input stream
3344     {
3345         auto kind = read_header(is); // read header and identify the next shape on input
3346         switch (kind) {
3347         case kCircle:
3348             return make_unique<Circle>(is);
3349         case kTriangle:
3350             return make_unique<Triangle>(is);
3351         // ...
3352         }
3353     }
3355 ##### Note
3357 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).
3359 ##### Enforcement
3361 (Simple) Warn if a function returns a locally allocated raw pointer. Suggest using either `unique_ptr` or `shared_ptr` instead.
3363 ### <a name="Rf-shared_ptr"></a>F.27: Use a `shared_ptr<T>` to share ownership
3365 ##### Reason
3367 Using `std::shared_ptr` is the standard way to represent shared ownership. That is, the last owner deletes the object.
3369 ##### Example
3371     shared_ptr<const Image> im { read_image(somewhere) };
3373     std::thread t0 {shade, args0, top_left, im};
3374     std::thread t1 {shade, args1, top_right, im};
3375     std::thread t2 {shade, args2, bottom_left, im};
3376     std::thread t3 {shade, args3, bottom_right, im};
3378     // detach threads
3379     // last thread to finish deletes the image
3381 ##### Note
3383 Prefer a `unique_ptr` over a `shared_ptr` if there is never more than one owner at a time.
3384 `shared_ptr` is for shared ownership.
3386 Note that pervasive use of `shared_ptr` has a cost (atomic operations on the `shared_ptr`'s reference count have a measurable aggregate cost).
3388 ##### Alternative
3390 Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.
3392 ##### Enforcement
3394 (Not enforceable) This is a too complex pattern to reliably detect.
3396 ### <a name="Rf-ptr-ref"></a>F.60: Prefer `T*` over `T&` when "no argument" is a valid option
3398 ##### Reason
3400 A pointer (`T*`) can be a `nullptr` and a reference (`T&`) cannot, there is no valid "null reference".
3401 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.
3403 ##### Example
3405     string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string
3406     {
3407         if (!p) return string{};    // p might be nullptr; remember to check
3408         return string{p};
3409     }
3411     void print(const vector<int>& r)
3412     {
3413         // r refers to a vector<int>; no check needed
3414     }
3416 ##### Note
3418 It is possible, but not valid C++ to construct a reference that is essentially a `nullptr` (e.g., `T* p = nullptr; T& r = (T&)*p;`).
3419 That error is very uncommon.
3421 ##### Note
3423 If you prefer the pointer notation (`->` and/or `*` vs. `.`), `not_null<T*>` provides the same guarantee as `T&`.
3425 ##### Enforcement
3427 * Flag ???
3429 ### <a name="Rf-return-ptr"></a>F.42: Return a `T*` to indicate a position (only)
3431 ##### Reason
3433 That's what pointers are good for.
3434 Returning a `T*` to transfer ownership is a misuse.
3436 ##### Example
3438     Node* find(Node* t, const string& s)  // find s in a binary tree of Nodes
3439     {
3440         if (!t || t->name == s) return t;
3441         if ((auto p = find(t->left, s))) return p;
3442         if ((auto p = find(t->right, s))) return p;
3443         return nullptr;
3444     }
3446 If it isn't the `nullptr`, the pointer returned by `find` indicates a `Node` holding `s`.
3447 Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller.
3449 ##### Note
3451 Positions can also be transferred by iterators, indices, and references.
3452 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](???).
3454 ##### Note
3456 Do not return a pointer to something that is not in the caller's scope; see [F.43](#Rf-dangle).
3458 **See also**: [discussion of dangling pointer prevention](#???)
3460 ##### Enforcement
3462 * Flag `delete`, `std::free()`, etc. applied to a plain `T*`.
3463 Only owners should be deleted.
3464 * Flag `new`, `malloc()`, etc. assigned to a plain `T*`.
3465 Only owners should be responsible for deletion.
3467 ### <a name="Rf-dangle"></a>F.43: Never (directly or indirectly) return a pointer or a reference to a local object
3469 ##### Reason
3471 To avoid the crashes and data corruption that can result from the use of such a dangling pointer.
3473 ##### Example, bad
3475 After the return from a function its local objects no longer exist:
3477     int* f()
3478     {
3479         int fx = 9;
3480         return &fx;  // BAD
3481     }
3483     void g(int* p)   // looks innocent enough
3484     {
3485         int gx;
3486         cout << "*p == " << *p << '\n';
3487         *p = 999;
3488         cout << "gx == " << gx << '\n';
3489     }
3491     void h()
3492     {
3493         int* p = f();
3494         int z = *p;  // read from abandoned stack frame (bad)
3495         g(p);        // pass pointer to abandoned stack frame to function (bad)
3496     }
3498 Here on one popular implementation I got the output:
3500     *p == 999
3501     gx == 999
3503 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`.
3505 * Imagine what would happen if `fx` and `gx` were of different types.
3506 * Imagine what would happen if `fx` or `gx` was a type with an invariant.
3507 * Imagine what would happen if more that dangling pointer was passed around among a larger set of functions.
3508 * Imagine what a cracker could do with that dangling pointer.
3510 Fortunately, most (all?) modern compilers catch and warn against this simple case.
3512 ##### Note
3514 This applies to references as well:
3516     int& f()
3517     {
3518         int x = 7;
3519         // ...
3520         return x;  // Bad: returns reference to object that is about to be destroyed
3521     }
3523 ##### Note
3525 This applies only to non-`static` local variables.
3526 All `static` variables are (as their name indicates) statically allocated, so that pointers to them cannot dangle.
3528 ##### Example, bad
3530 Not all examples of leaking a pointer to a local variable are that obvious:
3532     int* glob;       // global variables are bad in so many ways
3534     template<class T>
3535     void steal(T x)
3536     {
3537         glob = x();  // BAD
3538     }
3540     void f()
3541     {
3542         int i = 99;
3543         steal([&] { return &i; });
3544     }
3546     int main()
3547     {
3548         f();
3549         cout << *glob << '\n';
3550     }
3552 Here I managed to read the location abandoned by the call of `f`.
3553 The pointer stored in `glob` could be used much later and cause trouble in unpredictable ways.
3555 ##### Note
3557 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.
3559 ##### Note
3561 Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one;
3562 such examples are handled equivalently to leaks of pointers out of a function.
3564 A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to.
3566 **See also**: Another way of getting dangling pointers is [pointer invalidation](#???).
3567 It can be detected/prevented with similar techniques.
3569 ##### Enforcement
3571 * Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals.
3572 * Static analysis can catch many common patterns of the use of pointers indicating positions (thus eliminating dangling pointers)
3574 ### <a name="Rf-return-ref"></a>F.44: Return a `T&` when copy is undesirable and "returning no object" isn't needed
3576 ##### Reason
3578 The language guarantees that a `T&` refers to an object, so that testing for `nullptr` isn't necessary.
3580 **See also**: The return of a reference must not imply transfer of ownership:
3581 [discussion of dangling pointer prevention](#???) and [discussion of ownership](#???).
3583 ##### Example
3585     class Car
3586     {
3587         array<wheel, 4> w;
3588         // ...
3589     public:
3590         wheel& get_wheel(int i) { Expects(i < w.size()); return w[i]; }
3591         // ...
3592     };
3594     void use()
3595     {
3596         Car c;
3597         wheel& w0 = c.get_wheel(0); // w0 has the same lifetime as c
3598     }
3600 ##### Enforcement
3602 Flag functions where no `return` expression could yield `nullptr`
3604 ### <a name="Rf-return-ref-ref"></a>F.45: Don't return a `T&&`
3606 ##### Reason
3608 It's asking to return a reference to a destroyed temporary object.
3609 A `&&` is a magnet for temporary objects.
3611 ##### Example
3613 A returned rvalue reference goes out of scope at the end of the full expression to which it is returned:
3615     auto&& x = max(0, 1);   // OK, so far
3616     foo(x);                 // Undefined behavior
3618 This kind of use is a frequent source of bugs, often incorrectly reported as a compiler bug.
3619 An implementer of a function should avoid setting such traps for users.
3621 The [lifetime safety profile](#SS-lifetime) will (when completely implemented) catch such problems.
3624 ##### Example
3626 Returning an rvalue reference is fine when the reference to the temporary is being passed "downward" to a callee;
3627 then, the temporary is guaranteed to outlive the function call (see [F.18](#Rf-consume) and [F.19](#Rf-forward)).
3628 However, it's not fine when passing such a reference "upward" to a larger caller scope.
3629 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&&`).
3631 Assume that `F` returns by value:
3633     template<class F>
3634     auto&& wrapper(F f)
3635     {
3636         log_call(typeid(f)); // or whatever instrumentation
3637         return f();          // BAD: returns a reference to a temporary
3638     }
3640 Better:
3642     template<class F>
3643     auto wrapper(F f)
3644     {
3645         log_call(typeid(f)); // or whatever instrumentation
3646         return f();          // OK
3647     }
3650 ##### Exception
3652 `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 `&&`.
3654 ##### Enforcement
3656 Flag any use of `&&` as a return type, except in `std::move` and `std::forward`.
3658 ### <a name="Rf-main"></a>F.46: `int` is the return type for `main()`
3660 ##### Reason
3662 It's a language rule, but violated through "language extensions" so often that it is worth mentioning.
3663 Declaring `main` (the one global `main` of a program) `void` limits portability.
3665 ##### Example
3667         void main() { /* ... */ };  // bad, not C++
3669         int main()
3670         {
3671             std::cout << "This is the way to do it\n";
3672         }
3674 ##### Note
3676 We mention this only because of the persistence of this error in the community.
3678 ##### Enforcement
3680 * The compiler should do it
3681 * If the compiler doesn't do it, let tools flag it
3683 ### <a name="Rf-assignment-op"></a>F.47: Return `T&` from assignment operators
3685 ##### Reason
3687 The convention for operator overloads (especially on value types) is for
3688 `operator=(const T&)` to perform the assignment and then return (non-`const`)
3689 `*this`.  This ensures consistency with standard-library types and follows the
3690 principle of "do as the ints do."
3692 ##### Note
3694 Historically there was some guidance to make the assignment operator return `const T&`.
3695 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.
3697 ##### Example
3699     class Foo
3700     {
3701      public:
3702         ...
3703         Foo& operator=(const Foo& rhs) {
3704           // Copy members.
3705           ...
3706           return *this;
3707         }
3708     };
3710 ##### Enforcement
3712 This should be enforced by tooling by checking the return type (and return
3713 value) of any assignment operator.
3716 ### <a name="Rf-return-move-local"></a>F.48: Don't `return std::move(local)`
3718 ##### Reason
3720 With guaranteed copy elision, it is now almost always a pessimization to expressly use `std::move` in a return statement.
3722 ##### Example, bad
3724     S f()
3725     {
3726       S result;
3727       return std::move(result);
3728     }
3730 ##### Example, good
3732     S f()
3733     {
3734       S result;
3735       return result;
3736     }
3738 ##### Enforcement
3740 This should be enforced by tooling by checking the return expression .
3743 ### <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)
3745 ##### Reason
3747 Functions can't capture local variables or be declared 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.
3749 ##### Example
3751     // writing a function that should only take an int or a string
3752     // -- overloading is natural
3753     void f(int);
3754     void f(const string&);
3756     // writing a function object that needs to capture local state and appear
3757     // at statement or expression scope -- a lambda is natural
3758     vector<work> v = lots_of_work();
3759     for (int tasknum = 0; tasknum < max; ++tasknum) {
3760         pool.run([=, &v]{
3761             /*
3762             ...
3763             ... process 1 / max - th of v, the tasknum - th chunk
3764             ...
3765             */
3766         });
3767     }
3768     pool.join();
3770 ##### Exception
3772 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.
3774 ##### Enforcement
3776 * 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.
3778 ### <a name="Rf-default-args"></a>F.51: Where there is a choice, prefer default arguments over overloading
3780 ##### Reason
3782 Default arguments simply provide alternative interfaces to a single implementation.
3783 There is no guarantee that a set of overloaded functions all implement the same semantics.
3784 The use of default arguments can avoid code replication.
3786 ##### Note
3788 There is a choice between using default argument and overloading when the alternatives are from a set of arguments of the same types.
3789 For example:
3791     void print(const string& s, format f = {});
3793 as opposed to
3795     void print(const string& s);  // use default format
3796     void print(const string& s, format f);
3798 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:
3800     void print(const char&);
3801     void print(int);
3802     void print(zstring);
3804 ##### See also
3807 [Default arguments for virtual functions](#Rh-virtual-default-arg)
3809 ##### Enforcement
3811 * 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.)
3813 ### <a name="Rf-reference-capture"></a>F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms
3815 ##### Reason
3817 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.
3819 ##### Discussion
3821 The efficiency consideration is that most types are cheaper to pass by reference than by value.
3823 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.
3825 ##### Note
3827 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.
3829 ##### Example
3831 Here, a large object (a network message) is passed to an iterative algorithm, and is it not efficient or correct to copy the message (which may not be copyable):
3833     std::for_each(begin(sockets), end(sockets), [&message](auto& socket)
3834     {
3835         socket.send(message);
3836     });
3838 ##### Example
3840 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.
3842     void send_packets(buffers& bufs)
3843     {
3844         stage encryptor([] (buffer& b){ encrypt(b); });
3845         stage compressor([&](buffer& b){ compress(b); encryptor.process(b); });
3846         stage decorator([&](buffer& b){ decorate(b); compressor.process(b); });
3847         for (auto& b : bufs) { decorator.process(b); }
3848     }  // automatically blocks waiting for pipeline to finish
3850 ##### Enforcement
3852 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.)
3854 ### <a name="Rf-value-capture"></a>F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread
3856 ##### Reason
3858 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.
3860 ##### Example, bad
3862     int local = 42;
3864     // Want a reference to local.
3865     // Note, that after program exits this scope,
3866     // local no longer exists, therefore
3867     // process() call will have undefined behavior!
3868     thread_pool.queue_work([&]{ process(local); });
3870 ##### Example, good
3872     int local = 42;
3873     // Want a copy of local.
3874     // Since a copy of local is made, it will
3875     // always be available for the call.
3876     thread_pool.queue_work([=]{ process(local); });
3878 ##### Enforcement
3880 * (Simple) Warn when capture-list contains a reference to a locally declared variable
3881 * (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
3883 ### <a name="Rf-this-capture"></a>F.54: If you capture `this`, capture all variables explicitly (no default capture)
3885 ##### Reason
3887 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.
3889 ##### Example
3891     class My_class {
3892         int x = 0;
3893         // ...
3895         void f() {
3896             int i = 0;
3897             // ...
3899             auto lambda = [=]{ use(i, x); };   // BAD: "looks like" copy/value capture
3900             // [&] has identical semantics and copies the this pointer under the current rules
3901             // [=,this] and [&,this] are not much better, and confusing
3903             x = 42;
3904             lambda(); // calls use(0, 42);
3905             x = 43;
3906             lambda(); // calls use(0, 43);
3908             // ...
3910             auto lambda2 = [i, this]{ use(i, x); }; // ok, most explicit and least confusing
3912             // ...
3913         }
3914     };
3916 ##### Note
3918 This is under active discussion in standardization, and may be addressed in a future version of the standard by adding a new capture mode or possibly adjusting the meaning of `[=]`. For now, just be explicit.
3920 ##### Enforcement
3922 * Flag any lambda capture-list that specifies a default capture and also captures `this` (whether explicitly or via default capture)
3924 ### <a name="F-varargs"></a>F.55: Don't use `va_arg` arguments
3926 ##### Reason
3928 Reading from a `va_arg` assumes that the correct type was actually passed.
3929 Passing to varargs assumes the correct type will be read.
3930 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.
3932 ##### Example
3934     int sum(...) {
3935         // ...
3936         while (/*...*/)
3937             result += va_arg(list, int); // BAD, assumes it will be passed ints
3938         // ...
3939     }
3941     sum(3, 2); // ok
3942     sum(3.14159, 2.71828); // BAD, undefined
3944     template<class ...Args>
3945     auto sum(Args... args) { // GOOD, and much more flexible
3946         return (... + args); // note: C++17 "fold expression"
3947     }
3949     sum(3, 2); // ok: 5
3950     sum(3.14159, 2.71828); // ok: ~5.85987
3952 ##### Alternatives
3954 * overloading
3955 * variadic templates
3956 * `variant` arguments
3957 * `initializer_list` (homogeneous)
3959 ##### Note
3961 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.
3963 ##### Enforcement
3965 * Issue a diagnostic for using `va_list`, `va_start`, or `va_arg`.
3966 * 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)]]`.
3968 # <a name="S-class"></a>C: Classes and class hierarchies
3970 A class is a user-defined type, for which a programmer can define the representation, operations, and interfaces.
3971 Class hierarchies are used to organize related classes into hierarchical structures.
3973 Class rule summary:
3975 * [C.1: Organize related data into structures (`struct`s or `class`es)](#Rc-org)
3976 * [C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently](#Rc-struct)
3977 * [C.3: Represent the distinction between an interface and an implementation using a class](#Rc-interface)
3978 * [C.4: Make a function a member only if it needs direct access to the representation of a class](#Rc-member)
3979 * [C.5: Place helper functions in the same namespace as the class they support](#Rc-helper)
3980 * [C.7: Don't define a class or enum and declare a variable of its type in the same statement](#Rc-standalone)
3981 * [C.8: Use `class` rather than `struct` if any member is non-public](#Rc-class)
3982 * [C.9: Minimize exposure of members](#Rc-private)
3984 Subsections:
3986 * [C.concrete: Concrete types](#SS-concrete)
3987 * [C.ctor: Constructors, assignments, and destructors](#S-ctor)
3988 * [C.con: Containers and other resource handles](#SS-containers)
3989 * [C.lambdas: Function objects and lambdas](#SS-lambdas)
3990 * [C.hier: Class hierarchies (OOP)](#SS-hier)
3991 * [C.over: Overloading and overloaded operators](#SS-overload)
3992 * [C.union: Unions](#SS-union)
3994 ### <a name="Rc-org"></a>C.1: Organize related data into structures (`struct`s or `class`es)
3996 ##### Reason
3998 Ease of comprehension.
3999 If data is related (for fundamental reasons), that fact should be reflected in code.
4001 ##### Example
4003     void draw(int x, int y, int x2, int y2);  // BAD: unnecessary implicit relationships
4004     void draw(Point from, Point to);          // better
4006 ##### Note
4008 A simple class without virtual functions implies no space or time overhead.
4010 ##### Note
4012 From a language perspective `class` and `struct` differ only in the default visibility of their members.
4014 ##### Enforcement
4016 Probably impossible. Maybe a heuristic looking for data items used together is possible.
4018 ### <a name="Rc-struct"></a>C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently
4020 ##### Reason
4022 Readability.
4023 Ease of comprehension.
4024 The use of `class` alerts the programmer to the need for an invariant.
4025 This is a useful convention.
4027 ##### Note
4029 An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume.
4030 After the invariant is established (typically by a constructor) every member function can be called for the object.
4031 An invariant can be stated informally (e.g., in a comment) or more formally using `Expects`.
4033 If all data members can vary independently of each other, no invariant is possible.
4035 ##### Example
4037     struct Pair {  // the members can vary independently
4038         string name;
4039         int volume;
4040     };
4042 but:
4044     class Date {
4045     public:
4046         // validate that {yy, mm, dd} is a valid date and initialize
4047         Date(int yy, Month mm, char dd);
4048         // ...
4049     private:
4050         int y;
4051         Month m;
4052         char d;    // day
4053     };
4055 ##### Note
4057 If a class has any `private` data, a user cannot completely initialize an object without the use of a constructor.
4058 Hence, the class definer will provide a constructor and must specify its meaning.
4059 This effectively means the definer need to define an invariant.
4061 **See also**:
4063 * [define a class with private data as `class`](#Rc-class)
4064 * [Prefer to place the interface first in a class](#Rl-order)
4065 * [minimize exposure of members](#Rc-private)
4066 * [Avoid `protected` data](#Rh-protected)
4068 ##### Enforcement
4070 Look for `struct`s with all data private and `class`es with public members.
4072 ### <a name="Rc-interface"></a>C.3: Represent the distinction between an interface and an implementation using a class
4074 ##### Reason
4076 An explicit distinction between interface and implementation improves readability and simplifies maintenance.
4078 ##### Example
4080     class Date {
4081         // ... some representation ...
4082     public:
4083         Date();
4084         // validate that {yy, mm, dd} is a valid date and initialize
4085         Date(int yy, Month mm, char dd);
4087         int day() const;
4088         Month month() const;
4089         // ...
4090     };
4092 For example, we can now change the representation of a `Date` without affecting its users (recompilation is likely, though).
4094 ##### Note
4096 Using a class in this way to represent the distinction between interface and implementation is of course not the only way.
4097 For example, we can use a set of declarations of freestanding functions in a namespace, an abstract base class, or a template function with concepts to represent an interface.
4098 The most important issue is to explicitly distinguish between an interface and its implementation "details."
4099 Ideally, and typically, an interface is far more stable than its implementation(s).
4101 ##### Enforcement
4105 ### <a name="Rc-member"></a>C.4: Make a function a member only if it needs direct access to the representation of a class
4107 ##### Reason
4109 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.
4111 ##### Example
4113     class Date {
4114         // ... relatively small interface ...
4115     };
4117     // helper functions:
4118     Date next_weekday(Date);
4119     bool operator==(Date, Date);
4121 The "helper functions" have no need for direct access to the representation of a `Date`.
4123 ##### Note
4125 This rule becomes even better if C++ gets ["uniform function call"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0251r0.pdf).
4127 ##### Exception
4129 The language requires `virtual` functions to be members, and not all `virtual` functions directly access data.
4130 In particular, members of an abstract class rarely do.
4132 Note [multi-methods](https://parasol.tamu.edu/~yuriys/papers/OMM10.pdf).
4134 ##### Exception
4136 The language requires operators `=`, `()`, `[]`, and `->` to be members.
4138 ##### Exception
4140 An overload set may have some members that do not directly access `private` data:
4142     class Foobar {
4143     public:
4144         void foo(long x)    { /* manipulate private data */ }
4145         void foo(double x) { foo(std::lround(x)); }
4146         // ...
4147     private:
4148         // ...
4149     };
4151 ##### Exception
4153 Similarly, a set of functions may be designed to be used in a chain:
4155     x.scale(0.5).rotate(45).set_color(Color::red);
4157 Typically, some but not all of such functions directly access `private` data.
4159 ##### Enforcement
4161 * Look for non-`virtual` member functions that do not touch data members directly.
4162 The snag is that many member functions that do not need to touch data members directly do.
4163 * Ignore `virtual` functions.
4164 * Ignore functions that are part of an overload set out of which at least one function accesses `private` members.
4165 * Ignore functions returning `this`.
4167 ### <a name="Rc-helper"></a>C.5: Place helper functions in the same namespace as the class they support
4169 ##### Reason
4171 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.
4172 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.
4174 ##### Example
4176     namespace Chrono { // here we keep time-related services
4178         class Time { /* ... */ };
4179         class Date { /* ... */ };
4181         // helper functions:
4182         bool operator==(Date, Date);
4183         Date next_weekday(Date);
4184         // ...
4185     }
4187 ##### Note
4189 This is especially important for [overloaded operators](#Ro-namespace).
4191 ##### Enforcement
4193 * Flag global functions taking argument types from a single namespace.
4195 ### <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
4197 ##### Reason
4199 Mixing a type definition and the definition of another entity in the same declaration is confusing and unnecessary.
4201 ##### Example, bad
4203     struct Data { /*...*/ } data{ /*...*/ };
4205 ##### Example, good
4207     struct Data { /*...*/ };
4208     Data data{ /*...*/ };
4210 ##### Enforcement
4212 * Flag if the `}` of a class or enumeration definition is not followed by a `;`. The `;` is missing.
4214 ### <a name="Rc-class"></a>C.8: Use `class` rather than `struct` if any member is non-public
4216 ##### Reason
4218 Readability.
4219 To make it clear that something is being hidden/abstracted.
4220 This is a useful convention.
4222 ##### Example, bad
4224     struct Date {
4225         int d, m;
4227         Date(int i, Month m);
4228         // ... lots of functions ...
4229     private:
4230         int y;  // year
4231     };
4233 There is nothing wrong with this code as far as the C++ language rules are concerned,
4234 but nearly everything is wrong from a design perspective.
4235 The private data is hidden far from the public data.
4236 The data is split in different parts of the class declaration.
4237 Different parts of the data have different access.
4238 All of this decreases readability and complicates maintenance.
4240 ##### Note
4242 Prefer to place the interface first in a class, [see NL.16](#Rl-order).
4244 ##### Enforcement
4246 Flag classes declared with `struct` if there is a `private` or `protected` member.
4248 ### <a name="Rc-private"></a>C.9: Minimize exposure of members
4250 ##### Reason
4252 Encapsulation.
4253 Information hiding.
4254 Minimize the chance of unintended access.
4255 This simplifies maintenance.
4257 ##### Example
4259     template<typename T, typename U>
4260     struct pair {
4261         T a;
4262         U b;
4263         // ...
4264     };
4266 Whatever we do in the `//`-part, an arbitrary user of a `pair` can arbitrarily and independently change its `a` and `b`.
4267 In a large code base, we cannot easily find which code does what to the members of `pair`.
4268 This may be exactly what we want, but if we want to enforce a relation among members, we need to make them `private`
4269 and enforce that relation (invariant) through constructors and member functions.
4270 For example:
4272     class Distance {
4273     public:
4274         // ...
4275         double meters() const { return magnitude*unit; }
4276         void set_unit(double u)
4277         {
4278                 // ... check that u is a factor of 10 ...
4279                 // ... change magnitude appropriately ...
4280                 unit = u;
4281         }
4282         // ...
4283     private:
4284         double magnitude;
4285         double unit;    // 1 is meters, 1000 is kilometers, 0.001 is millimeters, etc.
4286     };
4288 ##### Note
4290 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.
4291 For `public` and `protected` data, that's usually the case.
4293 ##### Example
4295 A class can provide two interfaces to its users.
4296 One for derived classes (`protected`) and one for general users (`public`).
4297 For example, a derived class might be allowed to skip a run-time check because it has already guaranteed correctness:
4299     class Foo {
4300     public:
4301         int bar(int x) { check(x); return do_bar(x); }
4302         // ...
4303     protected:
4304         int do_bar(int x); // do some operation on the data
4305         // ...
4306     private:
4307         // ... data ...
4308     };
4310     class Dir : public Foo {
4311         //...
4312         int mem(int x, int y)
4313         {
4314             /* ... do something ... */
4315             return do_bar(x + y); // OK: derived class can bypass check
4316         }
4317     };
4319     void user(Foo& x)
4320     {
4321         int r1 = x.bar(1);      // OK, will check
4322         int r2 = x.do_bar(2);   // error: would bypass check
4323         // ...
4324     }
4326 ##### Note
4328 [`protected` data is a bad idea](#Rh-protected).
4330 ##### Note
4332 Prefer the order `public` members before `protected` members before `private` members [see](#Rl-order).
4334 ##### Enforcement
4336 * [Flag protected data](#Rh-protected).
4337 * Flag mixtures of `public` and private `data`
4339 ## <a name="SS-concrete"></a>C.concrete: Concrete types
4341 One ideal for a class is to be a regular type.
4342 That means roughly "behaves like an `int`." A concrete type is the simplest kind of class.
4343 A value of regular type can be copied and the result of a copy is an independent object with the same value as the original.
4344 If a concrete type has both `=` and `==`, `a = b` should result in `a == b` being `true`.
4345 Concrete classes without assignment and equality can be defined, but they are (and should be) rare.
4346 The C++ built-in types are regular, and so are standard-library classes, such as `string`, `vector`, and `map`.
4347 Concrete types are also often referred to as value types to distinguish them from types used as part of a hierarchy.
4349 Concrete type rule summary:
4351 * [C.10: Prefer concrete types over class hierarchies](#Rc-concrete)
4352 * [C.11: Make concrete types regular](#Rc-regular)
4354 ### <a name="Rc-concrete"></a>C.10: Prefer concrete types over class hierarchies
4356 ##### Reason
4358 A concrete type is fundamentally simpler than a hierarchy:
4359 easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster.
4360 You need a reason (use cases) for using a hierarchy.
4362 ##### Example
4364     class Point1 {
4365         int x, y;
4366         // ... operations ...
4367         // ... no virtual functions ...
4368     };
4370     class Point2 {
4371         int x, y;
4372         // ... operations, some virtual ...
4373         virtual ~Point2();
4374     };
4376     void use()
4377     {
4378         Point1 p11 {1, 2};   // make an object on the stack
4379         Point1 p12 {p11};    // a copy
4381         auto p21 = make_unique<Point2>(1, 2);   // make an object on the free store
4382         auto p22 = p21->clone();                // make a copy
4383         // ...
4384     }
4386 If a class can be part of a hierarchy, we (in real code if not necessarily in small examples) must manipulate its objects through pointers or references.
4387 That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections.
4389 ##### Note
4391 Concrete types can be stack-allocated and be members of other classes.
4393 ##### Note
4395 The use of indirection is fundamental for run-time polymorphic interfaces.
4396 The allocation/deallocation overhead is not (that's just the most common case).
4397 We can use a base class as the interface of a scoped object of a derived class.
4398 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.
4401 ##### Enforcement
4405 ### <a name="Rc-regular"></a>C.11: Make concrete types regular
4407 ##### Reason
4409 Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).
4411 ##### Example
4413     struct Bundle {
4414         string name;
4415         vector<Record> vr;
4416     };
4418     bool operator==(const Bundle& a, const Bundle& b)
4419     {
4420         return a.name == b.name && a.vr == b.vr;
4421     }
4423     Bundle b1 { "my bundle", {r1, r2, r3}};
4424     Bundle b2 = b1;
4425     if (!(b1 == b2)) error("impossible!");
4426     b2.name = "the other bundle";
4427     if (b1 == b2) error("No!");
4429 In particular, if a concrete type has an assignment also give it an equals operator so that `a = b` implies `a == b`.
4431 ##### Note
4433 Handles for resources that cannot be cloned, e.g., a `scoped_lock` for a `mutex`, resemble concrete types in that they most often are stack-allocated.
4434 However, objects of such types typically cannot be copied (instead, they can usually be moved),
4435 so they can't be `regular`; instead, they tend to be `semiregular`.
4436 Often, such types are referred to as "move-only types".
4438 ##### Enforcement
4442 ## <a name="S-ctor"></a>C.ctor: Constructors, assignments, and destructors
4444 These functions control the lifecycle of objects: creation, copy, move, and destruction.
4445 Define constructors to guarantee and simplify initialization of classes.
4447 These are *default operations*:
4449 * a default constructor: `X()`
4450 * a copy constructor: `X(const X&)`
4451 * a copy assignment: `operator=(const X&)`
4452 * a move constructor: `X(X&&)`
4453 * a move assignment: `operator=(X&&)`
4454 * a destructor: `~X()`
4456 By default, the compiler defines each of these operations if it is used, but the default can be suppressed.
4458 The default operations are a set of related operations that together implement the lifecycle semantics of an object.
4459 By default, C++ treats classes as value-like types, but not all types are value-like.
4461 Set of default operations rules:
4463 * [C.20: If you can avoid defining any default operations, do](#Rc-zero)
4464 * [C.21: If you define or `=delete` any default operation, define or `=delete` them all](#Rc-five)
4465 * [C.22: Make default operations consistent](#Rc-matched)
4467 Destructor rules:
4469 * [C.30: Define a destructor if a class needs an explicit action at object destruction](#Rc-dtor)
4470 * [C.31: All resources acquired by a class must be released by the class's destructor](#Rc-dtor-release)
4471 * [C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning](#Rc-dtor-ptr)
4472 * [C.33: If a class has an owning pointer member, define or `=delete` a destructor](#Rc-dtor-ptr2)
4473 * [C.35: A base class destructor should be either public and virtual, or protected and nonvirtual](#Rc-dtor-virtual)
4474 * [C.36: A destructor may not fail](#Rc-dtor-fail)
4475 * [C.37: Make destructors `noexcept`](#Rc-dtor-noexcept)
4477 Constructor rules:
4479 * [C.40: Define a constructor if a class has an invariant](#Rc-ctor)
4480 * [C.41: A constructor should create a fully initialized object](#Rc-complete)
4481 * [C.42: If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
4482 * [C.43: Ensure that a copyable (value type) class has a default constructor](#Rc-default0)
4483 * [C.44: Prefer default constructors to be simple and non-throwing](#Rc-default00)
4484 * [C.45: Don't define a default constructor that only initializes data members; use member initializers instead](#Rc-default)
4485 * [C.46: By default, declare single-argument constructors `explicit`](#Rc-explicit)
4486 * [C.47: Define and initialize member variables in the order of member declaration](#Rc-order)
4487 * [C.48: Prefer in-class initializers to member initializers in constructors for constant initializers](#Rc-in-class-initializer)
4488 * [C.49: Prefer initialization to assignment in constructors](#Rc-initialize)
4489 * [C.50: Use a factory function if you need "virtual behavior" during initialization](#Rc-factory)
4490 * [C.51: Use delegating constructors to represent common actions for all constructors of a class](#Rc-delegating)
4491 * [C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization](#Rc-inheriting)
4493 Copy and move rules:
4495 * [C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`](#Rc-copy-assignment)
4496 * [C.61: A copy operation should copy](#Rc-copy-semantic)
4497 * [C.62: Make copy assignment safe for self-assignment](#Rc-copy-self)
4498 * [C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const&`](#Rc-move-assignment)
4499 * [C.64: A move operation should move and leave its source in a valid state](#Rc-move-semantic)
4500 * [C.65: Make move assignment safe for self-assignment](#Rc-move-self)
4501 * [C.66: Make move operations `noexcept`](#Rc-move-noexcept)
4502 * [C.67: A polymorphic class should suppress copying](#Rc-copy-virtual)
4504 Other default operations rules:
4506 * [C.80: Use `=default` if you have to be explicit about using the default semantics](#Rc-eqdefault)
4507 * [C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)](#Rc-delete)
4508 * [C.82: Don't call virtual functions in constructors and destructors](#Rc-ctor-virtual)
4509 * [C.83: For value-like types, consider providing a `noexcept` swap function](#Rc-swap)
4510 * [C.84: A `swap` may not fail](#Rc-swap-fail)
4511 * [C.85: Make `swap` `noexcept`](#Rc-swap-noexcept)
4512 * [C.86: Make `==` symmetric with respect of operand types and `noexcept`](#Rc-eq)
4513 * [C.87: Beware of `==` on base classes](#Rc-eq-base)
4514 * [C.89: Make a `hash` `noexcept`](#Rc-hash)
4516 ## <a name="SS-defop"></a>C.defop: Default Operations
4518 By default, the language supplies the default operations with their default semantics.
4519 However, a programmer can disable or replace these defaults.
4521 ### <a name="Rc-zero"></a>C.20: If you can avoid defining default operations, do
4523 ##### Reason
4525 It's the simplest and gives the cleanest semantics.
4527 ##### Example
4529     struct Named_map {
4530     public:
4531         // ... no default operations declared ...
4532     private:
4533         string name;
4534         map<int, int> rep;
4535     };
4537     Named_map nm;        // default construct
4538     Named_map nm2 {nm};  // copy construct
4540 Since `std::map` and `string` have all the special functions, no further work is needed.
4542 ##### Note
4544 This is known as "the rule of zero".
4546 ##### Enforcement
4548 (Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule.
4549 For example, a class with a (pointer, size) pair of member and a destructor that `delete`s the pointer could probably be converted to a `vector`.
4551 ### <a name="Rc-five"></a>C.21: If you define or `=delete` any default operation, define or `=delete` them all
4553 ##### Reason
4555 The *special member functions* are the default constructor, copy constructor,
4556 copy assignment operator, move constructor, move assignment operator, and
4557 destructor.
4559 The semantics of the special functions are closely related, so if one needs to be declared, the odds are that others need consideration too.
4561 Declaring any special member function except a default constructor,
4562 even as `=default` or `=delete`, will suppress the implicit declaration
4563 of a move constructor and move assignment operator.
4564 Declaring a move constructor or move assignment operator, even as
4565 `=default` or `=delete`, will cause an implicitly generated copy constructor
4566 or implicitly generated copy assignment operator to be defined as deleted.
4567 So as soon as any of the special functions is declared, the others should
4568 all be declared to avoid unwanted effects like turning all potential moves
4569 into more expensive copies, or making a class move-only.
4571 ##### Example, bad
4573     struct M2 {   // bad: incomplete set of default operations
4574     public:
4575         // ...
4576         // ... no copy or move operations ...
4577         ~M2() { delete[] rep; }
4578     private:
4579         pair<int, int>* rep;  // zero-terminated set of pairs
4580     };
4582     void use()
4583     {
4584         M2 x;
4585         M2 y;
4586         // ...
4587         x = y;   // the default assignment
4588         // ...
4589     }
4591 Given that "special attention" was needed for the destructor (here, to deallocate), the likelihood that copy and move assignment (both will implicitly destroy an object) are correct is low (here, we would get double deletion).
4593 ##### Note
4595 This is known as "the rule of five" or "the rule of six", depending on whether you count the default constructor.
4597 ##### Note
4599 If you want a default implementation of a default operation (while defining another), write `=default` to show you're doing so intentionally for that function.
4600 If you don't want a default operation, suppress it with `=delete`.
4602 ##### Example, good
4604 When a destructor needs to be declared just to make it `virtual`, it can be
4605 defined as defaulted. To avoid suppressing the implicit move operations
4606 they must also be declared, and then to avoid the class becoming move-only
4607 (and not copyable) the copy operations must be declared:
4609     class AbstractBase {
4610     public:
4611       virtual ~AbstractBase() = default;
4612       AbstractBase(const AbstractBase&) = default;
4613       AbstractBase& operator=(const AbstractBase&) = default;
4614       AbstractBase(AbstractBase&&) = default;
4615       AbstractBase& operator=(AbstractBase&&) = default;
4616     };
4618 Alternatively to prevent slicing as per [C.67](#Rc-copy-virtual),
4619 the copy and move operations can all be deleted:
4621     class ClonableBase {
4622     public:
4623       virtual unique_ptr<ClonableBase> clone() const;
4624       virtual ~ClonableBase() = default;
4625       ClonableBase(const ClonableBase&) = delete;
4626       ClonableBase& operator=(const ClonableBase&) = delete;
4627       ClonableBase(ClonableBase&&) = delete;
4628       ClonableBase& operator=(ClonableBase&&) = delete;
4629     };
4631 Defining only the move operations or only the copy operations would have the
4632 same effect here, but stating the intent explicitly for each special member
4633 makes it more obvious to the reader.
4635 ##### Note
4637 Compilers enforce much of this rule and ideally warn about any violation.
4639 ##### Note
4641 Relying on an implicitly generated copy operation in a class with a destructor is deprecated.
4643 ##### Note
4645 Writing the six special member functions can be error prone.
4646 Note their argument types:
4648     class X {
4649     public:
4650         // ...
4651         virtual ~X() = default;            // destructor (virtual if X is meant to be a base class)
4652         X(const X&) = default;             // copy constructor
4653         X& operator=(const X&) = default;  // copy assignment
4654         X(X&&) = default;                  // move constructor
4655         X& operator=(X&&) = default;       // move assignment
4656     };
4658 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.
4659 To avoid the tedium and the possibility of errors, try to follow the [rule of zero](#Rc-zero).
4661 ##### Enforcement
4663 (Simple) A class should have a declaration (even a `=delete` one) for either all or none of the special functions.
4665 ### <a name="Rc-matched"></a>C.22: Make default operations consistent
4667 ##### Reason
4669 The default operations are conceptually a matched set. Their semantics are interrelated.
4670 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.
4672 ##### Example, bad
4674     class Silly {   // BAD: Inconsistent copy operations
4675         class Impl {
4676             // ...
4677         };
4678         shared_ptr<Impl> p;
4679     public:
4680         Silly(const Silly& a) : p{a.p} { *p = *a.p; }   // deep copy
4681         Silly& operator=(const Silly& a) { p = a.p; }   // shallow copy
4682         // ...
4683     };
4685 These operations disagree about copy semantics. This will lead to confusion and bugs.
4687 ##### Enforcement
4689 * (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.
4690 * (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors.
4691 * (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable.
4692 * (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators.
4694 ## <a name="SS-dtor"></a>C.dtor: Destructors
4696 "Does this class need a destructor?" is a surprisingly powerful design question.
4697 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);
4698 that is, its members can take care of themselves as concerns destruction.
4699 If the answer is "yes", much of the design of the class follows (see [the rule of five](#Rc-five)).
4701 ### <a name="Rc-dtor"></a>C.30: Define a destructor if a class needs an explicit action at object destruction
4703 ##### Reason
4705 A destructor is implicitly invoked at the end of an object's lifetime.
4706 If the default destructor is sufficient, use it.
4707 Only define a non-default destructor if a class needs to execute code that is not already part of its members' destructors.
4709 ##### Example
4711     template<typename A>
4712     struct final_action {   // slightly simplified
4713         A act;
4714         final_action(A a) :act{a} {}
4715         ~final_action() { act(); }
4716     };
4718     template<typename A>
4719     final_action<A> finally(A act)   // deduce action type
4720     {
4721         return final_action<A>{act};
4722     }
4724     void test()
4725     {
4726         auto act = finally([]{ cout << "Exit test\n"; });  // establish exit action
4727         // ...
4728         if (something) return;   // act done here
4729         // ...
4730     } // act done here
4732 The whole purpose of `final_action` is to get a piece of code (usually a lambda) executed upon destruction.
4734 ##### Note
4736 There are two general categories of classes that need a user-defined destructor:
4738 * A class with a resource that is not already represented as a class with a destructor, e.g., a `vector` or a transaction class.
4739 * A class that exists primarily to execute an action upon destruction, such as a tracer or `final_action`.
4741 ##### Example, bad
4743     class Foo {   // bad; use the default destructor
4744     public:
4745         // ...
4746         ~Foo() { s = ""; i = 0; vi.clear(); }  // clean up
4747     private:
4748         string s;
4749         int i;
4750         vector<int> vi;
4751     };
4753 The default destructor does it better, more efficiently, and can't get it wrong.
4755 ##### Note
4757 If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use `=default`.
4759 ##### Enforcement
4761 Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors.
4763 ### <a name="Rc-dtor-release"></a>C.31: All resources acquired by a class must be released by the class's destructor
4765 ##### Reason
4767 Prevention of resource leaks, especially in error cases.
4769 ##### Note
4771 For resources represented as classes with a complete set of default operations, this happens automatically.
4773 ##### Example
4775     class X {
4776         ifstream f;   // may own a file
4777         // ... no default operations defined or =deleted ...
4778     };
4780 `X`'s `ifstream` implicitly closes any file it may have open upon destruction of its `X`.
4782 ##### Example, bad
4784     class X2 {     // bad
4785         FILE* f;   // may own a file
4786         // ... no default operations defined or =deleted ...
4787     };
4789 `X2` may leak a file handle.
4791 ##### Note
4793 What about a sockets that won't close? A destructor, close, or cleanup operation [should never fail](#Rc-dtor-fail).
4794 If it does nevertheless, we have a problem that has no really good solution.
4795 For starters, the writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
4796 See [discussion](#Sd-never-fail).
4797 To make the problem worse, many "close/release" operations are not retryable.
4798 Many have tried to solve this problem, but no general solution is known.
4799 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
4801 ##### Note
4803 A class can hold pointers and references to objects that it does not own.
4804 Obviously, such objects should not be `delete`d by the class's destructor.
4805 For example:
4807     Preprocessor pp { /* ... */ };
4808     Parser p { pp, /* ... */ };
4809     Type_checker tc { p, /* ... */ };
4811 Here `p` refers to `pp` but does not own it.
4813 ##### Enforcement
4815 * (Simple) If a class has pointer or reference member variables that are owners
4816   (e.g., deemed owners by using `gsl::owner`), then they should be referenced in its destructor.
4817 * (Hard) Determine if pointer or reference member variables are owners when there is no explicit statement of ownership
4818   (e.g., look into the constructors).
4820 ### <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
4822 ##### Reason
4824 There is a lot of code that is non-specific about ownership.
4826 ##### Example
4828     ???
4830 ##### Note
4832 If the `T*` or `T&` is owning, mark it `owning`. If the `T*` is not owning, consider marking it `ptr`.
4833 This will aid documentation and analysis.
4835 ##### Enforcement
4837 Look at the initialization of raw member pointers and member references and see if an allocation is used.
4839 ### <a name="Rc-dtor-ptr2"></a>C.33: If a class has an owning pointer member, define a destructor
4841 ##### Reason
4843 An owned object must be `deleted` upon destruction of the object that owns it.
4845 ##### Example
4847 A pointer member may represent a resource.
4848 [A `T*` should not do so](#Rr-ptr), but in older code, that's common.
4849 Consider a `T*` a possible owner and therefore suspect.
4851     template<typename T>
4852     class Smart_ptr {
4853         T* p;   // BAD: vague about ownership of *p
4854         // ...
4855     public:
4856         // ... no user-defined default operations ...
4857     };
4859     void use(Smart_ptr<int> p1)
4860     {
4861         // error: p2.p leaked (if not nullptr and not owned by some other code)
4862         auto p2 = p1;
4863     }
4865 Note that if you define a destructor, you must define or delete [all default operations](#Rc-five):
4867     template<typename T>
4868     class Smart_ptr2 {
4869         T* p;   // BAD: vague about ownership of *p
4870         // ...
4871     public:
4872         // ... no user-defined copy operations ...
4873         ~Smart_ptr2() { delete p; }  // p is an owner!
4874     };
4876     void use(Smart_ptr2<int> p1)
4877     {
4878         auto p2 = p1;   // error: double deletion
4879     }
4881 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:
4883     template<typename T>
4884     class Smart_ptr3 {
4885         owner<T*> p;   // OK: explicit about ownership of *p
4886         // ...
4887     public:
4888         // ...
4889         // ... copy and move operations ...
4890         ~Smart_ptr3() { delete p; }
4891     };
4893     void use(Smart_ptr3<int> p1)
4894     {
4895         auto p2 = p1;   // OK: no double deletion
4896     }
4898 ##### Note
4900 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.
4902 ##### Note
4904 Why not just require all owning pointers to be "smart pointers"?
4905 That would sometimes require non-trivial code changes and may affect ABIs.
4907 ##### Enforcement
4909 * A class with a pointer data member is suspect.
4910 * A class with an `owner<T>` should define its default operations.
4913 ### <a name="Rc-dtor-virtual"></a>C.35: A base class destructor should be either public and virtual, or protected and nonvirtual
4915 ##### Reason
4917 To prevent undefined behavior.
4918 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.
4919 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.
4920 In general, the writer of a base class does not know the appropriate action to be done upon destruction.
4922 ##### Discussion
4924 See [this in the Discussion section](#Sd-dtor).
4926 ##### Example, bad
4928     struct Base {  // BAD: implicitly has a public nonvirtual destructor
4929         virtual void f();
4930     };
4932     struct D : Base {
4933         string s {"a resource needing cleanup"};
4934         ~D() { /* ... do some cleanup ... */ }
4935         // ...
4936     };
4938     void use()
4939     {
4940         unique_ptr<Base> p = make_unique<D>();
4941         // ...
4942     } // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more
4944 ##### Note
4946 A virtual function defines an interface to derived classes that can be used without looking at the derived classes.
4947 If the interface allows destroying, it should be safe to do so.
4949 ##### Note
4951 A destructor must be nonprivate or it will prevent using the type:
4953     class X {
4954         ~X();   // private destructor
4955         // ...
4956     };
4958     void use()
4959     {
4960         X a;                        // error: cannot destroy
4961         auto p = make_unique<X>();  // error: cannot destroy
4962     }
4964 ##### Exception
4966 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.
4969 ##### Enforcement
4971 * A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.
4973 ### <a name="Rc-dtor-fail"></a>C.36: A destructor may not fail
4975 ##### Reason
4977 In general we do not know how to write error-free code if a destructor should fail.
4978 The standard library requires that all classes it deals with have destructors that do not exit by throwing.
4980 ##### Example
4982     class X {
4983     public:
4984         ~X() noexcept;
4985         // ...
4986     };
4988     X::~X() noexcept
4989     {
4990         // ...
4991         if (cannot_release_a_resource) terminate();
4992         // ...
4993     }
4995 ##### Note
4997 Many have tried to devise a fool-proof scheme for dealing with failure in destructors.
4998 None have succeeded to come up with a general scheme.
4999 This can be a real practical problem: For example, what about a socket that won't close?
5000 The writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
5001 See [discussion](#Sd-dtor).
5002 To make the problem worse, many "close/release" operations are not retryable.
5003 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
5005 ##### Note
5007 Declare a destructor `noexcept`. That will ensure that it either completes normally or terminate the program.
5009 ##### Note
5011 If a resource cannot be released and the program may not fail, try to signal the failure to the rest of the system somehow
5012 (maybe even by modifying some global state and hope something will notice and be able to take care of the problem).
5013 Be fully aware that this technique is special-purpose and error-prone.
5014 Consider the "my connection will not close" example.
5015 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.
5016 The destructor could send a message (somehow) to the responsible part of the system, consider that to have closed the connection, and return normally.
5018 ##### Note
5020 If a destructor uses operations that may fail, it can catch exceptions and in some cases still complete successfully
5021 (e.g., by using a different clean-up mechanism from the one that threw an exception).
5023 ##### Enforcement
5025 (Simple) A destructor should be declared `noexcept` if it could throw.
5027 ### <a name="Rc-dtor-noexcept"></a>C.37: Make destructors `noexcept`
5029 ##### Reason
5031  [A destructor may 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.
5033 ##### Note
5035 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.
5037 ##### Example
5039 Not all destructors are noexcept by default; one throwing member poisons the whole class hierarchy
5041     struct X {
5042         Details x;  // happens to have a throwing destructor
5043         // ...
5044         ~X() { }    // implicitly noexcept(false); aka can throw
5045     };
5047 So, if in doubt, declare a destructor noexcept.
5049 ##### Note
5051 Why not then declare all destructors noexcept?
5052 Because that would in many cases -- especially simple cases -- be distracting clutter.
5054 ##### Enforcement
5056 (Simple) A destructor should be declared `noexcept` if it could throw.
5058 ## <a name="SS-ctor"></a>C.ctor: Constructors
5060 A constructor defines how an object is initialized (constructed).
5062 ### <a name="Rc-ctor"></a>C.40: Define a constructor if a class has an invariant
5064 ##### Reason
5066 That's what constructors are for.
5068 ##### Example
5070     class Date {  // a Date represents a valid date
5071                   // in the January 1, 1900 to December 31, 2100 range
5072         Date(int dd, int mm, int yy)
5073             :d{dd}, m{mm}, y{yy}
5074         {
5075             if (!is_valid(d, m, y)) throw Bad_date{};  // enforce invariant
5076         }
5077         // ...
5078     private:
5079         int d, m, y;
5080     };
5082 It is often a good idea to express the invariant as an `Ensures` on the constructor.
5084 ##### Note
5086 A constructor can be used for convenience even if a class does not have an invariant. For example:
5088     struct Rec {
5089         string s;
5090         int i {0};
5091         Rec(const string& ss) : s{ss} {}
5092         Rec(int ii) :i{ii} {}
5093     };
5095     Rec r1 {7};
5096     Rec r2 {"Foo bar"};
5098 ##### Note
5100 The C++11 initializer list rule eliminates the need for many constructors. For example:
5102     struct Rec2{
5103         string s;
5104         int i;
5105         Rec2(const string& ss, int ii = 0) :s{ss}, i{ii} {}   // redundant
5106     };
5108     Rec2 r1 {"Foo", 7};
5109     Rec2 r2 {"Bar"};
5111 The `Rec2` constructor is redundant.
5112 Also, the default for `int` would be better done as a [member initializer](#Rc-in-class-initializer).
5114 **See also**: [construct valid object](#Rc-complete) and [constructor throws](#Rc-throw).
5116 ##### Enforcement
5118 * Flag classes with user-defined copy operations but no constructor (a user-defined copy is a good indicator that the class has an invariant)
5120 ### <a name="Rc-complete"></a>C.41: A constructor should create a fully initialized object
5122 ##### Reason
5124 A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
5126 ##### Example, bad
5128     class X1 {
5129         FILE* f;   // call init() before any other function
5130         // ...
5131     public:
5132         X1() {}
5133         void init();   // initialize f
5134         void read();   // read from f
5135         // ...
5136     };
5138     void f()
5139     {
5140         X1 file;
5141         file.read();   // crash or bad read!
5142         // ...
5143         file.init();   // too late
5144         // ...
5145     }
5147 Compilers do not read comments.
5149 ##### Exception
5151 If a valid object cannot conveniently be constructed by a constructor, [use a factory function](#Rc-factory).
5153 ##### Enforcement
5155 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
5156 * (Unknown) If a constructor has an `Ensures` contract, try to see if it holds as a postcondition.
5158 ##### Note
5160 If a constructor acquires a resource (to create a valid object), that resource should be [released by the destructor](#Rc-dtor-release).
5161 The idiom of having constructors acquire resources and destructors release them is called [RAII](#Rr-raii) ("Resource Acquisition Is Initialization").
5163 ### <a name="Rc-throw"></a>C.42: If a constructor cannot construct a valid object, throw an exception
5165 ##### Reason
5167 Leaving behind an invalid object is asking for trouble.
5169 ##### Example
5171     class X2 {
5172         FILE* f;
5173         // ...
5174     public:
5175         X2(const string& name)
5176             :f{fopen(name.c_str(), "r")}
5177         {
5178             if (!f) throw runtime_error{"could not open" + name};
5179             // ...
5180         }
5182         void read();      // read from f
5183         // ...
5184     };
5186     void f()
5187     {
5188         X2 file {"Zeno"}; // throws if file isn't open
5189         file.read();      // fine
5190         // ...
5191     }
5193 ##### Example, bad
5195     class X3 {     // bad: the constructor leaves a non-valid object behind
5196         FILE* f;   // call is_valid() before any other function
5197         bool valid;
5198         // ...
5199     public:
5200         X3(const string& name)
5201             :f{fopen(name.c_str(), "r")}, valid{false}
5202         {
5203             if (f) valid = true;
5204             // ...
5205         }
5207         bool is_valid() { return valid; }
5208         void read();   // read from f
5209         // ...
5210     };
5212     void f()
5213     {
5214         X3 file {"Heraclides"};
5215         file.read();   // crash or bad read!
5216         // ...
5217         if (file.is_valid()) {
5218             file.read();
5219             // ...
5220         }
5221         else {
5222             // ... handle error ...
5223         }
5224         // ...
5225     }
5227 ##### Note
5229 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.
5230 Leaving behind an invalid object and relying on users to consistently check an `is_valid()` function before use is tedious, error-prone, and inefficient.
5232 ##### Exception
5234 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.
5235 There the `is_valid()` technique must be used. In such cases, check `is_valid()` consistently and immediately to simulate [RAII](#Rr-raii).
5237 ##### Alternative
5239 If you feel tempted to use some "post-constructor initialization" or "two-stage initialization" idiom, try not to do that.
5240 If you really have to, look at [factory functions](#Rc-factory).
5242 ##### Note
5244 One reason people have used `init()` functions rather than doing the initialization work in a constructor has been to avoid code replication.
5245 [Delegating constructors](#Rc-delegating) and [default member initialization](#Rc-in-class-initializer) do that better.
5246 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)
5248 ##### Enforcement
5252 ### <a name="Rc-default0"></a>C.43: Ensure that a copyable (value type) class has a default constructor
5254 ##### Reason
5256 Many language and library facilities rely on default constructors to initialize their elements, e.g. `T a[10]` and `std::vector<T> v(10)`.
5257 A default constructor often simplifies the task of defining a suitable [moved-from state](#???) for a type that is also copyable.
5259 ##### Note
5261 A [value type](#SS-concrete) is a class that is copyable (and usually also comparable).
5262 It is closely related to the notion of Regular type from [EoP](http://elementsofprogramming.com/) and [the Palo Alto TR](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3351.pdf).
5264 ##### Example
5266     class Date { // BAD: no default constructor
5267     public:
5268         Date(int dd, int mm, int yyyy);
5269         // ...
5270     };
5272     vector<Date> vd1(1000);   // default Date needed here
5273     vector<Date> vd2(1000, Date{Month::October, 7, 1885});   // alternative
5275 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.
5276 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.
5278 `Date` is chosen to encourage thought:
5279 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.
5280 `{0, 0, 0}` is not a valid date in most calendar systems, so choosing that would be introducing something like floating-point's `NaN`.
5281 However, most realistic `Date` classes have a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial.
5283     class Date {
5284     public:
5285         Date(int dd, int mm, int yyyy);
5286         Date() = default; // [See also](#Rc-default)
5287         // ...
5288     private:
5289         int dd = 1;
5290         int mm = 1;
5291         int yyyy = 1970;
5292         // ...
5293     };
5295     vector<Date> vd1(1000);
5297 ##### Note
5299 A class with members that all have default constructors implicitly gets a default constructor:
5301     struct X {
5302         string s;
5303         vector<int> v;
5304     };
5306     X x; // means X{{}, {}}; that is the empty string and the empty vector
5308 Beware that built-in types are not properly default constructed:
5310     struct X {
5311         string s;
5312         int i;
5313     };
5315     void f()
5316     {
5317         X x;    // x.s is initialized to the empty string; x.i is uninitialized
5319         cout << x.s << ' ' << x.i << '\n';
5320         ++x.i;
5321     }
5323 Statically allocated objects of built-in types are by default initialized to `0`, but local built-in variables are not.
5324 Beware that your compiler may default initialize local built-in variables, whereas an optimized build will not.
5325 Thus, code like the example above may appear to work, but it relies on undefined behavior.
5326 Assuming that you want initialization, an explicit default initialization can help:
5328     struct X {
5329         string s;
5330         int i {};   // default initialize (to 0)
5331     };
5333 ##### Notes
5335 Classes that don't have a reasonable default construction are usually not copyable either, so they don't fall under this guideline.
5337 For example, a base class is not a value type (base classes should not be copyable) and so does not necessarily need a default constructor:
5339     // Shape is an abstract base class, not a copyable value type.
5340     // It may or may not need a default constructor.
5341     struct Shape {
5342         virtual void draw() = 0;
5343         virtual void rotate(int) = 0;
5344         // =delete copy/move functions
5345         // ...
5346     };
5348 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:
5350     // std::lock_guard is not a copyable value type.
5351     // It does not have a default constructor.
5352     lock_guard g {mx};  // guard the mutex mx
5353     lock_guard g2;      // error: guarding nothing
5355 A class that has a "special state" that must be handled separately from other states by member functions or users causes extra work
5356 (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:
5358     // std::ofstream is not a copyable value type.
5359     // It does happen to have a default constructor
5360     // that goes along with a special "not open" state.
5361     ofstream out {"Foobar"};
5362     // ...
5363     out << log(time, transaction);
5365 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.
5367 However, it is preferable to have a default constructor default to a meaningful state such as `std::string`s `""` and `std::vector`s `{}`.
5369 ##### Enforcement
5371 * Flag classes that are copyable by `=` without a default constructor
5372 * Flag classes that are comparable with `==` but not copyable
5375 ### <a name="Rc-default00"></a>C.44: Prefer default constructors to be simple and non-throwing
5377 ##### Reason
5379 Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.
5381 ##### Example, problematic
5383     template<typename T>
5384     // elem points to space-elem element allocated using new
5385     class Vector0 {
5386     public:
5387         Vector0() :Vector0{0} {}
5388         Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
5389         // ...
5390     private:
5391         own<T*> elem;
5392         T* space;
5393         T* last;
5394     };
5396 This is nice and general, but setting a `Vector0` to empty after an error involves an allocation, which may fail.
5397 Also, having a default `Vector` represented as `{new T[0], 0, 0}` seems wasteful.
5398 For example, `Vector0<int> v[100]` costs 100 allocations.
5400 ##### Example
5402     template<typename T>
5403     // elem is nullptr or elem points to space-elem element allocated using new
5404     class Vector1 {
5405     public:
5406         // sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
5407         Vector1() noexcept {}
5408         Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
5409         // ...
5410     private:
5411         own<T*> elem = nullptr;
5412         T* space = nullptr;
5413         T* last = nullptr;
5414     };
5416 Using `{nullptr, nullptr, nullptr}` makes `Vector1{}` cheap, but a special case and implies run-time checks.
5417 Setting a `Vector1` to empty after detecting an error is trivial.
5419 ##### Enforcement
5421 * Flag throwing default constructors
5423 ### <a name="Rc-default"></a>C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead
5425 ##### Reason
5427 Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
5429 ##### Example, bad
5431     class X1 { // BAD: doesn't use member initializers
5432         string s;
5433         int i;
5434     public:
5435         X1() :s{"default"}, i{1} { }
5436         // ...
5437     };
5439 ##### Example
5441     class X2 {
5442         string s = "default";
5443         int i = 1;
5444     public:
5445         // use compiler-generated default constructor
5446         // ...
5447     };
5449 ##### Enforcement
5451 (Simple) A default constructor should do more than just initialize member variables with constants.
5453 ### <a name="Rc-explicit"></a>C.46: By default, declare single-argument constructors explicit
5455 ##### Reason
5457 To avoid unintended conversions.
5459 ##### Example, bad
5461     class String {
5462         // ...
5463     public:
5464         String(int);   // BAD
5465         // ...
5466     };
5468     String s = 10;   // surprise: string of size 10
5470 ##### Exception
5472 If you really want an implicit conversion from the constructor argument type to the class type, don't use `explicit`:
5474     class Complex {
5475         // ...
5476     public:
5477         Complex(double d);   // OK: we want a conversion from d to {d, 0}
5478         // ...
5479     };
5481     Complex z = 10.7;   // unsurprising conversion
5483 **See also**: [Discussion of implicit conversions](#Ro-conversion)
5485 ##### Note
5487 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.
5489 ##### Enforcement
5491 (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".
5493 ### <a name="Rc-order"></a>C.47: Define and initialize member variables in the order of member declaration
5495 ##### Reason
5497 To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).
5499 ##### Example, bad
5501     class Foo {
5502         int m1;
5503         int m2;
5504     public:
5505         Foo(int x) :m2{x}, m1{++x} { }   // BAD: misleading initializer order
5506         // ...
5507     };
5509     Foo x(1); // surprise: x.m1 == x.m2 == 2
5511 ##### Enforcement
5513 (Simple) A member initializer list should mention the members in the same order they are declared.
5515 **See also**: [Discussion](#Sd-order)
5517 ### <a name="Rc-in-class-initializer"></a>C.48: Prefer in-class initializers to member initializers in constructors for constant initializers
5519 ##### Reason
5521 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.
5523 ##### Example, bad
5525     class X {   // BAD
5526         int i;
5527         string s;
5528         int j;
5529     public:
5530         X() :i{666}, s{"qqq"} { }   // j is uninitialized
5531         X(int ii) :i{ii} {}         // s is "" and j is uninitialized
5532         // ...
5533     };
5535 How would a maintainer know whether `j` was deliberately uninitialized (probably a poor 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.
5537 ##### Example
5539     class X2 {
5540         int i {666};
5541         string s {"qqq"};
5542         int j {0};
5543     public:
5544         X2() = default;        // all members are initialized to their defaults
5545         X2(int ii) :i{ii} {}   // s and j initialized to their defaults
5546         // ...
5547     };
5549 **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:
5551     class X3 {   // BAD: inexplicit, argument passing overhead
5552         int i;
5553         string s;
5554         int j;
5555     public:
5556         X3(int ii = 666, const string& ss = "qqq", int jj = 0)
5557             :i{ii}, s{ss}, j{jj} { }   // all members are initialized to their defaults
5558         // ...
5559     };
5561 ##### Enforcement
5563 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
5564 * (Simple) Default arguments to constructors suggest an in-class initializer may be more appropriate.
5566 ### <a name="Rc-initialize"></a>C.49: Prefer initialization to assignment in constructors
5568 ##### Reason
5570 An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.
5572 ##### Example, good
5574     class A {   // Good
5575         string s1;
5576     public:
5577         A(czstring p) : s1{p} { }    // GOOD: directly construct (and the C-string is explicitly named)
5578         // ...
5579     };
5581 ##### Example, bad
5583     class B {   // BAD
5584         string s1;
5585     public:
5586         B(const char* p) { s1 = p; }   // BAD: default constructor followed by assignment
5587         // ...
5588     };
5590     class C {   // UGLY, aka very bad
5591         int* p;
5592     public:
5593         C() { cout << *p; p = new int{10}; }   // accidental use before initialized
5594         // ...
5595     };
5597 ##### Example, better still
5599 Instead of those `const char*`s we could use `gsl::string_span` or (in C++17) `std::string_view`
5600 as [a more general way to present arguments to a function](#Rstr-view):
5602     class D {   // Good
5603         string s1;
5604     public:
5605         A(string_view v) : s1{v} { }    // GOOD: directly construct
5606         // ...
5607     };
5609 ### <a name="Rc-factory"></a>C.50: Use a factory function if you need "virtual behavior" during initialization
5611 ##### Reason
5613 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.
5615 ##### Note
5617 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.
5619 ##### Example, bad
5621     class B {
5622     public:
5623         B()
5624         {
5625             // ...
5626             f();   // BAD: virtual call in constructor
5627             // ...
5628         }
5630         virtual void f() = 0;
5632         // ...
5633     };
5635 ##### Example
5637     class B {
5638     protected:
5639         B() { /* ... */ }              // create an imperfectly initialized object
5641         virtual void PostInitialize()  // to be called right after construction
5642         {
5643             // ...
5644             f();    // GOOD: virtual dispatch is safe
5645             // ...
5646         }
5648     public:
5649         virtual void f() = 0;
5651         template<class T>
5652         static shared_ptr<T> Create()  // interface for creating shared objects
5653         {
5654             auto p = make_shared<T>();
5655             p->PostInitialize();
5656             return p;
5657         }
5658     };
5660     class D : public B { /* ... */ };  // some derived class
5662     shared_ptr<D> p = D::Create<D>();  // creating a D object
5664 By making the constructor `protected` we avoid an incompletely constructed object escaping into the wild.
5665 By providing the factory function `Create()`, we make construction (on the free store) convenient.
5667 ##### Note
5669 Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object.
5671 **See also**: [Discussion](#Sd-factory)
5673 ### <a name="Rc-delegating"></a>C.51: Use delegating constructors to represent common actions for all constructors of a class
5675 ##### Reason
5677 To avoid repetition and accidental differences.
5679 ##### Example, bad
5681     class Date {   // BAD: repetitive
5682         int d;
5683         Month m;
5684         int y;
5685     public:
5686         Date(int dd, Month mm, year yy)
5687             :d{dd}, m{mm}, y{yy}
5688             { if (!valid(d, m, y)) throw Bad_date{}; }
5690         Date(int dd, Month mm)
5691             :d{dd}, m{mm} y{current_year()}
5692             { if (!valid(d, m, y)) throw Bad_date{}; }
5693         // ...
5694     };
5696 The common action gets tedious to write and may accidentally not be common.
5698 ##### Example
5700     class Date2 {
5701         int d;
5702         Month m;
5703         int y;
5704     public:
5705         Date2(int dd, Month mm, year yy)
5706             :d{dd}, m{mm}, y{yy}
5707             { if (!valid(d, m, y)) throw Bad_date{}; }
5709         Date2(int dd, Month mm)
5710             :Date2{dd, mm, current_year()} {}
5711         // ...
5712     };
5714 **See also**: If the "repeated action" is a simple initialization, consider [an in-class member initializer](#Rc-in-class-initializer).
5716 ##### Enforcement
5718 (Moderate) Look for similar constructor bodies.
5720 ### <a name="Rc-inheriting"></a>C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization
5722 ##### Reason
5724 If you need those constructors for a derived class, re-implementing them is tedious and error-prone.
5726 ##### Example
5728 `std::vector` has a lot of tricky constructors, so if I want my own `vector`, I don't want to reimplement them:
5730     class Rec {
5731         // ... data and lots of nice constructors ...
5732     };
5734     class Oper : public Rec {
5735         using Rec::Rec;
5736         // ... no data members ...
5737         // ... lots of nice utility functions ...
5738     };
5740 ##### Example, bad
5742     struct Rec2 : public Rec {
5743         int x;
5744         using Rec::Rec;
5745     };
5747     Rec2 r {"foo", 7};
5748     int val = r.x;   // uninitialized
5750 ##### Enforcement
5752 Make sure that every member of the derived class is initialized.
5754 ## <a name="SS-copy"></a>C.copy: Copy and move
5756 Value types should generally be copyable, but interfaces in a class hierarchy should not.
5757 Resource handles may or may not be copyable.
5758 Types can be defined to move for logical as well as performance reasons.
5760 ### <a name="Rc-copy-assignment"></a>C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`
5762 ##### Reason
5764 It is simple and efficient. If you want to optimize for rvalues, provide an overload that takes a `&&` (see [F.18](#Rf-consume)).
5766 ##### Example
5768     class Foo {
5769     public:
5770         Foo& operator=(const Foo& x)
5771         {
5772             // GOOD: no need to check for self-assignment (other than performance)
5773             auto tmp = x;
5774             swap(tmp); // see C.83
5775             return *this;
5776         }
5777         // ...
5778     };
5780     Foo a;
5781     Foo b;
5782     Foo f();
5784     a = b;    // assign lvalue: copy
5785     a = f();  // assign rvalue: potentially move
5787 ##### Note
5789 The `swap` implementation technique offers the [strong guarantee](#Abrahams01).
5791 ##### Example
5793 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:
5795     template<typename T>
5796     class Vector {
5797     public:
5798         Vector& operator=(const Vector&);
5799         // ...
5800     private:
5801         T* elem;
5802         int sz;
5803     };
5805     Vector& Vector::operator=(const Vector& a)
5806     {
5807         if (a.sz > sz) {
5808             // ... use the swap technique, it can't be bettered ...
5809             return *this;
5810         }
5811         // ... copy sz elements from *a.elem to elem ...
5812         if (a.sz < sz) {
5813             // ... destroy the surplus elements in *this and adjust size ...
5814         }
5815         return *this;
5816     }
5818 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).
5820 **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&)`.
5821 See [copy constructor vs. `clone()`](#Rc-copy-virtual).
5823 ##### Enforcement
5825 * (Simple) An assignment operator should not be virtual. Here be dragons!
5826 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
5827 * (Moderate) An assignment operator should (implicitly or explicitly) invoke all base and member assignment operators.
5828   Look at the destructor to determine if the type has pointer semantics or value semantics.
5830 ### <a name="Rc-copy-semantic"></a>C.61: A copy operation should copy
5832 ##### Reason
5834 That is the generally assumed semantics. After `x = y`, we should have `x == y`.
5835 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).
5837 ##### Example
5839     class X {   // OK: value semantics
5840     public:
5841         X();
5842         X(const X&);     // copy X
5843         void modify();   // change the value of X
5844         // ...
5845         ~X() { delete[] p; }
5846     private:
5847         T* p;
5848         int sz;
5849     };
5851     bool operator==(const X& a, const X& b)
5852     {
5853         return a.sz == b.sz && equal(a.p, a.p + a.sz, b.p, b.p + b.sz);
5854     }
5856     X::X(const X& a)
5857         :p{new T[a.sz]}, sz{a.sz}
5858     {
5859         copy(a.p, a.p + sz, p);
5860     }
5862     X x;
5863     X y = x;
5864     if (x != y) throw Bad{};
5865     x.modify();
5866     if (x == y) throw Bad{};   // assume value semantics
5868 ##### Example
5870     class X2 {  // OK: pointer semantics
5871     public:
5872         X2();
5873         X2(const X2&) = default; // shallow copy
5874         ~X2() = default;
5875         void modify();          // change the pointed-to value
5876         // ...
5877     private:
5878         T* p;
5879         int sz;
5880     };
5882     bool operator==(const X2& a, const X2& b)
5883     {
5884         return a.sz == b.sz && a.p == b.p;
5885     }
5887     X2 x;
5888     X2 y = x;
5889     if (x != y) throw Bad{};
5890     x.modify();
5891     if (x != y) throw Bad{};  // assume pointer semantics
5893 ##### Note
5895 Prefer copy semantics unless you are building a "smart pointer". Value semantics is the simplest to reason about and what the standard-library facilities expect.
5897 ##### Enforcement
5899 (Not enforceable)
5901 ### <a name="Rc-copy-self"></a>C.62: Make copy assignment safe for self-assignment
5903 ##### Reason
5905 If `x = x` changes the value of `x`, people will be surprised and bad errors will occur (often including leaks).
5907 ##### Example
5909 The standard-library containers handle self-assignment elegantly and efficiently:
5911     std::vector<int> v = {3, 1, 4, 1, 5, 9};
5912     v = v;
5913     // the value of v is still {3, 1, 4, 1, 5, 9}
5915 ##### Note
5917 The default assignment generated from members that handle self-assignment correctly handles self-assignment.
5919     struct Bar {
5920         vector<pair<int, int>> v;
5921         map<string, int> m;
5922         string s;
5923     };
5925     Bar b;
5926     // ...
5927     b = b;   // correct and efficient
5929 ##### Note
5931 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)).
5933     class Foo {
5934         string s;
5935         int i;
5936     public:
5937         Foo& operator=(const Foo& a);
5938         // ...
5939     };
5941     Foo& Foo::operator=(const Foo& a)   // OK, but there is a cost
5942     {
5943         if (this == &a) return *this;
5944         s = a.s;
5945         i = a.i;
5946         return *this;
5947     }
5949 This is obviously safe and apparently efficient.
5950 However, what if we do one self-assignment per million assignments?
5951 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).
5952 Consider:
5954     Foo& Foo::operator=(const Foo& a)   // simpler, and probably much better
5955     {
5956         s = a.s;
5957         i = a.i;
5958         return *this;
5959     }
5961 `std::string` is safe for self-assignment and so are `int`. All the cost is carried by the (rare) case of self-assignment.
5963 ##### Enforcement
5965 (Simple) Assignment operators should not contain the pattern `if (this == &a) return *this;` ???
5967 ### <a name="Rc-move-assignment"></a>C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const &`
5969 ##### Reason
5971 It is simple and efficient.
5973 **See**: [The rule for copy-assignment](#Rc-copy-assignment).
5975 ##### Enforcement
5977 Equivalent to what is done for [copy-assignment](#Rc-copy-assignment).
5979 * (Simple) An assignment operator should not be virtual. Here be dragons!
5980 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
5981 * (Moderate) A move assignment operator should (implicitly or explicitly) invoke all base and member move assignment operators.
5983 ### <a name="Rc-move-semantic"></a>C.64: A move operation should move and leave its source in a valid state
5985 ##### Reason
5987 That is the generally assumed semantics.
5988 After `y = std::move(x)` the value of `y` should be the value `x` had and `x` should be in a valid state.
5990 ##### Example
5992     template<typename T>
5993     class X {   // OK: value semantics
5994     public:
5995         X();
5996         X(X&& a) noexcept;  // move X
5997         void modify();     // change the value of X
5998         // ...
5999         ~X() { delete[] p; }
6000     private:
6001         T* p;
6002         int sz;
6003     };
6006     X::X(X&& a)
6007         :p{a.p}, sz{a.sz}  // steal representation
6008     {
6009         a.p = nullptr;     // set to "empty"
6010         a.sz = 0;
6011     }
6013     void use()
6014     {
6015         X x{};
6016         // ...
6017         X y = std::move(x);
6018         x = X{};   // OK
6019     } // OK: x can be destroyed
6021 ##### Note
6023 Ideally, that moved-from should be the default value of the type.
6024 Ensure that unless there is an exceptionally good reason not to.
6025 However, not all types have a default value and for some types establishing the default value can be expensive.
6026 The standard requires only that the moved-from object can be destroyed.
6027 Often, we can easily and cheaply do better: The standard library assumes that it is possible to assign to a moved-from object.
6028 Always leave the moved-from object in some (necessarily specified) valid state.
6030 ##### Note
6032 Unless there is an exceptionally strong reason not to, make `x = std::move(y); y = z;` work with the conventional semantics.
6034 ##### Enforcement
6036 (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.
6038 ### <a name="Rc-move-self"></a>C.65: Make move assignment safe for self-assignment
6040 ##### Reason
6042 If `x = x` changes the value of `x`, people will be surprised and bad errors may 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.
6044 ##### Example
6046     class Foo {
6047         string s;
6048         int i;
6049     public:
6050         Foo& operator=(Foo&& a);
6051         // ...
6052     };
6054     Foo& Foo::operator=(Foo&& a) noexcept  // OK, but there is a cost
6055     {
6056         if (this == &a) return *this;  // this line is redundant
6057         s = std::move(a.s);
6058         i = a.i;
6059         return *this;
6060     }
6062 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.
6064 ##### Note
6066 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).
6068 ##### Note
6070 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.
6072 ##### Example
6074 Here is a way to move a pointer without a test (imagine it as code in the implementation a move assignment):
6076     // move from other.ptr to this->ptr
6077     T* temp = other.ptr;
6078     other.ptr = nullptr;
6079     delete ptr;
6080     ptr = temp;
6082 ##### Enforcement
6084 * (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`.
6085 * (Not enforceable) Look at the use of standard-library container types (incl. `string`) and consider them safe for ordinary (not life-critical) uses.
6087 ### <a name="Rc-move-noexcept"></a>C.66: Make move operations `noexcept`
6089 ##### Reason
6091 A throwing move violates most people's reasonably assumptions.
6092 A non-throwing move will be used more efficiently by standard-library and language facilities.
6094 ##### Example
6096     template<typename T>
6097     class Vector {
6098         // ...
6099         Vector(Vector&& a) noexcept :elem{a.elem}, sz{a.sz} { a.sz = 0; a.elem = nullptr; }
6100         Vector& operator=(Vector&& a) noexcept { elem = a.elem; sz = a.sz; a.sz = 0; a.elem = nullptr; }
6101         // ...
6102     public:
6103         T* elem;
6104         int sz;
6105     };
6107 These operations do not throw.
6109 ##### Example, bad
6111     template<typename T>
6112     class Vector2 {
6113         // ...
6114         Vector2(Vector2&& a) { *this = a; }             // just use the copy
6115         Vector2& operator=(Vector2&& a) { *this = a; }  // just use the copy
6116         // ...
6117     public:
6118         T* elem;
6119         int sz;
6120     };
6122 This `Vector2` is not just inefficient, but since a vector copy requires allocation, it can throw.
6124 ##### Enforcement
6126 (Simple) A move operation should be marked `noexcept`.
6128 ### <a name="Rc-copy-virtual"></a>C.67: A polymorphic class should suppress copying
6130 ##### Reason
6132 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.
6134 ##### Example, bad
6136     class B { // BAD: polymorphic base class doesn't suppress copying
6137     public:
6138         virtual char m() { return 'B'; }
6139         // ... nothing about copy operations, so uses default ...
6140     };
6142     class D : public B {
6143     public:
6144         char m() override { return 'D'; }
6145         // ...
6146     };
6148     void f(B& b) {
6149         auto b2 = b; // oops, slices the object; b2.m() will return 'B'
6150     }
6152     D d;
6153     f(d);
6155 ##### Example
6157     class B { // GOOD: polymorphic class suppresses copying
6158     public:
6159         B(const B&) = delete;
6160         B& operator=(const B&) = delete;
6161         virtual char m() { return 'B'; }
6162         // ...
6163     };
6165     class D : public B {
6166     public:
6167         char m() override { return 'D'; }
6168         // ...
6169     };
6171     void f(B& b) {
6172         auto b2 = b; // ok, compiler will detect inadvertent copying, and protest
6173     }
6175     D d;
6176     f(d);
6178 ##### Note
6180 If you need to create deep copies of polymorphic objects, use `clone()` functions: see [C.130](#Rh-copy).
6182 ##### Exception
6184 Classes that represent exception objects need both to be polymorphic and copy-constructible.
6186 ##### Enforcement
6188 * Flag a polymorphic class with a non-deleted copy operation.
6189 * Flag an assignment of polymorphic class objects.
6191 ## C.other: Other default operation rules
6193 In addition to the operations for which the language offer default implementations,
6194 there are a few operations that are so foundational that it rules for their definition are needed:
6195 comparisons, `swap`, and `hash`.
6197 ### <a name="Rc-eqdefault"></a>C.80: Use `=default` if you have to be explicit about using the default semantics
6199 ##### Reason
6201 The compiler is more likely to get the default semantics right and you cannot implement these functions better than the compiler.
6203 ##### Example
6205     class Tracer {
6206         string message;
6207     public:
6208         Tracer(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
6209         ~Tracer() { cerr << "exiting " << message << '\n'; }
6211         Tracer(const Tracer&) = default;
6212         Tracer& operator=(const Tracer&) = default;
6213         Tracer(Tracer&&) = default;
6214         Tracer& operator=(Tracer&&) = default;
6215     };
6217 Because we defined the destructor, we must define the copy and move operations. The `= default` is the best and simplest way of doing that.
6219 ##### Example, bad
6221     class Tracer2 {
6222         string message;
6223     public:
6224         Tracer2(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
6225         ~Tracer2() { cerr << "exiting " << message << '\n'; }
6227         Tracer2(const Tracer2& a) : message{a.message} {}
6228         Tracer2& operator=(const Tracer2& a) { message = a.message; return *this; }
6229         Tracer2(Tracer2&& a) :message{a.message} {}
6230         Tracer2& operator=(Tracer2&& a) { message = a.message; return *this; }
6231     };
6233 Writing out the bodies of the copy and move operations is verbose, tedious, and error-prone. A compiler does it better.
6235 ##### Enforcement
6237 (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
6239 ### <a name="Rc-delete"></a>C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)
6241 ##### Reason
6243 In a few cases, a default operation is not desirable.
6245 ##### Example
6247     class Immortal {
6248     public:
6249         ~Immortal() = delete;   // do not allow destruction
6250         // ...
6251     };
6253     void use()
6254     {
6255         Immortal ugh;   // error: ugh cannot be destroyed
6256         Immortal* p = new Immortal{};
6257         delete p;       // error: cannot destroy *p
6258     }
6260 ##### Example
6262 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:
6264     template <class T, class D = default_delete<T>> class unique_ptr {
6265     public:
6266         // ...
6267         constexpr unique_ptr() noexcept;
6268         explicit unique_ptr(pointer p) noexcept;
6269         // ...
6270         unique_ptr(unique_ptr&& u) noexcept;   // move constructor
6271         // ...
6272         unique_ptr(const unique_ptr&) = delete; // disable copy from lvalue
6273         // ...
6274     };
6276     unique_ptr<int> make();   // make "something" and return it by moving
6278     void f()
6279     {
6280         unique_ptr<int> pi {};
6281         auto pi2 {pi};      // error: no move constructor from lvalue
6282         auto pi3 {make()};  // OK, move: the result of make() is an rvalue
6283     }
6285 Note that deleted functions should be public.
6287 ##### Enforcement
6289 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.
6291 ### <a name="Rc-ctor-virtual"></a>C.82: Don't call virtual functions in constructors and destructors
6293 ##### Reason
6295 The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class.
6296 This can be most confusing.
6297 Worse, a direct or indirect call to an unimplemented pure virtual function from a constructor or destructor results in undefined behavior.
6299 ##### Example, bad
6301     class Base {
6302     public:
6303         virtual void f() = 0;   // not implemented
6304         virtual void g();       // implemented with Base version
6305         virtual void h();       // implemented with Base version
6306     };
6308     class Derived : public Base {
6309     public:
6310         void g() override;   // provide Derived implementation
6311         void h() final;      // provide Derived implementation
6313         Derived()
6314         {
6315             // BAD: attempt to call an unimplemented virtual function
6316             f();
6318             // BAD: will call Derived::g, not dispatch further virtually
6319             g();
6321             // GOOD: explicitly state intent to call only the visible version
6322             Derived::g();
6324             // ok, no qualification needed, h is final
6325             h();
6326         }
6327     };
6329 Note that calling a specific explicitly qualified function is not a virtual call even if the function is `virtual`.
6331 **See also** [factory functions](#Rc-factory) for how to achieve the effect of a call to a derived class function without risking undefined behavior.
6333 ##### Note
6335 There is nothing inherently wrong with calling virtual functions from constructors and destructors.
6336 The semantics of such calls is type safe.
6337 However, experience shows that such calls are rarely needed, easily confuse maintainers, and become a source of errors when used by novices.
6339 ##### Enforcement
6341 * Flag calls of virtual functions from constructors and destructors.
6343 ### <a name="Rc-swap"></a>C.83: For value-like types, consider providing a `noexcept` swap function
6345 ##### Reason
6347 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).
6349 ##### Example, good
6351     class Foo {
6352         // ...
6353     public:
6354         void swap(Foo& rhs) noexcept
6355         {
6356             m1.swap(rhs.m1);
6357             std::swap(m2, rhs.m2);
6358         }
6359     private:
6360         Bar m1;
6361         int m2;
6362     };
6364 Providing a nonmember `swap` function in the same namespace as your type for callers' convenience.
6366     void swap(Foo& a, Foo& b)
6367     {
6368         a.swap(b);
6369     }
6371 ##### Enforcement
6373 * (Simple) A class without virtual functions should have a `swap` member function declared.
6374 * (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6376 ### <a name="Rc-swap-fail"></a>C.84: A `swap` function may not fail
6378 ##### Reason
6380  `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.
6382 ##### Example, bad
6384     void swap(My_vector& x, My_vector& y)
6385     {
6386         auto tmp = x;   // copy elements
6387         x = y;
6388         y = tmp;
6389     }
6391 This is not just slow, but if a memory allocation occurs for the elements in `tmp`, this `swap` may throw and would make STL algorithms fail if used with them.
6393 ##### Enforcement
6395 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6397 ### <a name="Rc-swap-noexcept"></a>C.85: Make `swap` `noexcept`
6399 ##### Reason
6401  [A `swap` may not fail](#Rc-swap-fail).
6402 If a `swap` tries to exit with an exception, it's a bad design error and the program had better terminate.
6404 ##### Enforcement
6406 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6408 ### <a name="Rc-eq"></a>C.86: Make `==` symmetric with respect to operand types and `noexcept`
6410 ##### Reason
6412 Asymmetric treatment of operands is surprising and a source of errors where conversions are possible.
6413 `==` is a fundamental operations and programmers should be able to use it without fear of failure.
6415 ##### Example
6417     struct X {
6418         string name;
6419         int number;
6420     };
6422     bool operator==(const X& a, const X& b) noexcept {
6423         return a.name == b.name && a.number == b.number;
6424     }
6426 ##### Example, bad
6428     class B {
6429         string name;
6430         int number;
6431         bool operator==(const B& a) const {
6432             return name == a.name && number == a.number;
6433         }
6434         // ...
6435     };
6437 `B`'s comparison accepts conversions for its second operand, but not its first.
6439 ##### Note
6441 If a class has a failure state, like `double`'s `NaN`, there is a temptation to make a comparison against the failure state throw.
6442 The alternative is to make two failure states compare equal and any valid state compare false against the failure state.
6444 ##### Note
6446 This rule applies to all the usual comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6448 ##### Enforcement
6450 * Flag an `operator==()` for which the argument types differ; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6451 * Flag member `operator==()`s; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6453 ### <a name="Rc-eq-base"></a>C.87: Beware of `==` on base classes
6455 ##### Reason
6457 It is really hard to write a foolproof and useful `==` for a hierarchy.
6459 ##### Example, bad
6461     class B {
6462         string name;
6463         int number;
6464         virtual bool operator==(const B& a) const
6465         {
6466              return name == a.name && number == a.number;
6467         }
6468         // ...
6469     };
6471 `B`'s comparison accepts conversions for its second operand, but not its first.
6473     class D :B {
6474         char character;
6475         virtual bool operator==(const D& a) const
6476         {
6477             return name == a.name && number == a.number && character == a.character;
6478         }
6479         // ...
6480     };
6482     B b = ...
6483     D d = ...
6484     b == d;    // compares name and number, ignores d's character
6485     d == b;    // error: no == defined
6486     D d2;
6487     d == d2;   // compares name, number, and character
6488     B& b2 = d2;
6489     b2 == d;   // compares name and number, ignores d2's and d's character
6491 Of course there are ways of making `==` work in a hierarchy, but the naive approaches do not scale
6493 ##### Note
6495 This rule applies to all the usual comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6497 ##### Enforcement
6499 * Flag a virtual `operator==()`; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6501 ### <a name="Rc-hash"></a>C.89: Make a `hash` `noexcept`
6503 ##### Reason
6505 Users of hashed containers use hash indirectly and don't expect simple access to throw.
6506 It's a standard-library requirement.
6508 ##### Example, bad
6510     template<>
6511     struct hash<My_type> {  // thoroughly bad hash specialization
6512         using result_type = size_t;
6513         using argument_type = My_type;
6515         size_t operator() (const My_type & x) const
6516         {
6517             size_t xs = x.s.size();
6518             if (xs < 4) throw Bad_My_type{};    // "Nobody expects the Spanish inquisition!"
6519             return hash<size_t>()(x.s.size()) ^ trim(x.s);
6520         }
6521     };
6523     int main()
6524     {
6525         unordered_map<My_type, int> m;
6526         My_type mt{ "asdfg" };
6527         m[mt] = 7;
6528         cout << m[My_type{ "asdfg" }] << '\n';
6529     }
6531 If you have to define a `hash` specialization, try simply to let it combine standard-library `hash` specializations with `^` (xor).
6532 That tends to work better than "cleverness" for non-specialists.
6534 ##### Enforcement
6536 * Flag throwing `hash`es.
6538 ## <a name="SS-containers"></a>C.con: Containers and other resource handles
6540 A container is an object holding a sequence of objects of some type; `std::vector` is the archetypical container.
6541 A resource handle is a class that owns a resource; `std::vector` is the typical resource handle; its resource is its sequence of elements.
6543 Summary of container rules:
6545 * [C.100: Follow the STL when defining a container](#Rcon-stl)
6546 * [C.101: Give a container value semantics](#Rcon-val)
6547 * [C.102: Give a container move operations](#Rcon-move)
6548 * [C.103: Give a container an initializer list constructor](#Rcon-init)
6549 * [C.104: Give a container a default constructor that sets it to empty](#Rcon-empty)
6550 * ???
6551 * [C.109: If a resource handle has pointer semantics, provide `*` and `->`](#Rcon-ptr)
6553 **See also**: [Resources](#S-resource)
6556 ### <a name="Rcon-stl"></a>C.100: Follow the STL when defining a container
6558 ##### Reason
6560 The STL containers are familiar to most C++ programmers and a fundamentally sound design.
6562 ##### Note
6564 There are of course other fundamentally sound design styles and sometimes reasons to depart from
6565 the style of the standard library, but in the absence of a solid reason to differ, it is simpler
6566 and easier for both implementers and users to follow the standard.
6568 In particular, `std::vector` and `std::map` provide useful relatively simple models.
6570 ##### Example
6572     // simplified (e.g., no allocators):
6574     template<typename T>
6575     class Sorted_vector {
6576         using value_type = T;
6577         // ... iterator types ...
6579         Sorted_vector() = default;
6580         Sorted_vector(initializer_list<T>);    // initializer-list constructor: sort and store
6581         Sorted_vector(const Sorted_vector&) = default;
6582         Sorted_vector(Sorted_vector&&) = default;
6583         Sorted_vector& operator=(const Sorted_vector&) = default;   // copy assignment
6584         Sorted_vector& operator=(Sorted_vector&&) = default;        // move assignment
6585         ~Sorted_vector() = default;
6587         Sorted_vector(const std::vector<T>& v);   // store and sort
6588         Sorted_vector(std::vector<T>&& v);        // sort and "steal representation"
6590         const T& operator[](int i) const { return rep[i]; }
6591         // no non-const direct access to preserve order
6593         void push_back(const T&);   // insert in the right place (not necessarily at back)
6594         void push_back(T&&);        // insert in the right place (not necessarily at back)
6596         // ... cbegin(), cend() ...
6597     private:
6598         std::vector<T> rep;  // use a std::vector to hold elements
6599     };
6601     template<typename T> bool operator==(const Sorted_vector<T>&, const Sorted_vector<T>&);
6602     template<typename T> bool operator!=(const Sorted_vector<T>&, const Sorted_vector<T>&);
6603     // ...
6605 Here, the STL style is followed, but incompletely.
6606 That's not uncommon.
6607 Provide only as much functionality as makes sense for a specific container.
6608 The key is to define the conventional constructors, assignments, destructors, and iterators
6609 (as meaningful for the specific container) with their conventional semantics.
6610 From that base, the container can be expanded as needed.
6611 Here, special constructors from `std::vector` were added.
6613 ##### Enforcement
6617 ### <a name="Rcon-val"></a>C.101: Give a container value semantics
6619 ##### Reason
6621 Regular objects are simpler to think and reason about than irregular ones.
6622 Familiarity.
6624 ##### Note
6626 If meaningful, make a container `Regular` (the concept).
6627 In particular, ensure that an object compares equal to its copy.
6629 ##### Example
6631     void f(const Sorted_vector<string>& v)
6632     {
6633         Sorted_vector<string> v2 {v};
6634         if (v != v2)
6635             cout << "insanity rules!\n";
6636         // ...
6637     }
6639 ##### Enforcement
6643 ### <a name="Rcon-move"></a>C.102: Give a container move operations
6645 ##### Reason
6647 Containers tend to get large; without a move constructor and a copy constructor an object can be
6648 expensive to move around, thus tempting people to pass pointers to it around and getting into
6649 resource management problems.
6651 ##### Example
6653     Sorted_vector<int> read_sorted(istream& is)
6654     {
6655         vector<int> v;
6656         cin >> v;   // assume we have a read operation for vectors
6657         Sorted_vector<int> sv = v;  // sorts
6658         return sv;
6659     }
6661 A user can reasonably assume that returning a standard-like container is cheap.
6663 ##### Enforcement
6667 ### <a name="Rcon-init"></a>C.103: Give a container an initializer list constructor
6669 ##### Reason
6671 People expect to be able to initialize a container with a set of values.
6672 Familiarity.
6674 ##### Example
6676     Sorted_vector<int> sv {1, 3, -1, 7, 0, 0}; // Sorted_vector sorts elements as needed
6678 ##### Enforcement
6682 ### <a name="Rcon-empty"></a>C.104: Give a container a default constructor that sets it to empty
6684 ##### Reason
6686 To make it `Regular`.
6688 ##### Example
6690     vector<Sorted_sequence<string>> vs(100);    // 100 Sorted_sequences each with the value ""
6692 ##### Enforcement
6696 ### <a name="Rcon-ptr"></a>C.109: If a resource handle has pointer semantics, provide `*` and `->`
6698 ##### Reason
6700 That's what is expected from pointers.
6701 Familiarity.
6703 ##### Example
6705     ???
6707 ##### Enforcement
6711 ## <a name="SS-lambdas"></a>C.lambdas: Function objects and lambdas
6713 A function object is an object supplying an overloaded `()` so that you can call it.
6714 A lambda expression (colloquially often shortened to "a lambda") is a notation for generating a function object.
6715 Function objects should be cheap to copy (and therefore [passed by value](#Rf-in)).
6717 Summary:
6719 * [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)
6720 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
6721 * [F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread](#Rf-value-capture)
6722 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
6724 ## <a name="SS-hier"></a>C.hier: Class hierarchies (OOP)
6726 A class hierarchy is constructed to represent a set of hierarchically organized concepts (only).
6727 Typically base classes act as interfaces.
6728 There are two major uses for hierarchies, often named implementation inheritance and interface inheritance.
6730 Class hierarchy rule summary:
6732 * [C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)](#Rh-domain)
6733 * [C.121: If a base class is used as an interface, make it a pure abstract class](#Rh-abstract)
6734 * [C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed](#Rh-separation)
6736 Designing rules for classes in a hierarchy summary:
6738 * [C.126: An abstract class typically doesn't need a constructor](#Rh-abstract-ctor)
6739 * [C.127: A class with a virtual function should have a virtual or protected destructor](#Rh-dtor)
6740 * [C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final`](#Rh-override)
6741 * [C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance](#Rh-kind)
6742 * [C.130: For making deep copies of polymorphic classes prefer a virtual `clone` function instead of copy construction/assignment](#Rh-copy)
6743 * [C.131: Avoid trivial getters and setters](#Rh-get)
6744 * [C.132: Don't make a function `virtual` without reason](#Rh-virtual)
6745 * [C.133: Avoid `protected` data](#Rh-protected)
6746 * [C.134: Ensure all non-`const` data members have the same access level](#Rh-public)
6747 * [C.135: Use multiple inheritance to represent multiple distinct interfaces](#Rh-mi-interface)
6748 * [C.136: Use multiple inheritance to represent the union of implementation attributes](#Rh-mi-implementation)
6749 * [C.137: Use `virtual` bases to avoid overly general base classes](#Rh-vbase)
6750 * [C.138: Create an overload set for a derived class and its bases with `using`](#Rh-using)
6751 * [C.139: Use `final` sparingly](#Rh-final)
6752 * [C.140: Do not provide different default arguments for a virtual function and an overrider](#Rh-virtual-default-arg)
6754 Accessing objects in a hierarchy rule summary:
6756 * [C.145: Access polymorphic objects through pointers and references](#Rh-poly)
6757 * [C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable](#Rh-dynamic_cast)
6758 * [C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error](#Rh-ref-cast)
6759 * [C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative](#Rh-ptr-cast)
6760 * [C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`](#Rh-smart)
6761 * [C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s](#Rh-make_unique)
6762 * [C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s](#Rh-make_shared)
6763 * [C.152: Never assign a pointer to an array of derived class objects to a pointer to its base](#Rh-array)
6764 * [C.153: Prefer virtual function to casting](#Rh-use-virtual)
6766 ### <a name="Rh-domain"></a>C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)
6768 ##### Reason
6770 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.
6772 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.
6774 ##### Example
6776     class DrawableUIElement {
6777     public:
6778         virtual void render() const = 0;
6779         // ...
6780     };
6782     class AbstractButton : public DrawableUIElement {
6783     public:
6784         virtual void onClick() = 0;
6785         // ...
6786     };
6788     class PushButton : public AbstractButton {
6789         void render() const override;
6790         void onClick() override;
6791         // ...
6792     };
6794     class Checkbox : public AbstractButton {
6795     // ...
6796     };
6798 ##### Example, bad
6800 Do *not* represent non-hierarchical domain concepts as class hierarchies.
6802     template<typename T>
6803     class Container {
6804     public:
6805         // list operations:
6806         virtual T& get() = 0;
6807         virtual void put(T&) = 0;
6808         virtual void insert(Position) = 0;
6809         // ...
6810         // vector operations:
6811         virtual T& operator[](int) = 0;
6812         virtual void sort() = 0;
6813         // ...
6814         // tree operations:
6815         virtual void balance() = 0;
6816         // ...
6817     };
6819 Here most overriding classes cannot implement most of the functions required in the interface well.
6820 Thus the base class becomes an implementation burden.
6821 Furthermore, the user of `Container` cannot rely on the member functions actually performing meaningful operations reasonably efficiently;
6822 it may throw an exception instead.
6823 Thus users have to resort to run-time checking and/or
6824 not using this (over)general interface in favor of a particular interface found by a run-time type inquiry (e.g., a `dynamic_cast`).
6826 ##### Enforcement
6828 * Look for classes with lots of members that do nothing but throw.
6829 * Flag every use of a nonpublic 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`.
6831 ### <a name="Rh-abstract"></a>C.121: If a base class is used as an interface, make it a pure abstract class
6833 ##### Reason
6835 A class is more stable (less brittle) if it does not contain data.
6836 Interfaces should normally be composed entirely of public pure virtual functions and a default/empty virtual destructor.
6838 ##### Example
6840     class My_interface {
6841     public:
6842         // ...only pure virtual functions here ...
6843         virtual ~My_interface() {}   // or =default
6844     };
6846 ##### Example, bad
6848     class Goof {
6849     public:
6850         // ...only pure virtual functions here ...
6851         // no virtual destructor
6852     };
6854     class Derived : public Goof {
6855         string s;
6856         // ...
6857     };
6859     void use()
6860     {
6861         unique_ptr<Goof> p {new Derived{"here we go"}};
6862         f(p.get()); // use Derived through the Goof interface
6863         g(p.get()); // use Derived through the Goof interface
6864     } // leak
6866 The `Derived` is `delete`d through its `Goof` interface, so its `string` is leaked.
6867 Give `Goof` a virtual destructor and all is well.
6870 ##### Enforcement
6872 * Warn on any class that contains data members and also has an overridable (non-`final`) virtual function.
6874 ### <a name="Rh-separation"></a>C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed
6876 ##### Reason
6878 Such as on an ABI (link) boundary.
6880 ##### Example
6882     struct Device {
6883         virtual ~Device() = default;
6884         virtual void write(span<const char> outbuf) = 0;
6885         virtual void read(span<char> inbuf) = 0;
6886     };
6888     class D1 : public Device {
6889         // ... data ...
6891         void write(span<const char> outbuf) override;
6892         void read(span<char> inbuf) override;
6893     };
6895     class D2 : public Device {
6896         // ... different data ...
6898         void write(span<const char> outbuf) override;
6899         void read(span<char> inbuf) override;
6900     };
6902 A user can now use `D1`s and `D2`s interchangeably through the interface provided by `Device`.
6903 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`.
6905 ##### Enforcement
6907     ???
6909 ## C.hierclass: Designing classes in a hierarchy:
6911 ### <a name="Rh-abstract-ctor"></a>C.126: An abstract class typically doesn't need a constructor
6913 ##### Reason
6915 An abstract class typically does not have any data for a constructor to initialize.
6917 ##### Example
6919     ???
6921 ##### Exception
6923 * A base class constructor that does work, such as registering an object somewhere, may need a constructor.
6924 * In extremely rare cases, you might find it reasonable for an abstract class to have a bit of data shared by all derived classes
6925   (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.
6927 ##### Enforcement
6929 Flag abstract classes with constructors.
6931 ### <a name="Rh-dtor"></a>C.127: A class with a virtual function should have a virtual or protected destructor
6933 ##### Reason
6935 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 nonvirtual; see [C.35](#Rc-dtor-virtual).
6937 ##### Example, bad
6939     struct B {
6940         virtual int f() = 0;
6941         // ... no user-written destructor, defaults to public nonvirtual ...
6942     };
6944     // bad: derived from a class without a virtual destructor
6945     struct D : B {
6946         string s {"default"};
6947     };
6949     void use()
6950     {
6951         unique_ptr<B> p = make_unique<D>();
6952         // ...
6953     } // undefined behavior. May call B::~B only and leak the string
6955 ##### Note
6957 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`.
6959 ##### Enforcement
6961 * A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.
6962 * Flag `delete` of a class with a virtual function but no virtual destructor.
6964 ### <a name="Rh-override"></a>C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final`
6966 ##### Reason
6968 Readability.
6969 Detection of mistakes.
6970 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.
6972 It's simple and clear:
6974 * `virtual` means exactly and only "this is a new virtual function."
6975 * `override` means exactly and only "this is a non-final overrider."
6976 * `final` means exactly and only "this is a final overrider."
6978 If a base class destructor is declared `virtual`, one should avoid declaring derived class destructors  `virtual` or `override`. Some code base and tools might insist on `override` for destructors, but that is not the recommendation of these guidelines.
6980 ##### Example, bad
6982     struct B {
6983         void f1(int);
6984         virtual void f2(int) const;
6985         virtual void f3(int);
6986         // ...
6987     };
6989     struct D : B {
6990         void f1(int);        // bad (hope for a warning): D::f1() hides B::f1()
6991         void f2(int) const;  // bad (but conventional and valid): no explicit override
6992         void f3(double);     // bad (hope for a warning): D::f3() hides B::f3()
6993         // ...
6994     };
6996 ##### Example, good
6998     struct Better : B {
6999         void f1(int) override;        // error (caught): Better::f1() hides B::f1()
7000         void f2(int) const override;
7001         void f3(double) override;     // error (caught): Better::f3() hides B::f3()
7002         // ...
7003     };
7005 #### Discussion
7007 We want to eliminate two particular classes of errors:
7009 * **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)
7010 * **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 may have intended to create either a new virtual function or a new nonvirtual function)
7012 ##### Enforcement
7014 * Compare virtual function names in base and derived classes and flag uses of the same name that does not override.
7015 * Flag overrides with neither `override` nor `final`.
7016 * Flag function declarations that use more than one of `virtual`, `override`, and `final`.
7018 ### <a name="Rh-kind"></a>C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance
7020 ##### Reason
7022 Implementation details in an interface make the interface brittle;
7023 that is, make its users vulnerable to having to recompile after changes in the implementation.
7024 Data in a base class increases the complexity of implementing the base and can lead to replication of code.
7026 ##### Note
7028 Definition:
7030 * interface inheritance is the use of inheritance to separate users from implementations,
7031 in particular to allow derived classes to be added and changed without affecting the users of base classes.
7032 * implementation inheritance is the use of inheritance to simplify implementation of new facilities
7033 by making useful operations available for implementers of related new operations (sometimes called "programming by difference").
7035 A pure interface class is simply a set of pure virtual functions; see [I.25](#Ri-abstract).
7037 In early OOP (e.g., in the 1980s and 1990s), implementation inheritance and interface inheritance were often mixed
7038 and bad habits die hard.
7039 Even now, mixtures are not uncommon in old code bases and in old-style teaching material.
7041 The importance of keeping the two kinds of inheritance increases
7043 * with the size of a hierarchy (e.g., dozens of derived classes),
7044 * with the length of time the hierarchy is used (e.g., decades), and
7045 * with the number of distinct organizations in which a hierarchy is used
7046 (e.g., it can be difficult to distribute an update to a base class)
7049 ##### Example, bad
7051     class Shape {   // BAD, mixed interface and implementation
7052     public:
7053         Shape();
7054         Shape(Point ce = {0, 0}, Color co = none): cent{ce}, col {co} { /* ... */}
7056         Point center() const { return cent; }
7057         Color color() const { return col; }
7059         virtual void rotate(int) = 0;
7060         virtual void move(Point p) { cent = p; redraw(); }
7062         virtual void redraw();
7064         // ...
7065     private:
7066         Point cent;
7067         Color col;
7068     };
7070     class Circle : public Shape {
7071     public:
7072         Circle(Point c, int r) :Shape{c}, rad{r} { /* ... */ }
7074         // ...
7075     private:
7076         int rad;
7077     };
7079     class Triangle : public Shape {
7080     public:
7081         Triangle(Point p1, Point p2, Point p3); // calculate center
7082         // ...
7083     };
7085 Problems:
7087 * As the hierarchy grows and more data is added to `Shape`, the constructors get harder to write and maintain.
7088 * Why calculate the center for the `Triangle`? we may never use it.
7089 * Add a data member to `Shape` (e.g., drawing style or canvas)
7090 and all classes derived from `Shape` and all code using `Shape` will need to be reviewed, possibly changed, and probably recompiled.
7092 The implementation of `Shape::move()` is an example of implementation inheritance:
7093 we have defined `move()` once and for all for all derived classes.
7094 The more code there is in such base class member function implementations and the more data is shared by placing it in the base,
7095 the more benefits we gain - and the less stable the hierarchy is.
7097 ##### Example
7099 This Shape hierarchy can be rewritten using interface inheritance:
7101     class Shape {  // pure interface
7102     public:
7103         virtual Point center() const = 0;
7104         virtual Color color() const = 0;
7106         virtual void rotate(int) = 0;
7107         virtual void move(Point p) = 0;
7109         virtual void redraw() = 0;
7111         // ...
7112     };
7114 Note that a pure interface rarely has constructors: there is nothing to construct.
7116     class Circle : public Shape {
7117     public:
7118         Circle(Point c, int r, Color c) :cent{c}, rad{r}, col{c} { /* ... */ }
7120         Point center() const override { return cent; }
7121         Color color() const override { return col; }
7123         // ...
7124     private:
7125         Point cent;
7126         int rad;
7127         Color col;
7128     };
7130 The interface is now less brittle, but there is more work in implementing the member functions.
7131 For example, `center` has to be implemented by every class derived from `Shape`.
7133 ##### Example, dual hierarchy
7135 How can we gain the benefit of stable hierarchies from implementation hierarchies and the benefit of implementation reuse from implementation inheritance?
7136 One popular technique is dual hierarchies.
7137 There are many ways of implementing the idea of dual hierarchies; here, we use a multiple-inheritance variant.
7139 First we devise a hierarchy of interface classes:
7141     class Shape {   // pure interface
7142     public:
7143         virtual Point center() const = 0;
7144         virtual Color color() const = 0;
7146         virtual void rotate(int) = 0;
7147         virtual void move(Point p) = 0;
7149         virtual void redraw() = 0;
7151         // ...
7152     };
7154     class Circle : public virtual Shape {   // pure interface
7155     public:
7156         virtual int radius() = 0;
7157         // ...
7158     };
7160 To make this interface useful, we must provide its implementation classes (here, named equivalently, but in the `Impl` namespace):
7162     class Impl::Shape : public virtual ::Shape { // implementation
7163     public:
7164         // constructors, destructor
7165         // ...
7166         Point center() const override { /* ... */ }
7167         Color color() const override { /* ... */ }
7169         void rotate(int) override { /* ... */ }
7170         void move(Point p) override { /* ... */ }
7172         void redraw() override { /* ... */ }
7174         // ...
7175     };
7177 Now `Shape` is a poor example of a class with an implementation,
7178 but bear with us because this is just a simple example of a technique aimed at more complex hierarchies.
7180     class Impl::Circle : public virtual ::Circle, public Impl::Shape {   // implementation
7181     public:
7182         // constructors, destructor
7184         int radius() override { /* ... */ }
7185         // ...
7186     };
7188 And we could extend the hierarchies by adding a Smiley class (:-)):
7190     class Smiley : public virtual Circle { // pure interface
7191     public:
7192         // ...
7193     };
7195     class Impl::Smiley : public virtual ::Smiley, public Impl::Circle {   // implementation
7196     public:
7197         // constructors, destructor
7198         // ...
7199     }
7201 There are now two hierarchies:
7203 * interface: Smiley -> Circle -> Shape
7204 * implementation: Impl::Smiley -> Impl::Circle -> Impl::Shape
7206 Since each implementation is derived from its interface as well as its implementation base class we get a lattice (DAG):
7208     Smiley     ->         Circle     ->  Shape
7209       ^                     ^               ^
7210       |                     |               |
7211     Impl::Smiley -> Impl::Circle -> Impl::Shape
7213 As mentioned, this is just one way to construct a dual hierarchy.
7215 The implementation hierarchy can be used directly, rather than through the abstract interface.
7217     void work_with_shape(Shape&);
7219     int user()
7220     {
7221         Impl::Smiley my_smiley{ /* args */ };   // create concrete shape
7222         // ...
7223         my_smiley.some_member();        // use implementation class directly
7224         // ...
7225         work_with_shape(my_smiley);     // use implementation through abstract interface
7226         // ...
7227     }
7229 This can be useful when the implementation class has members that are not offered in the abstract interface
7230 or if direct use of a member offers optimization opportunities (e.g., if an implementation member function is `final`)
7232 ##### Note
7234 Another (related) technique for separating interface and implementation is [Pimpl](#Ri-pimpl).
7236 ##### Note
7238 There is often a choice between offering common functionality as (implemented) base class functions and free-standing functions
7239 (in an implementation namespace).
7240 Base classes gives a shorter notation and easier access to shared data (in the base)
7241 at the cost of the functionality being available only to users of the hierarchy.
7243 ##### Enforcement
7245 * Flag a derived to base conversion to a base with both data and virtual functions
7246 (except for calls from a derived class member to a base class member)
7247 * ???
7250 ### <a name="Rh-copy"></a>C.130: For making deep copies of polymorphic classes prefer a virtual `clone` function instead of copy construction/assignment
7252 ##### Reason
7254 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).
7256 ##### Example
7258     class B {
7259     public:
7260         virtual owner<B*> clone() = 0;
7261         virtual ~B() = 0;
7263         B(const B&) = delete;
7264         B& operator=(const B&) = delete;
7265     };
7267     class D : public B {
7268     public:
7269         owner<D*> clone() override;
7270         virtual ~D() override;
7271     };
7273 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).
7277 ### <a name="Rh-get"></a>C.131: Avoid trivial getters and setters
7279 ##### Reason
7281 A trivial getter or setter adds no semantic value; the data item could just as well be `public`.
7283 ##### Example
7285     class Point {   // Bad: verbose
7286         int x;
7287         int y;
7288     public:
7289         Point(int xx, int yy) : x{xx}, y{yy} { }
7290         int get_x() const { return x; }
7291         void set_x(int xx) { x = xx; }
7292         int get_y() const { return y; }
7293         void set_y(int yy) { y = yy; }
7294         // no behavioral member functions
7295     };
7297 Consider making such a class a `struct` -- that is, a behaviorless bunch of variables, all public data and no member functions.
7299     struct Point {
7300         int x {0};
7301         int y {0};
7302     };
7304 Note that we can put default initializers on member variables: [C.49: Prefer initialization to assignment in constructors](#Rc-initialize).
7306 ##### Note
7308 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.
7310 ##### Enforcement
7312 Flag multiple `get` and `set` member functions that simply access a member without additional semantics.
7314 ### <a name="Rh-virtual"></a>C.132: Don't make a function `virtual` without reason
7316 ##### Reason
7318 Redundant `virtual` increases run-time and object-code size.
7319 A virtual function can be overridden and is thus open to mistakes in a derived class.
7320 A virtual function ensures code replication in a templated hierarchy.
7322 ##### Example, bad
7324     template<class T>
7325     class Vector {
7326     public:
7327         // ...
7328         virtual int size() const { return sz; }   // bad: what good could a derived class do?
7329     private:
7330         T* elem;   // the elements
7331         int sz;    // number of elements
7332     };
7334 This kind of "vector" isn't meant to be used as a base class at all.
7336 ##### Enforcement
7338 * Flag a class with virtual functions but no derived classes.
7339 * Flag a class where all member functions are virtual and have implementations.
7341 ### <a name="Rh-protected"></a>C.133: Avoid `protected` data
7343 ##### Reason
7345 `protected` data is a source of complexity and errors.
7346 `protected` data complicates the statement of invariants.
7347 `protected` data inherently violates the guidance against putting data in base classes, which usually leads to having to deal with virtual inheritance as well.
7349 ##### Example, bad
7351     class Shape {
7352     public:
7353         // ... interface functions ...
7354     protected:
7355         // data for use in derived classes:
7356         Color fill_color;
7357         Color edge_color;
7358         Style st;
7359     };
7361 Now it is up to every derived `Shape` to manipulate the protected data correctly.
7362 This has been popular, but also a major source of maintenance problems.
7363 In a large class hierarchy, the consistent use of protected data is hard to maintain because there can be a lot of code,
7364 spread over a lot of classes.
7365 The set of classes that can touch that data is open: anyone can derive a new class and start manipulating the protected data.
7366 Often, it is not possible to examine the complete set of classes, so any change to the representation of the class becomes infeasible.
7367 There is no enforced invariant for the protected data; it is much like a set of global variables.
7368 The protected data has de facto become global to a large body of code.
7370 ##### Note
7372 Protected data often looks tempting to enable arbitrary improvements through derivation.
7373 Often, what you get is unprincipled changes and errors.
7374 [Prefer `private` data](#Rc-private) with a well-specified and enforced invariant.
7375 Alternative, and often better, [keep data out of any class used as an interface](#Rh-abstract).
7377 ##### Note
7379 Protected member function can be just fine.
7381 ##### Enforcement
7383 Flag classes with `protected` data.
7385 ### <a name="Rh-public"></a>C.134: Ensure all non-`const` data members have the same access level
7387 ##### Reason
7389 Prevention of logical confusion leading to errors.
7390 If the non-`const` data members don't have the same access level, the type is confused about what it's trying to do.
7391 Is it a type that maintains an invariant or simply a collection of values?
7393 ##### Discussion
7395 The core question is: What code is responsible for maintaining a meaningful/correct value for that variable?
7397 There are exactly two kinds of data members:
7399 * A: Ones that don't participate in the object's invariant. Any combination of values for these members is valid.
7400 * 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.
7402 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.
7404 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.
7406 Most classes are either all A or all B:
7408 * *All public*: If you're writing an aggregate bundle-of-variables without an invariant across those variables, then all the variables should be `public`.
7409   [By convention, declare such classes `struct` rather than `class`](#Rc-struct)
7410 * *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.
7412 ##### Exception
7414 Occasionally classes will mix A and B, usually for debug reasons. An encapsulated object may 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`).
7416 ##### Enforcement
7418 Flag any class that has non-`const` data members with different access levels.
7420 ### <a name="Rh-mi-interface"></a>C.135: Use multiple inheritance to represent multiple distinct interfaces
7422 ##### Reason
7424 Not all classes will necessarily support all interfaces, and not all callers will necessarily want to deal with all operations.
7425 Especially to break apart monolithic interfaces into "aspects" of behavior supported by a given derived class.
7427 ##### Example
7429     class iostream : public istream, public ostream {   // very simplified
7430         // ...
7431     };
7433 `istream` provides the interface to input operations; `ostream` provides the interface to output operations.
7434 `iostream` provides the union of the `istream` and `ostream` interfaces and the synchronization needed to allow both on a single stream.
7436 ##### Note
7438 This is a very common use of inheritance because the need for multiple different interfaces to an implementation is common
7439 and such interfaces are often not easily or naturally organized into a single-rooted hierarchy.
7441 ##### Note
7443 Such interfaces are typically abstract classes.
7445 ##### Enforcement
7449 ### <a name="Rh-mi-implementation"></a>C.136: Use multiple inheritance to represent the union of implementation attributes
7451 ##### Reason
7453 Some forms of mixins have state and often operations on that state.
7454 If the operations are virtual the use of inheritance is necessary, if not using inheritance can avoid boilerplate and forwarding.
7456 ##### Example
7458     class iostream : public istream, public ostream {   // very simplified
7459         // ...
7460     };
7462 `istream` provides the interface to input operations (and some data); `ostream` provides the interface to output operations (and some data).
7463 `iostream` provides the union of the `istream` and `ostream` interfaces and the synchronization needed to allow both on a single stream.
7465 ##### Note
7467 This a relatively rare use because implementation can often be organized into a single-rooted hierarchy.
7469 ##### Example
7471 Sometimes, an "implementation attribute" is more like a "mixin" that determine the behavior of an implementation and inject
7472 members to enable the implementation of the policies it requires.
7473 For example, see `std::enable_shared_from_this`
7474 or various bases from boost.intrusive (e.g. `list_base_hook` or `intrusive_ref_counter`).
7476 ##### Enforcement
7480 ### <a name="Rh-vbase"></a>C.137: Use `virtual` bases to avoid overly general base classes
7482 ##### Reason
7484  Allow separation of shared data and interface.
7485  To avoid all shared data to being put into an ultimate base class.
7487 ##### Example
7489     struct Interface {
7490         virtual void f();
7491         virtual int g();
7492         // ... no data here ...
7493     };
7495     class Utility {  // with data
7496         void utility1();
7497         virtual void utility2();    // customization point
7498     public:
7499         int x;
7500         int y;
7501     };
7503     class Derive1 : public Interface, virtual protected Utility {
7504         // override Interface functions
7505         // Maybe override Utility virtual functions
7506         // ...
7507     };
7509     class Derive2 : public Interface, virtual protected Utility {
7510         // override Interface functions
7511         // Maybe override Utility virtual functions
7512         // ...
7513     };
7515 Factoring out `Utility` makes sense if many derived classes share significant "implementation details."
7518 ##### Note
7520 Obviously, the example is too "theoretical", but it is hard to find a *small* realistic example.
7521 `Interface` is the root of an [interface hierarchy](#Rh-abstract)
7522 and `Utility` is the root of an [implementation hierarchy](#Rh-kind).
7523 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.
7525 ##### Note
7527 Often, linearization of a hierarchy is a better solution.
7529 ##### Enforcement
7531 Flag mixed interface and implementation hierarchies.
7533 ### <a name="Rh-using"></a>C.138: Create an overload set for a derived class and its bases with `using`
7535 ##### Reason
7537 Without a using declaration, member functions in the derived class hide the entire inherited overload sets.
7539 ##### Example, bad
7541     #include <iostream>
7542     class B {
7543     public:
7544         virtual int f(int i) { std::cout << "f(int): "; return i; }
7545         virtual double f(double d) { std::cout << "f(double): "; return d; }
7546     };
7547     class D: public B {
7548     public:
7549         int f(int i) override { std::cout << "f(int): "; return i + 1; }
7550     };
7551     int main()
7552     {
7553         D d;
7554         std::cout << d.f(2) << '\n';   // prints "f(int): 3"
7555         std::cout << d.f(2.3) << '\n'; // prints "f(int): 3"
7556     }
7558 ##### Example, good
7560     class D: public B {
7561     public:
7562         int f(int i) override { std::cout << "f(int): "; return i + 1; }
7563         using B::f; // exposes f(double)
7564     };
7566 ##### Note
7568 This issue affects both virtual and nonvirtual member functions
7570 For variadic bases, C++17 introduced a variadic form of the using-declaration,
7572     template <class... Ts>
7573     struct Overloader : Ts... {
7574         using Ts::operator()...; // exposes operator() from every base
7575     };
7577 ##### Enforcement
7579 Diagnose name hiding
7581 ### <a name="Rh-final"></a>C.139: Use `final` sparingly
7583 ##### Reason
7585 Capping a hierarchy with `final` is rarely needed for logical reasons and can be damaging to the extensibility of a hierarchy.
7587 ##### Example, bad
7589     class Widget { /* ... */ };
7591     // nobody will ever want to improve My_widget (or so you thought)
7592     class My_widget final : public Widget { /* ... */ };
7594     class My_improved_widget : public My_widget { /* ... */ };  // error: can't do that
7596 ##### Note
7598 Not every class is meant to be a base class.
7599 Most standard-library classes are examples of that (e.g., `std::vector` and `std::string` are not designed to be derived from).
7600 This rule is about using `final` on classes with virtual functions meant to be interfaces for a class hierarchy.
7602 ##### Note
7604 Capping an individual virtual function with `final` is error-prone as `final` can easily be overlooked when defining/overriding a set of functions.
7605 Fortunately, the compiler catches such mistakes: You cannot re-declare/re-open a `final` member in a derived class.
7607 ##### Note
7609 Claims of performance improvements from `final` should be substantiated.
7610 Too often, such claims are based on conjecture or experience with other languages.
7612 There are examples where `final` can be important for both logical and performance reasons.
7613 One example is a performance-critical AST hierarchy in a compiler or language analysis tool.
7614 New derived classes are not added every year and only by library implementers.
7615 However, misuses are (or at least have been) far more common.
7617 ##### Enforcement
7619 Flag uses of `final`.
7622 ### <a name="Rh-virtual-default-arg"></a>C.140: Do not provide different default arguments for a virtual function and an overrider
7624 ##### Reason
7626 That can cause confusion: An overrider does not inherit default arguments.
7628 ##### Example, bad
7630     class Base {
7631     public:
7632         virtual int multiply(int value, int factor = 2) = 0;
7633     };
7635     class Derived : public Base {
7636     public:
7637         int multiply(int value, int factor = 10) override;
7638     };
7640     Derived d;
7641     Base& b = d;
7643     b.multiply(10);  // these two calls will call the same function but
7644     d.multiply(10);  // with different arguments and so different results
7646 ##### Enforcement
7648 Flag default arguments on virtual functions if they differ between base and derived declarations.
7650 ## C.hier-access: Accessing objects in a hierarchy
7652 ### <a name="Rh-poly"></a>C.145: Access polymorphic objects through pointers and references
7654 ##### Reason
7656 If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.
7658 ##### Example
7660     struct B { int a; virtual int f(); };
7661     struct D : B { int b; int f() override; };
7663     void use(B b)
7664     {
7665         D d;
7666         B b2 = d;   // slice
7667         B b3 = b;
7668     }
7670     void use2()
7671     {
7672         D d;
7673         use(d);   // slice
7674     }
7676 Both `d`s are sliced.
7678 ##### Exception
7680 You can safely access a named polymorphic object in the scope of its definition, just don't slice it.
7682     void use3()
7683     {
7684         D d;
7685         d.f();   // OK
7686     }
7688 ##### Enforcement
7690 Flag all slicing.
7692 ### <a name="Rh-dynamic_cast"></a>C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable
7694 ##### Reason
7696 `dynamic_cast` is checked at run time.
7698 ##### Example
7700     struct B {   // an interface
7701         virtual void f();
7702         virtual void g();
7703     };
7705     struct D : B {   // a wider interface
7706         void f() override;
7707         virtual void h();
7708     };
7710     void user(B* pb)
7711     {
7712         if (D* pd = dynamic_cast<D*>(pb)) {
7713             // ... use D's interface ...
7714         }
7715         else {
7716             // ... make do with B's interface ...
7717         }
7718     }
7720 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`:
7722     void user2(B* pb)   // bad
7723     {
7724         D* pd = static_cast<D*>(pb);    // I know that pb really points to a D; trust me
7725         // ... use D's interface ...
7726     }
7728     void user3(B* pb)    // unsafe
7729     {
7730         if (some_condition) {
7731             D* pd = static_cast<D*>(pb);   // I know that pb really points to a D; trust me
7732             // ... use D's interface ...
7733         }
7734         else {
7735             // ... make do with B's interface ...
7736         }
7737     }
7739     void f()
7740     {
7741         B b;
7742         user(&b);   // OK
7743         user2(&b);  // bad error
7744         user3(&b);  // OK *if* the programmer got the some_condition check right
7745     }
7747 ##### Note
7749 Like other casts, `dynamic_cast` is overused.
7750 [Prefer virtual functions to casting](#Rh-use-virtual).
7751 Prefer [static polymorphism](#???) to hierarchy navigation where it is possible (no run-time resolution necessary)
7752 and reasonably convenient.
7754 ##### Note
7756 Some people use `dynamic_cast` where a `typeid` would have been more appropriate;
7757 `dynamic_cast` is a general "is kind of" operation for discovering the best interface to an object,
7758 whereas `typeid` is a "give me the exact type of this object" operation to discover the actual type of an object.
7759 The latter is an inherently simpler operation that ought to be faster.
7760 The latter (`typeid`) is easily hand-crafted if necessary (e.g., if working on a system where RTTI is -- for some reason -- prohibited),
7761 the former (`dynamic_cast`) is far harder to implement correctly in general.
7763 Consider:
7765     struct B {
7766         const char* name {"B"};
7767         // if pb1->id() == pb2->id() *pb1 is the same type as *pb2
7768         virtual const char* id() const { return name; }
7769         // ...
7770     };
7772     struct D : B {
7773         const char* name {"D"};
7774         const char* id() const override { return name; }
7775         // ...
7776     };
7778     void use()
7779     {
7780         B* pb1 = new B;
7781         B* pb2 = new D;
7783         cout << pb1->id(); // "B"
7784         cout << pb2->id(); // "D"
7787         if (pb1->id() == "D") {         // looks innocent
7788             D* pd = static_cast<D*>(pb1);
7789             // ...
7790         }
7791         // ...
7792     }
7794 The result of `pb2->id() == "D"` is actually implementation defined.
7795 We added it to warn of the dangers of home-brew RTTI.
7796 This code may work as expected for years, just to fail on a new machine, new compiler, or a new linker that does not unify character literals.
7798 If you implement your own RTTI, be careful.
7800 ##### Exception
7802 If your implementation provided a really slow `dynamic_cast`, you may have to use a workaround.
7803 However, all workarounds that cannot be statically resolved involve explicit casting (typically `static_cast`) and are error-prone.
7804 You will basically be crafting your own special-purpose `dynamic_cast`.
7805 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)
7806 and that your use of `dynamic_cast` is really performance critical.
7808 We are of the opinion that current implementations of `dynamic_cast` are unnecessarily slow.
7809 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).
7810 However, compatibility makes changes difficult even if all agree that an effort to optimize is worthwhile.
7812 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.
7814 ##### Exception
7816 Consider:
7818     template<typename B>
7819     class Dx : B {
7820         // ...
7821     };
7823 ##### Enforcement
7825 * Flag all uses of `static_cast` for downcasts, including C-style casts that perform a `static_cast`.
7826 * This rule is part of the [type-safety profile](#Pro-type-downcast).
7828 ### <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
7830 ##### Reason
7832 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.
7834 ##### Example
7836     ???
7838 ##### Enforcement
7842 ### <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
7844 ##### Reason
7846 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.
7848 Contrast with [C.147](#Rh-ptr-cast), where failure is an error, and should not be used for conditional execution.
7850 ##### Example
7852 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.
7853 In this example, `Shape` does not inherit from `Geometric_attributes`. Only its subclasses do.
7855     void add(Shape* const item)
7856     {
7857       // Ownership is always taken
7858       owned_shapes.emplace_back(item);
7860       // Check the Geometric_attributes and add the shape to none/one/some/all of the views
7862       if (auto even = dynamic_cast<Even_sided*>(item))
7863       {
7864         view_of_evens.emplace_back(even);
7865       }
7867       if (auto trisym = dynamic_cast<Trilaterally_symmetrical*>(item))
7868       {
7869         view_of_trisyms.emplace_back(trisym);
7870       }
7871     }
7873 ##### Notes
7875 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.
7876 Therefore the result of the `dynamic_cast` should always be treated as if it may contain a null value, and tested.
7878 ##### Enforcement
7880 * (Complex) Unless there is a null test on the result of a `dynamic_cast` of a pointer type, warn upon dereference of the pointer.
7882 ### <a name="Rh-smart"></a>C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`
7884 ##### Reason
7886 Avoid resource leaks.
7888 ##### Example
7890     void use(int i)
7891     {
7892         auto p = new int {7};           // bad: initialize local pointers with new
7893         auto q = make_unique<int>(9);   // ok: guarantee the release of the memory-allocated for 9
7894         if (0 < i) return;              // maybe return and leak
7895         delete p;                       // too late
7896     }
7898 ##### Enforcement
7900 * Flag initialization of a naked pointer with the result of a `new`
7901 * Flag `delete` of local variable
7903 ### <a name="Rh-make_unique"></a>C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s
7905 ##### Reason
7907 `make_unique` gives a more concise statement of the construction.
7908 It also ensures exception safety in complex expressions.
7910 ##### Example
7912     unique_ptr<Foo> p {new Foo{7}};    // OK: but repetitive
7914     auto q = make_unique<Foo>(7);      // Better: no repetition of Foo
7916     // Not exception-safe: the compiler may interleave the computations of arguments as follows:
7917     //
7918     // 1. allocate memory for Foo,
7919     // 2. construct Foo,
7920     // 3. call bar,
7921     // 4. construct unique_ptr<Foo>.
7922     //
7923     // If bar throws, Foo will not be destroyed, and the memory-allocated for it will leak.
7924     f(unique_ptr<Foo>(new Foo()), bar());
7926     // Exception-safe: calls to functions are never interleaved.
7927     f(make_unique<Foo>(), bar());
7929 ##### Enforcement
7931 * Flag the repetitive usage of template specialization list `<Foo>`
7932 * Flag variables declared to be `unique_ptr<Foo>`
7934 ### <a name="Rh-make_shared"></a>C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s
7936 ##### Reason
7938 `make_shared` gives a more concise statement of the construction.
7939 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.
7941 ##### Example
7943     void test() {
7944         // OK: but repetitive; and separate allocations for the Bar and shared_ptr's use count
7945         shared_ptr<Bar> p {new Bar{7}};
7947         auto q = make_shared<Bar>(7);   // Better: no repetition of Bar; one object
7948     }
7950 ##### Enforcement
7952 * Flag the repetitive usage of template specialization list`<Bar>`
7953 * Flag variables declared to be `shared_ptr<Bar>`
7955 ### <a name="Rh-array"></a>C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
7957 ##### Reason
7959 Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.
7961 ##### Example
7963     struct B { int x; };
7964     struct D : B { int y; };
7966     void use(B*);
7968     D a[] = {{1, 2}, {3, 4}, {5, 6}};
7969     B* p = a;     // bad: a decays to &a[0] which is converted to a B*
7970     p[1].x = 7;   // overwrite D[0].y
7972     use(a);       // bad: a decays to &a[0] which is converted to a B*
7974 ##### Enforcement
7976 * Flag all combinations of array decay and base to derived conversions.
7977 * 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`
7980 ### <a name="Rh-use-virtual"></a>C.153: Prefer virtual function to casting
7982 ##### Reason
7984 A virtual function call is safe, whereas casting is error-prone.
7985 A virtual function call reaches the most derived function, whereas a cast may reach an intermediate class and therefore
7986 give a wrong result (especially as a hierarchy is modified during maintenance).
7988 ##### Example
7990     ???
7992 ##### Enforcement
7994 See [C.146](#Rh-dynamic_cast) and ???
7996 ## <a name="SS-overload"></a>C.over: Overloading and overloaded operators
7998 You can overload ordinary functions, template functions, and operators.
7999 You cannot overload function objects.
8001 Overload rule summary:
8003 * [C.160: Define operators primarily to mimic conventional usage](#Ro-conventional)
8004 * [C.161: Use nonmember functions for symmetric operators](#Ro-symmetric)
8005 * [C.162: Overload operations that are roughly equivalent](#Ro-equivalent)
8006 * [C.163: Overload only for operations that are roughly equivalent](#Ro-equivalent-2)
8007 * [C.164: Avoid implicit conversion operators](#Ro-conversion)
8008 * [C.165: Use `using` for customization points](#Ro-custom)
8009 * [C.166: Overload unary `&` only as part of a system of smart pointers and references](#Ro-address-of)
8010 * [C.167: Use an operator for an operation with its conventional meaning](#Ro-overload)
8011 * [C.168: Define overloaded operators in the namespace of their operands](#Ro-namespace)
8012 * [C.170: If you feel like overloading a lambda, use a generic lambda](#Ro-lambda)
8014 ### <a name="Ro-conventional"></a>C.160: Define operators primarily to mimic conventional usage
8016 ##### Reason
8018 Minimize surprises.
8020 ##### Example
8022     class X {
8023     public:
8024         // ...
8025         X& operator=(const X&); // member function defining assignment
8026         friend bool operator==(const X&, const X&); // == needs access to representation
8027                                                     // after a = b we have a == b
8028         // ...
8029     };
8031 Here, the conventional semantics is maintained: [Copies compare equal](#SS-copy).
8033 ##### Example, bad
8035     X operator+(X a, X b) { return a.v - b.v; }   // bad: makes + subtract
8037 ##### Note
8039 Nonmember operators should be either friends or defined in [the same namespace as their operands](#Ro-namespace).
8040 [Binary operators should treat their operands equivalently](#Ro-symmetric).
8042 ##### Enforcement
8044 Possibly impossible.
8046 ### <a name="Ro-symmetric"></a>C.161: Use nonmember functions for symmetric operators
8048 ##### Reason
8050 If you use member functions, you need two.
8051 Unless you use a nonmember function for (say) `==`, `a == b` and `b == a` will be subtly different.
8053 ##### Example
8055     bool operator==(Point a, Point b) { return a.x == b.x && a.y == b.y; }
8057 ##### Enforcement
8059 Flag member operator functions.
8061 ### <a name="Ro-equivalent"></a>C.162: Overload operations that are roughly equivalent
8063 ##### Reason
8065 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.
8067 ##### Example
8069 Consider:
8071     void print(int a);
8072     void print(int a, int base);
8073     void print(const string&);
8075 These three functions all print their arguments (appropriately). Conversely:
8077     void print_int(int a);
8078     void print_based(int a, int base);
8079     void print_string(const string&);
8081 These three functions all print their arguments (appropriately). Adding to the name just introduced verbosity and inhibits generic code.
8083 ##### Enforcement
8087 ### <a name="Ro-equivalent-2"></a>C.163: Overload only for operations that are roughly equivalent
8089 ##### Reason
8091 Having the same name for logically different functions is confusing and leads to errors when using generic programming.
8093 ##### Example
8095 Consider:
8097     void open_gate(Gate& g);   // remove obstacle from garage exit lane
8098     void fopen(const char* name, const char* mode);   // open file
8100 The two operations are fundamentally different (and unrelated) so it is good that their names differ. Conversely:
8102     void open(Gate& g);   // remove obstacle from garage exit lane
8103     void open(const char* name, const char* mode ="r");   // open file
8105 The two operations are still fundamentally different (and unrelated) but the names have been reduced to their (common) minimum, opening opportunities for confusion.
8106 Fortunately, the type system will catch many such mistakes.
8108 ##### Note
8110 Be particularly careful about common and popular names, such as `open`, `move`, `+`, and `==`.
8112 ##### Enforcement
8116 ### <a name="Ro-conversion"></a>C.164: Avoid implicit conversion operators
8118 ##### Reason
8120 Implicit conversions can be essential (e.g., `double` to `int`) but often cause surprises (e.g., `String` to C-style string).
8122 ##### Note
8124 Prefer explicitly named conversions until a serious need is demonstrated.
8125 By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion)
8126 and frequently needed. Do not introduce implicit conversions (through conversion operators or non-`explicit` constructors)
8127 just to gain a minor convenience.
8129 ##### Example
8131     struct S1 {
8132         string s;
8133         // ...
8134         operator char*() { return s.data(); }  // BAD, likely to cause surprises
8135     };
8137     struct S2 {
8138         string s;
8139         // ...
8140         explicit operator char*() { return s.data(); }
8141     };
8143     void f(S1 s1, S2 s2)
8144     {
8145         char* x1 = s1;     // OK, but can cause surprises in many contexts
8146         char* x2 = s2;     // error (and that's usually a good thing)
8147         char* x3 = static_cast<char*>(s2); // we can be explicit (on your head be it)
8148     }
8150 The surprising and potentially damaging implicit conversion can occur in arbitrarily hard-to spot contexts, e.g.,
8152     S1 ff();
8154     char* g()
8155     {
8156         return ff();
8157     }
8159 The string returned by `ff()` is destroyed before the returned pointer into it can be used.
8161 ##### Enforcement
8163 Flag all conversion operators.
8165 ### <a name="Ro-custom"></a>C.165: Use `using` for customization points
8167 ##### Reason
8169 To find function objects and functions defined in a separate namespace to "customize" a common function.
8171 ##### Example
8173 Consider `swap`. It is a general (standard-library) function with a definition that will work for just about any type.
8174 However, it is desirable to define specific `swap()`s for specific types.
8175 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.
8177     namespace N {
8178         My_type X { /* ... */ };
8179         void swap(X&, X&);   // optimized swap for N::X
8180         // ...
8181     }
8183     void f1(N::X& a, N::X& b)
8184     {
8185         std::swap(a, b);   // probably not what we wanted: calls std::swap()
8186     }
8188 The `std::swap()` in `f1()` does exactly what we asked it to do: it calls the `swap()` in namespace `std`.
8189 Unfortunately, that's probably not what we wanted.
8190 How do we get `N::X` considered?
8192     void f2(N::X& a, N::X& b)
8193     {
8194         swap(a, b);   // calls N::swap
8195     }
8197 But that may not be what we wanted for generic code.
8198 There, we typically want the specific function if it exists and the general function if not.
8199 This is done by including the general function in the lookup for the function:
8201     void f3(N::X& a, N::X& b)
8202     {
8203         using std::swap;  // make std::swap available
8204         swap(a, b);        // calls N::swap if it exists, otherwise std::swap
8205     }
8207 ##### Enforcement
8209 Unlikely, except for known customization points, such as `swap`.
8210 The problem is that the unqualified and qualified lookups both have uses.
8212 ### <a name="Ro-address-of"></a>C.166: Overload unary `&` only as part of a system of smart pointers and references
8214 ##### Reason
8216 The `&` operator is fundamental in C++.
8217 Many parts of the C++ semantics assumes its default meaning.
8219 ##### Example
8221     class Ptr { // a somewhat smart pointer
8222         Ptr(X* pp) :p(pp) { /* check */ }
8223         X* operator->() { /* check */ return p; }
8224         X operator[](int i);
8225         X operator*();
8226     private:
8227         T* p;
8228     };
8230     class X {
8231         Ptr operator&() { return Ptr{this}; }
8232         // ...
8233     };
8235 ##### Note
8237 If you "mess with" operator `&` be sure that its definition has matching meanings for `->`, `[]`, `*`, and `.` on the result type.
8238 Note that operator `.` currently cannot be overloaded so a perfect system is impossible.
8239 We hope to remedy that: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf>.
8240 Note that `std::addressof()` always yields a built-in pointer.
8242 ##### Enforcement
8244 Tricky. Warn if `&` is user-defined without also defining `->` for the result type.
8246 ### <a name="Ro-overload"></a>C.167: Use an operator for an operation with its conventional meaning
8248 ##### Reason
8250 Readability. Convention. Reusability. Support for generic code
8252 ##### Example
8254     void cout_my_class(const My_class& c) // confusing, not conventional,not generic
8255     {
8256         std::cout << /* class members here */;
8257     }
8259     std::ostream& operator<<(std::ostream& os, const my_class& c) // OK
8260     {
8261         return os << /* class members here */;
8262     }
8264 By itself, `cout_my_class` would be OK, but it is not usable/composable with code that rely on the `<<` convention for output:
8266     My_class var { /* ... */ };
8267     // ...
8268     cout << "var = " << var << '\n';
8270 ##### Note
8272 There are strong and vigorous conventions for the meaning most operators, such as
8274 * comparisons (`==`, `!=`, `<`, `<=`, `>`, and `>=`),
8275 * arithmetic operations (`+`, `-`, `*`, `/`, and `%`)
8276 * access operations (`.`, `->`, unary `*`, and `[]`)
8277 * assignment (`=`)
8279 Don't define those unconventionally and don't invent your own names for them.
8281 ##### Enforcement
8283 Tricky. Requires semantic insight.
8285 ### <a name="Ro-namespace"></a>C.168: Define overloaded operators in the namespace of their operands
8287 ##### Reason
8289 Readability.
8290 Ability for find operators using ADL.
8291 Avoiding inconsistent definition in different namespaces
8293 ##### Example
8295     struct S { };
8296     bool operator==(S, S);   // OK: in the same namespace as S, and even next to S
8297     S s;
8299     bool x = (s == s);
8301 This is what a default `==` would do, if we had such defaults.
8303 ##### Example
8305     namespace N {
8306         struct S { };
8307         bool operator==(S, S);   // OK: in the same namespace as S, and even next to S
8308     }
8310     N::S s;
8312     bool x = (s == s);  // finds N::operator==() by ADL
8314 ##### Example, bad
8316     struct S { };
8317     S s;
8319     namespace N {
8320         S::operator!(S a) { return true; }
8321         S not_s = !s;
8322     }
8324     namespace M {
8325         S::operator!(S a) { return false; }
8326         S not_s = !s;
8327     }
8329 Here, the meaning of `!s` differs in `N` and `M`.
8330 This can be most confusing.
8331 Remove the definition of `namespace M` and the confusion is replaced by an opportunity to make the mistake.
8333 ##### Note
8335 If a binary operator is defined for two types that are defined in different namespaces, you cannot follow this rule.
8336 For example:
8338     Vec::Vector operator*(const Vec::Vector&, const Mat::Matrix&);
8340 This may be something best avoided.
8342 ##### See also
8344 This is a special case of the rule that [helper functions should be defined in the same namespace as their class](#Rc-helper).
8346 ##### Enforcement
8348 * Flag operator definitions that are not it the namespace of their operands
8350 ### <a name="Ro-lambda"></a>C.170: If you feel like overloading a lambda, use a generic lambda
8352 ##### Reason
8354 You cannot overload by defining two different lambdas with the same name.
8356 ##### Example
8358     void f(int);
8359     void f(double);
8360     auto f = [](char);   // error: cannot overload variable and function
8362     auto g = [](int) { /* ... */ };
8363     auto g = [](double) { /* ... */ };   // error: cannot overload variables
8365     auto h = [](auto) { /* ... */ };   // OK
8367 ##### Enforcement
8369 The compiler catches the attempt to overload a lambda.
8371 ## <a name="SS-union"></a>C.union: Unions
8373 A `union` is a `struct` where all members start at the same address so that it can hold only one member at a time.
8374 A `union` does not keep track of which member is stored so the programmer has to get it right;
8375 this is inherently error-prone, but there are ways to compensate.
8377 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*.
8379 Union rule summary:
8381 * [C.180: Use `union`s to save Memory](#Ru-union)
8382 * [C.181: Avoid "naked" `union`s](#Ru-naked)
8383 * [C.182: Use anonymous `union`s to implement tagged unions](#Ru-anonymous)
8384 * [C.183: Don't use a `union` for type punning](#Ru-pun)
8385 * ???
8387 ### <a name="Ru-union"></a>C.180: Use `union`s to save memory
8389 ##### Reason
8391 A `union` allows a single piece of memory to be used for different types of objects at different times.
8392 Consequently, it can be used to save memory when we have several objects that are never used at the same time.
8394 ##### Example
8396     union Value {
8397         int x;
8398         double d;
8399     };
8401     Value v = { 123 };  // now v holds an int
8402     cout << v.x << '\n';    // write 123
8403     v.d = 987.654;  // now v holds a double
8404     cout << v.d << '\n';    // write 987.654
8406 But heed the warning: [Avoid "naked" `union`s](#Ru-naked)
8408 ##### Example
8410     // Short-string optimization
8412     constexpr size_t buffer_size = 16; // Slightly larger than the size of a pointer
8414     class Immutable_string {
8415     public:
8416         Immutable_string(const char* str) :
8417             size(strlen(str))
8418         {
8419             if (size < buffer_size)
8420                 strcpy_s(string_buffer, buffer_size, str);
8421             else {
8422                 string_ptr = new char[size + 1];
8423                 strcpy_s(string_ptr, size + 1, str);
8424             }
8425         }
8427         ~Immutable_string()
8428         {
8429             if (size >= buffer_size)
8430                 delete string_ptr;
8431         }
8433         const char* get_str() const
8434         {
8435             return (size < buffer_size) ? string_buffer : string_ptr;
8436         }
8438     private:
8439         // If the string is short enough, we store the string itself
8440         // instead of a pointer to the string.
8441         union {
8442             char* string_ptr;
8443             char string_buffer[buffer_size];
8444         };
8446         const size_t size;
8447     };
8449 ##### Enforcement
8453 ### <a name="Ru-naked"></a>C.181: Avoid "naked" `union`s
8455 ##### Reason
8457 A *naked union* is a union without an associated indicator which member (if any) it holds,
8458 so that the programmer has to keep track.
8459 Naked unions are a source of type errors.
8461 ##### Example, bad
8463     union Value {
8464         int x;
8465         double d;
8466     };
8468     Value v;
8469     v.d = 987.654;  // v holds a double
8471 So far, so good, but we can easily misuse the `union`:
8473     cout << v.x << '\n';    // BAD, undefined behavior: v holds a double, but we read it as an int
8475 Note that the type error happened without any explicit cast.
8476 When we tested that program the last value printed was `1683627180` which is the integer value for the bit pattern for `987.654`.
8477 What we have here is an "invisible" type error that happens to give a result that could easily look innocent.
8479 And, talking about "invisible", this code produced no output:
8481     v.x = 123;
8482     cout << v.d << '\n';    // BAD: undefined behavior
8484 ##### Alternative
8486 Wrap a `union` in a class together with a type field.
8488 The C++17 `variant` type (found in `<variant>`) does that for you:
8490     variant<int, double> v;
8491     v = 123;        // v holds an int
8492     int x = get<int>(v);
8493     v = 123.456;    // v holds a double
8494     w = get<double>(v);
8496 ##### Enforcement
8500 ### <a name="Ru-anonymous"></a>C.182: Use anonymous `union`s to implement tagged unions
8502 ##### Reason
8504 A well-designed tagged union is type safe.
8505 An *anonymous* union simplifies the definition of a class with a (tag, union) pair.
8507 ##### Example
8509 This example is mostly borrowed from TC++PL4 pp216-218.
8510 You can look there for an explanation.
8512 The code is somewhat elaborate.
8513 Handling a type with user-defined assignment and destructor is tricky.
8514 Saving programmers from having to write such code is one reason for including `variant` in the standard.
8516     class Value { // two alternative representations represented as a union
8517     private:
8518         enum class Tag { number, text };
8519         Tag type; // discriminant
8521         union { // representation (note: anonymous union)
8522             int i;
8523             string s; // string has default constructor, copy operations, and destructor
8524         };
8525     public:
8526         struct Bad_entry { }; // used for exceptions
8528         ~Value();
8529         Value& operator=(const Value&);   // necessary because of the string variant
8530         Value(const Value&);
8531         // ...
8532         int number() const;
8533         string text() const;
8535         void set_number(int n);
8536         void set_text(const string&);
8537         // ...
8538     };
8540     int Value::number() const
8541     {
8542         if (type != Tag::number) throw Bad_entry{};
8543         return i;
8544     }
8546     string Value::text() const
8547     {
8548         if (type != Tag::text) throw Bad_entry{};
8549         return s;
8550     }
8552     void Value::set_number(int n)
8553     {
8554         if (type == Tag::text) {
8555             s.~string();      // explicitly destroy string
8556             type = Tag::number;
8557         }
8558         i = n;
8559     }
8561     void Value::set_text(const string& ss)
8562     {
8563         if (type == Tag::text)
8564             s = ss;
8565         else {
8566             new(&s) string{ss};   // placement new: explicitly construct string
8567             type = Tag::text;
8568         }
8569     }
8571     Value& Value::operator=(const Value& e)   // necessary because of the string variant
8572     {
8573         if (type == Tag::text && e.type == Tag::text) {
8574             s = e.s;    // usual string assignment
8575             return *this;
8576         }
8578         if (type == Tag::text) s.~string(); // explicit destroy
8580         switch (e.type) {
8581         case Tag::number:
8582             i = e.i;
8583             break;
8584         case Tag::text:
8585             new(&s) string(e.s);   // placement new: explicit construct
8586         }
8588         type = e.type;
8589         return *this;
8590     }
8592     Value::~Value()
8593     {
8594         if (type == Tag::text) s.~string(); // explicit destroy
8595     }
8597 ##### Enforcement
8601 ### <a name="Ru-pun"></a>C.183: Don't use a `union` for type punning
8603 ##### Reason
8605 It is undefined behavior to read a `union` member with a different type from the one with which it was written.
8606 Such punning is invisible, or at least harder to spot than using a named cast.
8607 Type punning using a `union` is a source of errors.
8609 ##### Example, bad
8611     union Pun {
8612         int x;
8613         unsigned char c[sizeof(int)];
8614     };
8616 The idea of `Pun` is to be able to look at the character representation of an `int`.
8618     void bad(Pun& u)
8619     {
8620         u.x = 'x';
8621         cout << u.c[0] << '\n';     // undefined behavior
8622     }
8624 If you wanted to see the bytes of an `int`, use a (named) cast:
8626     void if_you_must_pun(int& x)
8627     {
8628         auto p = reinterpret_cast<unsigned char*>(&x);
8629         cout << p[0] << '\n';     // OK; better
8630         // ...
8631     }
8633 Accessing the result of an `reinterpret_cast` to a different type from the objects declared type is defined behavior (even though `reinterpret_cast` is discouraged),
8634 but at least we can see that something tricky is going on.
8636 ##### Note
8638 Unfortunately, `union`s are commonly used for type punning.
8639 We don't consider "sometimes, it works as expected" a strong argument.
8641 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.
8643 ##### Enforcement
8649 # <a name="S-enum"></a>Enum: Enumerations
8651 Enumerations are used to define sets of integer values and for defining types for such sets of values.
8652 There are two kind of enumerations, "plain" `enum`s and `class enum`s.
8654 Enumeration rule summary:
8656 * [Enum.1: Prefer enumerations over macros](#Renum-macro)
8657 * [Enum.2: Use enumerations to represent sets of related named constants](#Renum-set)
8658 * [Enum.3: Prefer `enum class`es over "plain" `enum`s](#Renum-class)
8659 * [Enum.4: Define operations on enumerations for safe and simple use](#Renum-oper)
8660 * [Enum.5: Don't use `ALL_CAPS` for enumerators](#Renum-caps)
8661 * [Enum.6: Avoid unnamed enumerations](#Renum-unnamed)
8662 * [Enum.7: Specify the underlying type of an enumeration only when necessary](#Renum-underlying)
8663 * [Enum.8: Specify enumerator values only when necessary](#Renum-value)
8665 ### <a name="Renum-macro"></a>Enum.1: Prefer enumerations over macros
8667 ##### Reason
8669 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.
8671 ##### Example
8673 First some bad old code:
8675     // webcolors.h (third party header)
8676     #define RED   0xFF0000
8677     #define GREEN 0x00FF00
8678     #define BLUE  0x0000FF
8680     // productinfo.h
8681     // The following define product subtypes based on color
8682     #define RED    0
8683     #define PURPLE 1
8684     #define BLUE   2
8686     int webby = BLUE;   // webby == 2; probably not what was desired
8688 Instead use an `enum`:
8690     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
8691     enum class Product_info { red = 0, purple = 1, blue = 2 };
8693     int webby = blue;   // error: be specific
8694     Web_color webby = Web_color::blue;
8696 We used an `enum class` to avoid name clashes.
8698 ##### Enforcement
8700 Flag macros that define integer values.
8703 ### <a name="Renum-set"></a>Enum.2: Use enumerations to represent sets of related named constants
8705 ##### Reason
8707 An enumeration shows the enumerators to be related and can be a named type.
8711 ##### Example
8713     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
8716 ##### Note
8718 Switching on an enumeration is common and the compiler can warn against unusual patterns of case labels. For example:
8720     enum class Product_info { red = 0, purple = 1, blue = 2 };
8722     void print(Product_info inf)
8723     {
8724         switch (inf) {
8725         case Product_info::red: cout << "red"; break;
8726         case Product_info::purple: cout << "purple"; break;
8727         }
8728     }
8730 Such off-by-one `switch`-statements are often the results of an added enumerator and insufficient testing.
8732 ##### Enforcement
8734 * Flag `switch`-statements where the `case`s cover most but not all enumerators of an enumeration.
8735 * Flag `switch`-statements where the `case`s cover a few enumerators of an enumeration, but has no `default`.
8738 ### <a name="Renum-class"></a>Enum.3: Prefer class enums over "plain" enums
8740 ##### Reason
8742 To minimize surprises: traditional enums convert to int too readily.
8744 ##### Example
8746     void Print_color(int color);
8748     enum Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
8749     enum Product_info { Red = 0, Purple = 1, Blue = 2 };
8751     Web_color webby = Web_color::blue;
8753     // Clearly at least one of these calls is buggy.
8754     Print_color(webby);
8755     Print_color(Product_info::Blue);
8757 Instead use an `enum class`:
8759     void Print_color(int color);
8761     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
8762     enum class Product_info { red = 0, purple = 1, blue = 2 };
8764     Web_color webby = Web_color::blue;
8765     Print_color(webby);  // Error: cannot convert Web_color to int.
8766     Print_color(Product_info::Red);  // Error: cannot convert Product_info to int.
8768 ##### Enforcement
8770 (Simple) Warn on any non-class `enum` definition.
8772 ### <a name="Renum-oper"></a>Enum.4: Define operations on enumerations for safe and simple use
8774 ##### Reason
8776 Convenience of use and avoidance of errors.
8778 ##### Example
8780     enum Day { mon, tue, wed, thu, fri, sat, sun };
8782     Day& operator++(Day& d)
8783     {
8784         return d = (d == Day::sun) ? Day::mon : static_cast<Day>(static_cast<int>(d)+1);
8785     }
8787     Day today = Day::sat;
8788     Day tomorrow = ++today;
8790 The use of a `static_cast` is not pretty, but
8792     Day& operator++(Day& d)
8793     {
8794         return d = (d == Day::sun) ? Day::mon : Day{++d};    // error
8795     }
8797 is an infinite recursion, and writing it without a cast, using a `switch` on all cases is long-winded.
8800 ##### Enforcement
8802 Flag repeated expressions cast back into an enumeration.
8805 ### <a name="Renum-caps"></a>Enum.5: Don't use `ALL_CAPS` for enumerators
8807 ##### Reason
8809 Avoid clashes with macros.
8811 ##### Example, bad
8813      // webcolors.h (third party header)
8814     #define RED   0xFF0000
8815     #define GREEN 0x00FF00
8816     #define BLUE  0x0000FF
8818     // productinfo.h
8819     // The following define product subtypes based on color
8821     enum class Product_info { RED, PURPLE, BLUE };   // syntax error
8823 ##### Enforcement
8825 Flag ALL_CAPS enumerators.
8827 ### <a name="Renum-unnamed"></a>Enum.6: Avoid unnamed enumerations
8829 ##### Reason
8831 If you can't name an enumeration, the values are not related
8833 ##### Example, bad
8835     enum { red = 0xFF0000, scale = 4, is_signed = 1 };
8837 Such code is not uncommon in code written before there were convenient alternative ways of specifying integer constants.
8839 ##### Alternative
8841 Use `constexpr` values instead. For example:
8843     constexpr int red = 0xFF0000;
8844     constexpr short scale = 4;
8845     constexpr bool is_signed = true;
8847 ##### Enforcement
8849 Flag unnamed enumerations.
8852 ### <a name="Renum-underlying"></a>Enum.7: Specify the underlying type of an enumeration only when necessary
8854 ##### Reason
8856 The default is the easiest to read and write.
8857 `int` is the default integer type.
8858 `int` is compatible with C `enum`s.
8860 ##### Example
8862     enum class Direction : char { n, s, e, w,
8863                                   ne, nw, se, sw };  // underlying type saves space
8865     enum class Web_color : int32_t { red   = 0xFF0000,
8866                                      green = 0x00FF00,
8867                                      blue  = 0x0000FF };  // underlying type is redundant
8869 ##### Note
8871 Specifying the underlying type is necessary in forward declarations of enumerations:
8873     enum Flags : char;
8875     void f(Flags);
8877     // ....
8879     enum flags : char { /* ... */ };
8882 ##### Enforcement
8884 ????
8887 ### <a name="Renum-value"></a>Enum.8: Specify enumerator values only when necessary
8889 ##### Reason
8891 It's the simplest.
8892 It avoids duplicate enumerator values.
8893 The default gives a consecutive set of values that is good for `switch`-statement implementations.
8895 ##### Example
8897     enum class Col1 { red, yellow, blue };
8898     enum class Col2 { red = 1, yellow = 2, blue = 2 }; // typo
8899     enum class Month { jan = 1, feb, mar, apr, may, jun,
8900                        jul, august, sep, oct, nov, dec }; // starting with 1 is conventional
8901     enum class Base_flag { dec = 1, oct = dec << 1, hex = dec << 2 }; // set of bits
8903 Specifying values is necessary to match conventional values (e.g., `Month`)
8904 and where consecutive values are undesirable (e.g., to get separate bits as in `Base_flag`).
8906 ##### Enforcement
8908 * Flag duplicate enumerator values
8909 * Flag explicitly specified all-consecutive enumerator values
8912 # <a name="S-resource"></a>R: Resource management
8914 This section contains rules related to resources.
8915 A resource is anything that must be acquired and (explicitly or implicitly) released, such as memory, file handles, sockets, and locks.
8916 The reason it must be released is typically that it can be in short supply, so even delayed release may do harm.
8917 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.
8918 An entity that is responsible for releasing a resource is called an owner.
8920 There are a few cases where leaks can be acceptable or even optimal:
8921 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.
8922 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.
8923 Here, we ignore such cases.
8925 * Resource management rule summary:
8927   * [R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)](#Rr-raii)
8928   * [R.2: In interfaces, use raw pointers to denote individual objects (only)](#Rr-use-ptr)
8929   * [R.3: A raw pointer (a `T*`) is non-owning](#Rr-ptr)
8930   * [R.4: A raw reference (a `T&`) is non-owning](#Rr-ref)
8931   * [R.5: Prefer scoped objects, don't heap-allocate unnecessarily](#Rr-scoped)
8932   * [R.6: Avoid non-`const` global variables](#Rr-global)
8934 * Allocation and deallocation rule summary:
8936   * [R.10: Avoid `malloc()` and `free()`](#Rr-mallocfree)
8937   * [R.11: Avoid calling `new` and `delete` explicitly](#Rr-newdelete)
8938   * [R.12: Immediately give the result of an explicit resource allocation to a manager object](#Rr-immediate-alloc)
8939   * [R.13: Perform at most one explicit resource allocation in a single expression statement](#Rr-single-alloc)
8940   * [R.14: Avoid `[]` parameters, prefer `span`](#Rr-ap)
8941   * [R.15: Always overload matched allocation/deallocation pairs](#Rr-pair)
8943 * <a name="Rr-summary-smartptrs"></a>Smart pointer rule summary:
8945   * [R.20: Use `unique_ptr` or `shared_ptr` to represent ownership](#Rr-owner)
8946   * [R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership](#Rr-unique)
8947   * [R.22: Use `make_shared()` to make `shared_ptr`s](#Rr-make_shared)
8948   * [R.23: Use `make_unique()` to make `unique_ptr`s](#Rr-make_unique)
8949   * [R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s](#Rr-weak_ptr)
8950   * [R.30: Take smart pointers as parameters only to explicitly express lifetime semantics](#Rr-smartptrparam)
8951   * [R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`](#Rr-smart)
8952   * [R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`](#Rr-uniqueptrparam)
8953   * [R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the `widget`](#Rr-reseat)
8954   * [R.34: Take a `shared_ptr<widget>` parameter to express that a function is part owner](#Rr-sharedptrparam-owner)
8955   * [R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer](#Rr-sharedptrparam)
8956   * [R.36: Take a `const shared_ptr<widget>&` parameter to express that it might retain a reference count to the object ???](#Rr-sharedptrparam-const)
8957   * [R.37: Do not pass a pointer or reference obtained from an aliased smart pointer](#Rr-smartptrget)
8959 ### <a name="Rr-raii"></a>R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)
8961 ##### Reason
8963 To avoid leaks and the complexity of manual resource management.
8964 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`.
8965 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.
8967 ##### Example, bad
8969 Consider:
8971     void send(X* x, cstring_span destination)
8972     {
8973         auto port = open_port(destination);
8974         my_mutex.lock();
8975         // ...
8976         send(port, x);
8977         // ...
8978         my_mutex.unlock();
8979         close_port(port);
8980         delete x;
8981     }
8983 In this code, you have to remember to `unlock`, `close_port`, and `delete` on all paths, and do each exactly once.
8984 Further, if any of the code marked `...` throws an exception, then `x` is leaked and `my_mutex` remains locked.
8986 ##### Example
8988 Consider:
8990     void send(unique_ptr<X> x, cstring_span destination)  // x owns the X
8991     {
8992         Port port{destination};            // port owns the PortHandle
8993         lock_guard<mutex> guard{my_mutex}; // guard owns the lock
8994         // ...
8995         send(port, x);
8996         // ...
8997     } // automatically unlocks my_mutex and deletes the pointer in x
8999 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.
9001 What is `Port`? A handy wrapper that encapsulates the resource:
9003     class Port {
9004         PortHandle port;
9005     public:
9006         Port(cstring_span destination) : port{open_port(destination)} { }
9007         ~Port() { close_port(port); }
9008         operator PortHandle() { return port; }
9010         // port handles can't usually be cloned, so disable copying and assignment if necessary
9011         Port(const Port&) = delete;
9012         Port& operator=(const Port&) = delete;
9013     };
9015 ##### Note
9017 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)
9019 **See also**: [RAII](#Rr-raii)
9021 ### <a name="Rr-use-ptr"></a>R.2: In interfaces, use raw pointers to denote individual objects (only)
9023 ##### Reason
9025 Arrays are best represented by a container type (e.g., `vector` (owning)) or a `span` (non-owning).
9026 Such containers and views hold sufficient information to do range checking.
9028 ##### Example, bad
9030     void f(int* p, int n)   // n is the number of elements in p[]
9031     {
9032         // ...
9033         p[2] = 7;   // bad: subscript raw pointer
9034         // ...
9035     }
9037 The compiler does not read comments, and without reading other code you do not know whether `p` really points to `n` elements.
9038 Use a `span` instead.
9040 ##### Example
9042     void g(int* p, int fmt)   // print *p using format #fmt
9043     {
9044         // ... uses *p and p[0] only ...
9045     }
9047 ##### Exception
9049 C-style strings are passed as single pointers to a zero-terminated sequence of characters.
9050 Use `zstring` rather than `char*` to indicate that you rely on that convention.
9052 ##### Note
9054 Many current uses of pointers to a single element could be references.
9055 However, where `nullptr` is a possible value, a reference may not be a reasonable alternative.
9057 ##### Enforcement
9059 * Flag pointer arithmetic (including `++`) on a pointer that is not part of a container, view, or iterator.
9060   This rule would generate a huge number of false positives if applied to an older code base.
9061 * Flag array names passed as simple pointers
9063 ### <a name="Rr-ptr"></a>R.3: A raw pointer (a `T*`) is non-owning
9065 ##### Reason
9067 There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning.
9068 We want owning pointers identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
9070 ##### Example
9072     void f()
9073     {
9074         int* p1 = new int{7};           // bad: raw owning pointer
9075         auto p2 = make_unique<int>(7);  // OK: the int is owned by a unique pointer
9076         // ...
9077     }
9079 The `unique_ptr` protects against leaks by guaranteeing the deletion of its object (even in the presence of exceptions). The `T*` does not.
9081 ##### Example
9083     template<typename T>
9084     class X {
9085         // ...
9086     public:
9087         T* p;   // bad: it is unclear whether p is owning or not
9088         T* q;   // bad: it is unclear whether q is owning or not
9089     };
9091 We can fix that problem by making ownership explicit:
9093     template<typename T>
9094     class X2 {
9095         // ...
9096     public:
9097         owner<T*> p;  // OK: p is owning
9098         T* q;         // OK: q is not owning
9099     };
9101 ##### Exception
9103 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.
9104 The fact that there are billions of lines of code that violate this rule against owning `T*`s cannot be ignored.
9105 We'd love to see program transformation tools turning 20-year-old "legacy" code into shiny modern code,
9106 we encourage the development, deployment and use of such tools,
9107 we hope the guidelines will help the development of such tools,
9108 and we even contributed (and contribute) to the research and development in this area.
9109 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.
9111 This code cannot all be rewritten (ever assuming good code transformation software), especially not soon.
9112 This problem cannot be solved (at scale) by transforming all owning pointers to `unique_ptr`s and `shared_ptr`s,
9113 partly because we need/use owning "raw pointers" as well as simple pointers in the implementation of our fundamental resource handles.
9114 For example, common `vector` implementations have one owning pointer and two non-owning pointers.
9115 Many ABIs (and essentially all interfaces to C code) use `T*`s, some of them owning.
9116 Some interfaces cannot be simply annotated with `owner` because they need to remain compilable as C
9117 (although this would be a rare good use for a macro, that expands to `owner` in C++ mode only).
9119 ##### Note
9121 `owner<T*>` has no default semantics beyond `T*`. It can be used without changing any code using it and without affecting ABIs.
9122 It is simply an indicator to programmers and analysis tools.
9123 For example, if an `owner<T*>` is a member of a class, that class better have a destructor that `delete`s it.
9125 ##### Example, bad
9127 Returning a (raw) pointer imposes a lifetime management uncertainty on the caller; that is, who deletes the pointed-to object?
9129     Gadget* make_gadget(int n)
9130     {
9131         auto p = new Gadget{n};
9132         // ...
9133         return p;
9134     }
9136     void caller(int n)
9137     {
9138         auto p = make_gadget(n);   // remember to delete p
9139         // ...
9140         delete p;
9141     }
9143 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)):
9145     Gadget make_gadget(int n)
9146     {
9147         Gadget g{n};
9148         // ...
9149         return g;
9150     }
9152 ##### Note
9154 This rule applies to factory functions.
9156 ##### Note
9158 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."
9160 ##### Enforcement
9162 * (Simple) Warn on `delete` of a raw pointer that is not an `owner<T>`.
9163 * (Moderate) Warn on failure to either `reset` or explicitly `delete` an `owner<T>` pointer on every code path.
9164 * (Simple) Warn if the return value of `new` is assigned to a raw pointer.
9165 * (Simple) Warn if a function returns an object that was allocated within the function but has a move constructor.
9166   Suggest considering returning it by value instead.
9168 ### <a name="Rr-ref"></a>R.4: A raw reference (a `T&`) is non-owning
9170 ##### Reason
9172 There is nothing (in the C++ standard or in most code) to say otherwise and most raw references are non-owning.
9173 We want owners identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
9175 ##### Example
9177     void f()
9178     {
9179         int& r = *new int{7};  // bad: raw owning reference
9180         // ...
9181         delete &r;             // bad: violated the rule against deleting raw pointers
9182     }
9184 **See also**: [The raw pointer rule](#Rr-ptr)
9186 ##### Enforcement
9188 See [the raw pointer rule](#Rr-ptr)
9190 ### <a name="Rr-scoped"></a>R.5: Prefer scoped objects, don't heap-allocate unnecessarily
9192 ##### Reason
9194 A scoped object is a local object, a global object, or a member.
9195 This implies that there is no separate allocation and deallocation cost in excess of that already used for the containing scope or object.
9196 The members of a scoped object are themselves scoped and the scoped object's constructor and destructor manage the members' lifetimes.
9198 ##### Example
9200 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:
9202     void f(int n)
9203     {
9204         auto p = new Gadget{n};
9205         // ...
9206         delete p;
9207     }
9209 Instead, use a local variable:
9211     void f(int n)
9212     {
9213         Gadget g{n};
9214         // ...
9215     }
9217 ##### Enforcement
9219 * (Moderate) Warn if an object is allocated and then deallocated on all paths within a function. Suggest it should be a local `auto` stack object instead.
9220 * (Simple) Warn if a local `Unique_ptr` or `Shared_ptr` is not moved, copied, reassigned or `reset` before its lifetime ends.
9222 ### <a name="Rr-global"></a>R.6: Avoid non-`const` global variables
9224 ##### Reason
9226 Global variables can be accessed from everywhere so they can introduce surprising dependencies between apparently unrelated objects.
9227 They are a notable source of errors.
9229 **Warning**: The initialization of global objects is not totally ordered.
9230 If you use a global object initialize it with a constant.
9231 Note that it is possible to get undefined initialization order even for `const` objects.
9233 ##### Exception
9235 A global object is often better than a singleton.
9237 ##### Exception
9239 An immutable (`const`) global does not introduce the problems we try to avoid by banning global objects.
9241 ##### Enforcement
9243 (??? NM: Obviously we can warn about non-`const` statics ... do we want to?)
9245 ## <a name="SS-alloc"></a>R.alloc: Allocation and deallocation
9247 ### <a name="Rr-mallocfree"></a>R.10: Avoid `malloc()` and `free()`
9249 ##### Reason
9251  `malloc()` and `free()` do not support construction and destruction, and do not mix well with `new` and `delete`.
9253 ##### Example
9255     class Record {
9256         int id;
9257         string name;
9258         // ...
9259     };
9261     void use()
9262     {
9263         // p1 may be nullptr
9264         // *p1 is not initialized; in particular,
9265         // that string isn't a string, but a string-sized bag of bits
9266         Record* p1 = static_cast<Record*>(malloc(sizeof(Record)));
9268         auto p2 = new Record;
9270         // unless an exception is thrown, *p2 is default initialized
9271         auto p3 = new(nothrow) Record;
9272         // p3 may be nullptr; if not, *p3 is default initialized
9274         // ...
9276         delete p1;    // error: cannot delete object allocated by malloc()
9277         free(p2);    // error: cannot free() object allocated by new
9278     }
9280 In some implementations that `delete` and that `free()` might work, or maybe they will cause run-time errors.
9282 ##### Exception
9284 There are applications and sections of code where exceptions are not acceptable.
9285 Some of the best such examples are in life-critical hard-real-time code.
9286 Beware that many bans on exception use are based on superstition (bad)
9287 or by concerns for older code bases with unsystematic resource management (unfortunately, but sometimes necessary).
9288 In such cases, consider the `nothrow` versions of `new`.
9290 ##### Enforcement
9292 Flag explicit use of `malloc` and `free`.
9294 ### <a name="Rr-newdelete"></a>R.11: Avoid calling `new` and `delete` explicitly
9296 ##### Reason
9298 The pointer returned by `new` should belong to a resource handle (that can call `delete`).
9299 If the pointer returned by `new` is assigned to a plain/naked pointer, the object can be leaked.
9301 ##### Note
9303 In a large program, a naked `delete` (that is a `delete` in application code, rather than part of code devoted to resource management)
9304 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?
9305 The bug may be latent: it may emerge only during maintenance.
9306 If you have a naked `new`, you probably need a naked `delete` somewhere, so you probably have a bug.
9308 ##### Enforcement
9310 (Simple) Warn on any explicit use of `new` and `delete`. Suggest using `make_unique` instead.
9312 ### <a name="Rr-immediate-alloc"></a>R.12: Immediately give the result of an explicit resource allocation to a manager object
9314 ##### Reason
9316 If you don't, an exception or a return may lead to a leak.
9318 ##### Example, bad
9320     void f(const string& name)
9321     {
9322         FILE* f = fopen(name, "r");            // open the file
9323         vector<char> buf(1024);
9324         auto _ = finally([f] { fclose(f); });  // remember to close the file
9325         // ...
9326     }
9328 The allocation of `buf` may fail and leak the file handle.
9330 ##### Example
9332     void f(const string& name)
9333     {
9334         ifstream f{name};   // open the file
9335         vector<char> buf(1024);
9336         // ...
9337     }
9339 The use of the file handle (in `ifstream`) is simple, efficient, and safe.
9341 ##### Enforcement
9343 * Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?)
9345 ### <a name="Rr-single-alloc"></a>R.13: Perform at most one explicit resource allocation in a single expression statement
9347 ##### Reason
9349 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.
9351 ##### Example
9353     void fun(shared_ptr<Widget> sp1, shared_ptr<Widget> sp2);
9355 This `fun` can be called like this:
9357     // BAD: potential leak
9358     fun(shared_ptr<Widget>(new Widget(a, b)), shared_ptr<Widget>(new Widget(c, d)));
9360 This is exception-unsafe because the compiler may reorder the two expressions building the function's two arguments.
9361 In particular, the compiler can interleave execution of the two expressions:
9362 Memory allocation (by calling `operator new`) could be done first for both objects, followed by attempts to call the two `Widget` constructors.
9363 If one of the constructor calls throws an exception, then the other object's memory will never be released!
9365 This subtle problem has a simple solution: Never perform more than one explicit resource allocation in a single expression statement.
9366 For example:
9368     shared_ptr<Widget> sp1(new Widget(a, b)); // Better, but messy
9369     fun(sp1, new Widget(c, d));
9371 The best solution is to avoid explicit allocation entirely use factory functions that return owning objects:
9373     fun(make_shared<Widget>(a, b), make_shared<Widget>(c, d)); // Best
9375 Write your own factory wrapper if there is not one already.
9377 ##### Enforcement
9379 * Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?)
9381 ### <a name="Rr-ap"></a>R.14: Avoid `[]` parameters, prefer `span`
9383 ##### Reason
9385 An array decays to a pointer, thereby losing its size, opening the opportunity for range errors.
9386 Use `span` to preserve size information.
9388 ##### Example
9390     void f(int[]);          // not recommended
9392     void f(int*);           // not recommended for multiple objects
9393                             // (a pointer should point to a single object, do not subscript)
9395     void f(gsl::span<int>); // good, recommended
9397 ##### Enforcement
9399 Flag `[]` parameters. Use `span` instead.
9401 ### <a name="Rr-pair"></a>R.15: Always overload matched allocation/deallocation pairs
9403 ##### Reason
9405 Otherwise you get mismatched operations and chaos.
9407 ##### Example
9409     class X {
9410         // ...
9411         void* operator new(size_t s);
9412         void operator delete(void*);
9413         // ...
9414     };
9416 ##### Note
9418 If you want memory that cannot be deallocated, `=delete` the deallocation operation.
9419 Don't leave it undeclared.
9421 ##### Enforcement
9423 Flag incomplete pairs.
9425 ## <a name="SS-smart"></a>R.smart: Smart pointers
9427 ### <a name="Rr-owner"></a>R.20: Use `unique_ptr` or `shared_ptr` to represent ownership
9429 ##### Reason
9431 They can prevent resource leaks.
9433 ##### Example
9435 Consider:
9437     void f()
9438     {
9439         X x;
9440         X* p1 { new X };              // see also ???
9441         unique_ptr<T> p2 { new X };   // unique ownership; see also ???
9442         shared_ptr<T> p3 { new X };   // shared ownership; see also ???
9443         auto p4 = make_unique<X>();   // unique_ownership, preferable to the explicit use "new"
9444         auto p5 = make_shared<X>();   // shared ownership, preferable to the explicit use "new"
9445     }
9447 This will leak the object used to initialize `p1` (only).
9449 ##### Enforcement
9451 (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
9453 ### <a name="Rr-unique"></a>R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership
9455 ##### Reason
9457 A `unique_ptr` is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count).
9459 ##### Example, bad
9461 This needlessly adds and maintains a reference count.
9463     void f()
9464     {
9465         shared_ptr<Base> base = make_shared<Derived>();
9466         // use base locally, without copying it -- refcount never exceeds 1
9467     } // destroy base
9469 ##### Example
9471 This is more efficient:
9473     void f()
9474     {
9475         unique_ptr<Base> base = make_unique<Derived>();
9476         // use base locally
9477     } // destroy base
9479 ##### Enforcement
9481 (Simple) Warn if a function uses a `Shared_ptr` with an object allocated within the function, but never returns the `Shared_ptr` or passes it to a function requiring a `Shared_ptr&`. Suggest using `unique_ptr` instead.
9483 ### <a name="Rr-make_shared"></a>R.22: Use `make_shared()` to make `shared_ptr`s
9485 ##### Reason
9487 If you first make an object and then give it to a `shared_ptr` constructor, you (most likely) do one more allocation (and later deallocation) than if you use `make_shared()` because the reference counts must be allocated separately from the object.
9489 ##### Example
9491 Consider:
9493     shared_ptr<X> p1 { new X{2} }; // bad
9494     auto p = make_shared<X>(2);    // good
9496 The `make_shared()` version mentions `X` only once, so it is usually shorter (as well as faster) than the version with the explicit `new`.
9498 ##### Enforcement
9500 (Simple) Warn if a `shared_ptr` is constructed from the result of `new` rather than `make_shared`.
9502 ### <a name="Rr-make_unique"></a>R.23: Use `make_unique()` to make `unique_ptr`s
9504 ##### Reason
9506 For convenience and consistency with `shared_ptr`.
9508 ##### Note
9510 `make_unique()` is C++14, but widely available (as well as simple to write).
9512 ##### Enforcement
9514 (Simple) Warn if a `unique_ptr` is constructed from the result of `new` rather than `make_unique`.
9516 ### <a name="Rr-weak_ptr"></a>R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s
9518 ##### Reason
9520  `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
9521 be able to destroy a cyclic structure.
9523 ##### Example
9525     #include <memory>
9527     class bar;
9529     class foo
9530     {
9531     public:
9532       explicit foo(const std::shared_ptr<bar>& forward_reference)
9533         : forward_reference_(forward_reference)
9534       { }
9535     private:
9536       std::shared_ptr<bar> forward_reference_;
9537     };
9539     class bar
9540     {
9541     public:
9542       explicit bar(const std::weak_ptr<foo>& back_reference)
9543         : back_reference_(back_reference)
9544       { }
9545       void do_something()
9546       {
9547         if (auto shared_back_reference = back_reference_.lock()) {
9548           // Use *shared_back_reference
9549         }
9550       }
9551     private:
9552       std::weak_ptr<foo> back_reference_;
9553     };
9555 ##### Note
9557  ??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.)
9558 ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it.
9559 You could "temporarily share ownership" simply by using another `shared_ptr`.)
9561 ##### Enforcement
9563 ??? probably impossible. If we could statically detect cycles, we wouldn't need `weak_ptr`
9565 ### <a name="Rr-smartptrparam"></a>R.30: Take smart pointers as parameters only to explicitly express lifetime semantics
9567 ##### Reason
9569 Accepting a smart pointer to a `widget` is wrong if the function just needs the `widget` itself.
9570 It should be able to accept any `widget` object, not just ones whose lifetimes are managed by a particular kind of smart pointer.
9571 A function that does not manipulate lifetime should take raw pointers or references instead.
9573 ##### Example, bad
9575     // callee
9576     void f(shared_ptr<widget>& w)
9577     {
9578         // ...
9579         use(*w); // only use of w -- the lifetime is not used at all
9580         // ...
9581     };
9583     // caller
9584     shared_ptr<widget> my_widget = /* ... */;
9585     f(my_widget);
9587     widget stack_widget;
9588     f(stack_widget); // error
9590 ##### Example, good
9592     // callee
9593     void f(widget& w)
9594     {
9595         // ...
9596         use(w);
9597         // ...
9598     };
9600     // caller
9601     shared_ptr<widget> my_widget = /* ... */;
9602     f(*my_widget);
9604     widget stack_widget;
9605     f(stack_widget); // ok -- now this works
9607 ##### Enforcement
9609 * (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()`.
9610   Suggest using a `T*` or `T&` instead.
9611 * 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.
9612   Suggest using a `T*` or `T&` instead.
9614 ### <a name="Rr-smart"></a>R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`
9616 ##### Reason
9618 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.
9619 You want the rules to work on all the smart pointers you use.
9621 Any type (including primary template or specialization) that overloads unary `*` and `->` is considered a smart pointer:
9623 * If it is copyable, it is recognized as a reference-counted `shared_ptr`.
9624 * If it is not copyable, it is recognized as a unique `unique_ptr`.
9626 ##### Example
9628     // use Boost's intrusive_ptr
9629     #include <boost/intrusive_ptr.hpp>
9630     void f(boost::intrusive_ptr<widget> p)  // error under rule 'sharedptrparam'
9631     {
9632         p->foo();
9633     }
9635     // use Microsoft's CComPtr
9636     #include <atlbase.h>
9637     void f(CComPtr<widget> p)               // error under rule 'sharedptrparam'
9638     {
9639         p->foo();
9640     }
9642 Both cases are an error under the [`sharedptrparam` guideline](#Rr-smartptrparam):
9643 `p` is a `Shared_ptr`, but nothing about its sharedness is used here and passing it by value is a silent pessimization;
9644 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&`.
9645 These smart pointers match the `Shared_ptr` concept, so these guideline enforcement rules work on them out of the box and expose this common pessimization.
9647 ### <a name="Rr-uniqueptrparam"></a>R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`
9649 ##### Reason
9651 Using `unique_ptr` in this way both documents and enforces the function call's ownership transfer.
9653 ##### Example
9655     void sink(unique_ptr<widget>); // takes ownership of the widget
9657     void uses(widget*);            // just uses the widget
9659 ##### Example, bad
9661     void thinko(const unique_ptr<widget>&); // usually not what you want
9663 ##### Enforcement
9665 * (Simple) Warn if a function takes a `Unique_ptr<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.
9666 * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr<T>` parameter by reference to `const`. Suggest taking a `const T*` or `const T&` instead.
9668 ### <a name="Rr-reseat"></a>R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the`widget`
9670 ##### Reason
9672 Using `unique_ptr` in this way both documents and enforces the function call's reseating semantics.
9674 ##### Note
9676 "reseat" means "making a pointer or a smart pointer refer to a different object."
9678 ##### Example
9680     void reseat(unique_ptr<widget>&); // "will" or "might" reseat pointer
9682 ##### Example, bad
9684     void thinko(const unique_ptr<widget>&); // usually not what you want
9686 ##### Enforcement
9688 * (Simple) Warn if a function takes a `Unique_ptr<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.
9689 * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr<T>` parameter by reference to `const`. Suggest taking a `const T*` or `const T&` instead.
9691 ### <a name="Rr-sharedptrparam-owner"></a>R.34: Take a `shared_ptr<widget>` parameter to express that a function is part owner
9693 ##### Reason
9695 This makes the function's ownership sharing explicit.
9697 ##### Example, good
9699     void share(shared_ptr<widget>);            // share -- "will" retain refcount
9701     void may_share(const shared_ptr<widget>&); // "might" retain refcount
9703     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
9705 ##### Enforcement
9707 * (Simple) Warn if a function takes a `Shared_ptr<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.
9708 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by value or by reference to `const` and does not copy or move it to another `Shared_ptr` on at least one code path. Suggest taking a `T*` or `T&` instead.
9709 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
9711 ### <a name="Rr-sharedptrparam"></a>R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer
9713 ##### Reason
9715 This makes the function's reseating explicit.
9717 ##### Note
9719 "reseat" means "making a reference or a smart pointer refer to a different object."
9721 ##### Example, good
9723     void share(shared_ptr<widget>);            // share -- "will" retain refcount
9725     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
9727     void may_share(const shared_ptr<widget>&); // "might" retain refcount
9729 ##### Enforcement
9731 * (Simple) Warn if a function takes a `Shared_ptr<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.
9732 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by value or by reference to `const` and does not copy or move it to another `Shared_ptr` on at least one code path. Suggest taking a `T*` or `T&` instead.
9733 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
9735 ### <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 ???
9737 ##### Reason
9739 This makes the function's ??? explicit.
9741 ##### Example, good
9743     void share(shared_ptr<widget>);            // share -- "will" retain refcount
9745     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
9747     void may_share(const shared_ptr<widget>&); // "might" retain refcount
9749 ##### Enforcement
9751 * (Simple) Warn if a function takes a `Shared_ptr<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.
9752 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by value or by reference to `const` and does not copy or move it to another `Shared_ptr` on at least one code path. Suggest taking a `T*` or `T&` instead.
9753 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
9755 ### <a name="Rr-smartptrget"></a>R.37: Do not pass a pointer or reference obtained from an aliased smart pointer
9757 ##### Reason
9759 Violating this rule is the number one cause of losing reference counts and finding yourself with a dangling pointer.
9760 Functions should prefer to pass raw pointers and references down call chains.
9761 At the top of the call tree where you obtain the raw pointer or reference from a smart pointer that keeps the object alive.
9762 You need to be sure that the smart pointer cannot inadvertently be reset or reassigned from within the call tree below.
9764 ##### Note
9766 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.
9768 ##### Example
9770 Consider this code:
9772     // global (static or heap), or aliased local ...
9773     shared_ptr<widget> g_p = ...;
9775     void f(widget& w)
9776     {
9777         g();
9778         use(w);  // A
9779     }
9781     void g()
9782     {
9783         g_p = ...; // oops, if this was the last shared_ptr to that widget, destroys the widget
9784     }
9786 The following should not pass code review:
9788     void my_code()
9789     {
9790         // BAD: passing pointer or reference obtained from a nonlocal smart pointer
9791         //      that could be inadvertently reset somewhere inside f or it callees
9792         f(*g_p);
9794         // BAD: same reason, just passing it as a "this" pointer
9795         g_p->func();
9796     }
9798 The fix is simple -- take a local copy of the pointer to "keep a ref count" for your call tree:
9800     void my_code()
9801     {
9802         // cheap: 1 increment covers this entire function and all the call trees below us
9803         auto pin = g_p;
9805         // GOOD: passing pointer or reference obtained from a local unaliased smart pointer
9806         f(*pin);
9808         // GOOD: same reason
9809         pin->func();
9810     }
9812 ##### Enforcement
9814 * (Simple) Warn if a pointer or reference obtained from a smart pointer variable (`Unique_ptr` or `Shared_ptr`) that is nonlocal, or that is local but potentially aliased, is used in a function call. If the smart pointer is a `Shared_ptr` then suggest taking a local copy of the smart pointer and obtain a pointer or reference from that instead.
9816 # <a name="S-expr"></a>ES: Expressions and statements
9818 Expressions and statements are the lowest and most direct way of expressing actions and computation. Declarations in local scopes are statements.
9820 For naming, commenting, and indentation rules, see [NL: Naming and layout](#S-naming).
9822 General rules:
9824 * [ES.1: Prefer the standard library to other libraries and to "handcrafted code"](#Res-lib)
9825 * [ES.2: Prefer suitable abstractions to direct use of language features](#Res-abstr)
9827 Declaration rules:
9829 * [ES.5: Keep scopes small](#Res-scope)
9830 * [ES.6: Declare names in for-statement initializers and conditions to limit scope](#Res-cond)
9831 * [ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer](#Res-name-length)
9832 * [ES.8: Avoid similar-looking names](#Res-name-similar)
9833 * [ES.9: Avoid `ALL_CAPS` names](#Res-not-CAPS)
9834 * [ES.10: Declare one name (only) per declaration](#Res-name-one)
9835 * [ES.11: Use `auto` to avoid redundant repetition of type names](#Res-auto)
9836 * [ES.12: Do not reuse names in nested scopes](#Res-reuse)
9837 * [ES.20: Always initialize an object](#Res-always)
9838 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
9839 * [ES.22: Don't declare a variable until you have a value to initialize it with](#Res-init)
9840 * [ES.23: Prefer the `{}`-initializer syntax](#Res-list)
9841 * [ES.24: Use a `unique_ptr<T>` to hold pointers](#Res-unique)
9842 * [ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on](#Res-const)
9843 * [ES.26: Don't use a variable for two unrelated purposes](#Res-recycle)
9844 * [ES.27: Use `std::array` or `stack_array` for arrays on the stack](#Res-stack)
9845 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
9846 * [ES.30: Don't use macros for program text manipulation](#Res-macros)
9847 * [ES.31: Don't use macros for constants or "functions"](#Res-macros2)
9848 * [ES.32: Use `ALL_CAPS` for all macro names](#Res-ALL_CAPS)
9849 * [ES.33: If you must use macros, give them unique names](#Res-MACROS)
9850 * [ES.34: Don't define a (C-style) variadic function](#Res-ellipses)
9852 Expression rules:
9854 * [ES.40: Avoid complicated expressions](#Res-complicated)
9855 * [ES.41: If in doubt about operator precedence, parenthesize](#Res-parens)
9856 * [ES.42: Keep use of pointers simple and straightforward](#Res-ptr)
9857 * [ES.43: Avoid expressions with undefined order of evaluation](#Res-order)
9858 * [ES.44: Don't depend on order of evaluation of function arguments](#Res-order-fct)
9859 * [ES.45: Avoid "magic constants"; use symbolic constants](#Res-magic)
9860 * [ES.46: Avoid narrowing conversions](#Res-narrowing)
9861 * [ES.47: Use `nullptr` rather than `0` or `NULL`](#Res-nullptr)
9862 * [ES.48: Avoid casts](#Res-casts)
9863 * [ES.49: If you must use a cast, use a named cast](#Res-casts-named)
9864 * [ES.50: Don't cast away `const`](#Res-casts-const)
9865 * [ES.55: Avoid the need for range checking](#Res-range-checking)
9866 * [ES.56: Write `std::move()` only when you need to explicitly move an object to another scope](#Res-move)
9867 * [ES.60: Avoid `new` and `delete` outside resource management functions](#Res-new)
9868 * [ES.61: Delete arrays using `delete[]` and non-arrays using `delete`](#Res-del)
9869 * [ES.62: Don't compare pointers into different arrays](#Res-arr2)
9870 * [ES.63: Don't slice](#Res-slice)
9871 * [ES.64: Use the `T{e}`notation for construction](#Res-construct)
9872 * [ES.65: Don't dereference an invalid pointer](#Res-deref)
9874 Statement rules:
9876 * [ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice](#Res-switch-if)
9877 * [ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice](#Res-for-range)
9878 * [ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable](#Res-for-while)
9879 * [ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable](#Res-while-for)
9880 * [ES.74: Prefer to declare a loop variable in the initializer part of a `for`-statement](#Res-for-init)
9881 * [ES.75: Avoid `do`-statements](#Res-do)
9882 * [ES.76: Avoid `goto`](#Res-goto)
9883 * [ES.77: Minimize the use of `break` and `continue` in loops](#Res-continue)
9884 * [ES.78: Always end a non-empty `case` with a `break`](#Res-break)
9885 * [ES.79: Use `default` to handle common cases (only)](#Res-default)
9886 * [ES.84: Don't try to declare a local variable with no name](#Res-noname)
9887 * [ES.85: Make empty statements visible](#Res-empty)
9888 * [ES.86: Avoid modifying loop control variables inside the body of raw for-loops](#Res-loop-counter)
9889 * [ES.87: Don't add redundant `==` or `!=` to conditions](#Res-if)
9891 Arithmetic rules:
9893 * [ES.100: Don't mix signed and unsigned arithmetic](#Res-mix)
9894 * [ES.101: Use unsigned types for bit manipulation](#Res-unsigned)
9895 * [ES.102: Use signed types for arithmetic](#Res-signed)
9896 * [ES.103: Don't overflow](#Res-overflow)
9897 * [ES.104: Don't underflow](#Res-underflow)
9898 * [ES.105: Don't divide by zero](#Res-zero)
9899 * [ES.106: Don't try to avoid negative values by using `unsigned`](#Res-nonnegative)
9900 * [ES.107: Don't use `unsigned` for subscripts, prefer `gsl::index`](#Res-subscripts)
9902 ### <a name="Res-lib"></a>ES.1: Prefer the standard library to other libraries and to "handcrafted code"
9904 ##### Reason
9906 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.
9907 The ISO C++ Standard Library is among the most widely known and best tested libraries.
9908 It is available as part of all C++ implementations.
9910 ##### Example
9912     auto sum = accumulate(begin(a), end(a), 0.0);   // good
9914 a range version of `accumulate` would be even better:
9916     auto sum = accumulate(v, 0.0); // better
9918 but don't hand-code a well-known algorithm:
9920     int max = v.size();   // bad: verbose, purpose unstated
9921     double sum = 0.0;
9922     for (int i = 0; i < max; ++i)
9923         sum = sum + v[i];
9925 ##### Exception
9927 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.
9929 ##### Enforcement
9931 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
9933 ### <a name="Res-abstr"></a>ES.2: Prefer suitable abstractions to direct use of language features
9935 ##### Reason
9937 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.
9939 ##### Example
9941     vector<string> read1(istream& is)   // good
9942     {
9943         vector<string> res;
9944         for (string s; is >> s;)
9945             res.push_back(s);
9946         return res;
9947     }
9949 The more traditional and lower-level near-equivalent is longer, messier, harder to get right, and most likely slower:
9951     char** read2(istream& is, int maxelem, int maxstring, int* nread)   // bad: verbose and incomplete
9952     {
9953         auto res = new char*[maxelem];
9954         int elemcount = 0;
9955         while (is && elemcount < maxelem) {
9956             auto s = new char[maxstring];
9957             is.read(s, maxstring);
9958             res[elemcount++] = s;
9959         }
9960         nread = &elemcount;
9961         return res;
9962     }
9964 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.
9966 ##### Enforcement
9968 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
9970 ## ES.dcl: Declarations
9972 A declaration is a statement. A declaration introduces a name into a scope and may cause the construction of a named object.
9974 ### <a name="Res-scope"></a>ES.5: Keep scopes small
9976 ##### Reason
9978 Readability. Minimize resource retention. Avoid accidental misuse of value.
9980 **Alternative formulation**: Don't declare a name in an unnecessarily large scope.
9982 ##### Example
9984     void use()
9985     {
9986         int i;    // bad: i is needlessly accessible after loop
9987         for (i = 0; i < 20; ++i) { /* ... */ }
9988         // no intended use of i here
9989         for (int i = 0; i < 20; ++i) { /* ... */ }  // good: i is local to for-loop
9991         if (auto pc = dynamic_cast<Circle*>(ps)) {  // good: pc is local to if-statement
9992             // ... deal with Circle ...
9993         }
9994         else {
9995             // ... handle error ...
9996         }
9997     }
9999 ##### Example, bad
10001     void use(const string& name)
10002     {
10003         string fn = name + ".txt";
10004         ifstream is {fn};
10005         Record r;
10006         is >> r;
10007         // ... 200 lines of code without intended use of fn or is ...
10008     }
10010 This function is by most measure too long anyway, but the point is that the resources used by `fn` and the file handle held by `is`
10011 are retained for much longer than needed and that unanticipated use of `is` and `fn` could happen later in the function.
10012 In this case, it might be a good idea to factor out the read:
10014     Record load_record(const string& name)
10015     {
10016         string fn = name + ".txt";
10017         ifstream is {fn};
10018         Record r;
10019         is >> r;
10020         return r;
10021     }
10023     void use(const string& name)
10024     {
10025         Record r = load_record(name);
10026         // ... 200 lines of code ...
10027     }
10029 ##### Enforcement
10031 * Flag loop variable declared outside a loop and not used after the loop
10032 * Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N)
10034 ### <a name="Res-cond"></a>ES.6: Declare names in for-statement initializers and conditions to limit scope
10036 ##### Reason
10038 Readability. Minimize resource retention.
10040 ##### Example
10042     void use()
10043     {
10044         for (string s; cin >> s;)
10045             v.push_back(s);
10047         for (int i = 0; i < 20; ++i) {   // good: i is local to for-loop
10048             // ...
10049         }
10051         if (auto pc = dynamic_cast<Circle*>(ps)) {   // good: pc is local to if-statement
10052             // ... deal with Circle ...
10053         }
10054         else {
10055             // ... handle error ...
10056         }
10057     }
10059 ##### Enforcement
10061 * Flag loop variables declared before the loop and not used after the loop
10062 * (hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose.
10064 ##### C++17 and C++20 example
10066 Note: C++17 and C++20 also add `if`, `switch`, and range-`for` initializer statements. These require C++17 and C++20 support.
10068     map<int, string> mymap;
10070     if (auto result = mymap.insert(value); result.second) {
10071         // insert succeeded, and result is valid for this block
10072         use(result.first);  // ok
10073         // ...
10074     } // result is destroyed here
10076 ##### C++17 and C++20 enforcement (if using a C++17 or C++20 compiler)
10078 * Flag selection/loop variables declared before the body and not used after the body
10079 * (hard) Flag selection/loop variables declared before the body and used after the body for an unrelated purpose.
10083 ### <a name="Res-name-length"></a>ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer
10085 ##### Reason
10087 Readability. Lowering the chance of clashes between unrelated non-local names.
10089 ##### Example
10091 Conventional short, local names increase readability:
10093     template<typename T>    // good
10094     void print(ostream& os, const vector<T>& v)
10095     {
10096         for (gsl::index i = 0; i < v.size(); ++i)
10097             os << v[i] << '\n';
10098     }
10100 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
10102     template<typename Element_type>   // bad: verbose, hard to read
10103     void print(ostream& target_stream, const vector<Element_type>& current_vector)
10104     {
10105         for (gsl::index current_element_index = 0;
10106              current_element_index < current_vector.size();
10107              ++current_element_index
10108         )
10109         target_stream << current_vector[current_element_index] << '\n';
10110     }
10112 Yes, it is a caricature, but we have seen worse.
10114 ##### Example
10116 Unconventional and short non-local names obscure code:
10118     void use1(const string& s)
10119     {
10120         // ...
10121         tt(s);   // bad: what is tt()?
10122         // ...
10123     }
10125 Better, give non-local entities readable names:
10127     void use1(const string& s)
10128     {
10129         // ...
10130         trim_tail(s);   // better
10131         // ...
10132     }
10134 Here, there is a chance that the reader knows what `trim_tail` means and that the reader can remember it after looking it up.
10136 ##### Example, bad
10138 Argument names of large functions are de facto non-local and should be meaningful:
10140     void complicated_algorithm(vector<Record>& vr, const vector<int>& vi, map<string, int>& out)
10141     // read from events in vr (marking used Records) for the indices in
10142     // vi placing (name, index) pairs into out
10143     {
10144         // ... 500 lines of code using vr, vi, and out ...
10145     }
10147 We recommend keeping functions short, but that rule isn't universally adhered to and naming should reflect that.
10149 ##### Enforcement
10151 Check length of local and non-local names. Also take function length into account.
10153 ### <a name="Res-name-similar"></a>ES.8: Avoid similar-looking names
10155 ##### Reason
10157 Code clarity and readability. Too-similar names slow down comprehension and increase the likelihood of error.
10159 ##### Example, bad
10161     if (readable(i1 + l1 + ol + o1 + o0 + ol + o1 + I0 + l0)) surprise();
10163 ##### Example, bad
10165 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.
10167     struct foo { int n; };
10168     struct foo foo();       // BAD, foo is a type already in scope
10169     struct foo x = foo();   // requires disambiguation
10171 ##### Exception
10173 Antique header files might declare non-types and types with the same name in the same scope.
10175 ##### Enforcement
10177 * Check names against a list of known confusing letter and digit combinations.
10178 * Flag a declaration of a variable, function, or enumerator that hides a class or enumeration declared in the same scope.
10180 ### <a name="Res-not-CAPS"></a>ES.9: Avoid `ALL_CAPS` names
10182 ##### Reason
10184 Such names are commonly used for macros. Thus, `ALL_CAPS` name are vulnerable to unintended macro substitution.
10186 ##### Example
10188     // somewhere in some header:
10189     #define NE !=
10191     // somewhere else in some other header:
10192     enum Coord { N, NE, NW, S, SE, SW, E, W };
10194     // somewhere third in some poor programmer's .cpp:
10195     switch (direction) {
10196     case N:
10197         // ...
10198     case NE:
10199         // ...
10200     // ...
10201     }
10203 ##### Note
10205 Do not use `ALL_CAPS` for constants just because constants used to be macros.
10207 ##### Enforcement
10209 Flag all uses of ALL CAPS. For older code, accept ALL CAPS for macro names and flag all non-ALL-CAPS macro names.
10211 ### <a name="Res-name-one"></a>ES.10: Declare one name (only) per declaration
10213 ##### Reason
10215 One declaration per line increases readability and avoids mistakes related to
10216 the C/C++ grammar. It also leaves room for a more descriptive end-of-line
10217 comment.
10219 ##### Example, bad
10221     char *p, c, a[7], *pp[7], **aa[10];   // yuck!
10223 ##### Exception
10225 A function declaration can contain several function argument declarations.
10227 ##### Exception
10229 A structured binding (C++17) is specifically designed to introduce several variables:
10231     auto [iter, inserted] = m.insert_or_assign(k, val);
10232     if (inserted) { /* new entry was inserted */ }
10234 ##### Example
10236     template <class InputIterator, class Predicate>
10237     bool any_of(InputIterator first, InputIterator last, Predicate pred);
10239 or better using concepts:
10241     bool any_of(InputIterator first, InputIterator last, Predicate pred);
10243 ##### Example
10245     double scalbn(double x, int n);   // OK: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
10249     double scalbn(    // better: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
10250         double x,     // base value
10251         int n         // exponent
10252     );
10256     // better: base * pow(FLT_RADIX, exponent); FLT_RADIX is usually 2
10257     double scalbn(double base, int exponent);
10259 ##### Example
10261     int a = 7, b = 9, c, d = 10, e = 3;
10263 In a long list of declarators it is easy to overlook an uninitialized variable.
10265 ##### Enforcement
10267 Flag variable and constant declarations with multiple declarators (e.g., `int* p, q;`)
10269 ### <a name="Res-auto"></a>ES.11: Use `auto` to avoid redundant repetition of type names
10271 ##### Reason
10273 * Simple repetition is tedious and error-prone.
10274 * When you use `auto`, the name of the declared entity is in a fixed position in the declaration, increasing readability.
10275 * In a template function declaration the return type can be a member type.
10277 ##### Example
10279 Consider:
10281     auto p = v.begin();   // vector<int>::iterator
10282     auto h = t.future();
10283     auto q = make_unique<int[]>(s);
10284     auto f = [](int x){ return x + 10; };
10286 In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.
10288 ##### Example
10290     template<class T>
10291     auto Container<T>::first() -> Iterator;   // Container<T>::Iterator
10293 ##### Exception
10295 Avoid `auto` for initializer lists and in cases where you know exactly which type you want and where an initializer might require conversion.
10297 ##### Example
10299     auto lst = { 1, 2, 3 };   // lst is an initializer list
10300     auto x{1};   // x is an int (in C++17; initializer_list in C++11)
10302 ##### Note
10304 When concepts become available, we can (and should) be more specific about the type we are deducing:
10306     // ...
10307     ForwardIterator p = algo(x, y, z);
10309 ##### Example (C++17)
10311     auto [ quotient, remainder ] = div(123456, 73);   // break out the members of the div_t result
10313 ##### Enforcement
10315 Flag redundant repetition of type names in a declaration.
10317 ### <a name="Res-reuse"></a>ES.12: Do not reuse names in nested scopes
10319 ##### Reason
10321 It is easy to get confused about which variable is used.
10322 Can cause maintenance problems.
10324 ##### Example, bad
10326     int d = 0;
10327     // ...
10328     if (cond) {
10329         // ...
10330         d = 9;
10331         // ...
10332     }
10333     else {
10334         // ...
10335         int d = 7;
10336         // ...
10337         d = value_to_be_returned;
10338         // ...
10339     }
10341     return d;
10343 If this is a large `if`-statement, it is easy to overlook that a new `d` has been introduced in the inner scope.
10344 This is a known source of bugs.
10345 Sometimes such reuse of a name in an inner scope is called "shadowing".
10347 ##### Note
10349 Shadowing is primarily a problem when functions are too large and too complex.
10351 ##### Example
10353 Shadowing of function arguments in the outermost block is disallowed by the language:
10355     void f(int x)
10356     {
10357         int x = 4;  // error: reuse of function argument name
10359         if (x) {
10360             int x = 7;  // allowed, but bad
10361             // ...
10362         }
10363     }
10365 ##### Example, bad
10367 Reuse of a member name as a local variable can also be a problem:
10369     struct S {
10370         int m;
10371         void f(int x);
10372     };
10374     void S::f(int x)
10375     {
10376         m = 7;    // assign to member
10377         if (x) {
10378             int m = 9;
10379             // ...
10380             m = 99; // assign to local variable
10381             // ...
10382         }
10383     }
10385 ##### Exception
10387 We often reuse function names from a base class in a derived class:
10389     struct B {
10390         void f(int);
10391     };
10393     struct D : B {
10394         void f(double);
10395         using B::f;
10396     };
10398 This is error-prone.
10399 For example, had we forgotten the using declaration, a call `d.f(1)` would not have found the `int` version of `f`.
10401 ??? Do we need a specific rule about shadowing/hiding in class hierarchies?
10403 ##### Enforcement
10405 * Flag reuse of a name in nested local scopes
10406 * Flag reuse of a member name as a local variable in a member function
10407 * Flag reuse of a global name as a local variable or a member name
10408 * Flag reuse of a base class member name in a derived class (except for function names)
10410 ### <a name="Res-always"></a>ES.20: Always initialize an object
10412 ##### Reason
10414 Avoid used-before-set errors and their associated undefined behavior.
10415 Avoid problems with comprehension of complex initialization.
10416 Simplify refactoring.
10418 ##### Example
10420     void use(int arg)
10421     {
10422         int i;   // bad: uninitialized variable
10423         // ...
10424         i = 7;   // initialize i
10425     }
10427 No, `i = 7` does not initialize `i`; it assigns to it. Also, `i` can be read in the `...` part. Better:
10429     void use(int arg)   // OK
10430     {
10431         int i = 7;   // OK: initialized
10432         string s;    // OK: default initialized
10433         // ...
10434     }
10436 ##### Note
10438 The *always initialize* rule is deliberately stronger than the *an object must be set before used* language rule.
10439 The latter, more relaxed rule, catches the technical bugs, but:
10441 * It leads to less readable code
10442 * It encourages people to declare names in greater than necessary scopes
10443 * It leads to harder to read code
10444 * It leads to logic bugs by encouraging complex code
10445 * It hampers refactoring
10447 The *always initialize* rule is a style rule aimed to improve maintainability as well as a rule protecting against used-before-set errors.
10449 ##### Example
10451 Here is an example that is often considered to demonstrate the need for a more relaxed rule for initialization
10453     widget i;    // "widget" a type that's expensive to initialize, possibly a large POD
10454     widget j;
10456     if (cond) {  // bad: i and j are initialized "late"
10457         i = f1();
10458         j = f2();
10459     }
10460     else {
10461         i = f3();
10462         j = f4();
10463     }
10465 This cannot trivially be rewritten to initialize `i` and `j` with initializers.
10466 Note that for types with a default constructor, attempting to postpone initialization simply leads to a default initialization followed by an assignment.
10467 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.
10469 Assuming that there is a logical connection between `i` and `j`, that connection should probably be expressed in code:
10471     pair<widget, widget> make_related_widgets(bool x)
10472     {
10473         return (x) ? {f1(), f2()} : {f3(), f4() };
10474     }
10476     auto [i, j] = make_related_widgets(cond);    // C++17
10478 ##### Note
10480 Complex initialization has been popular with clever programmers for decades.
10481 It has also been a major source of errors and complexity.
10482 Many such errors are introduced during maintenance years after the initial implementation.
10484 ##### Example
10486 This rule covers member variables.
10488     class X {
10489     public:
10490         X(int i, int ci) : m2{i}, cm2{ci} {}
10491         // ...
10493     private:
10494         int m1 = 7;
10495         int m2;
10496         int m3;
10498         const int cm1 = 7;
10499         const int cm2;
10500         const int cm3;
10501     };
10503 The compiler will flag the uninitialized `cm3` because it is a `const`, but it will not catch the lack of initialization of `m3`.
10504 Usually, a rare spurious member initialization is worth the absence of errors from lack of initialization and often an optimizer
10505 can eliminate a redundant initialization (e.g., an initialization that occurs immediately before an assignment).
10507 ##### Exception
10509 If you are declaring an object that is just about to be initialized from input, initializing it would cause a double initialization.
10510 However, beware that this may leave uninitialized data beyond the input -- and that has been a fertile source of errors and security breaches:
10512     constexpr int max = 8 * 1024;
10513     int buf[max];         // OK, but suspicious: uninitialized
10514     f.read(buf, max);
10516 The cost of initializing that array could be significant in some situations.
10517 However, such examples do tend to leave uninitialized variables accessible, so they should be treated with suspicion.
10519     constexpr int max = 8 * 1024;
10520     int buf[max] = {};   // zero all elements; better in some situations
10521     f.read(buf, max);
10523 When feasible use a library function that is known not to overflow. For example:
10525     string s;   // s is default initialized to ""
10526     cin >> s;   // s expands to hold the string
10528 Don't consider simple variables that are targets for input operations exceptions to this rule:
10530     int i;   // bad
10531     // ...
10532     cin >> i;
10534 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.
10536     int i2 = 0;   // better, assuming that zero is an acceptable value for i2
10537     // ...
10538     cin >> i2;
10540 A good optimizer should know about input operations and eliminate the redundant operation.
10542 ##### Example
10544 Using a value representing "uninitialized" is a symptom of a problem and not a solution:
10546     widget i = uninit;  // bad
10547     widget j = uninit;
10549     // ...
10550     use(i);         // possibly used before set
10551     // ...
10553     if (cond) {     // bad: i and j are initialized "late"
10554         i = f1();
10555         j = f2();
10556     }
10557     else {
10558         i = f3();
10559         j = f4();
10560     }
10562 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?
10564 ##### Note
10566 Sometimes, a lambda can be used as an initializer to avoid an uninitialized variable:
10568     error_code ec;
10569     Value v = [&] {
10570         auto p = get_value();   // get_value() returns a pair<error_code, Value>
10571         ec = p.first;
10572         return p.second;
10573     }();
10575 or maybe:
10577     Value v = [] {
10578         auto p = get_value();   // get_value() returns a pair<error_code, Value>
10579         if (p.first) throw Bad_value{p.first};
10580         return p.second;
10581     }();
10583 **See also**: [ES.28](#Res-lambda-init)
10585 ##### Enforcement
10587 * Flag every uninitialized variable.
10588   Don't flag variables of user-defined types with default constructors.
10589 * Check that an uninitialized buffer is written into *immediately* after declaration.
10590   Passing an uninitialized variable as a reference to non-`const` argument can be assumed to be a write into the variable.
10592 ### <a name="Res-introduce"></a>ES.21: Don't introduce a variable (or constant) before you need to use it
10594 ##### Reason
10596 Readability. To limit the scope in which the variable can be used.
10598 ##### Example
10600     int x = 7;
10601     // ... no use of x here ...
10602     ++x;
10604 ##### Enforcement
10606 Flag declarations that are distant from their first use.
10608 ### <a name="Res-init"></a>ES.22: Don't declare a variable until you have a value to initialize it with
10610 ##### Reason
10612 Readability. Limit the scope in which a variable can be used. Don't risk used-before-set. Initialization is often more efficient than assignment.
10614 ##### Example, bad
10616     string s;
10617     // ... no use of s here ...
10618     s = "what a waste";
10620 ##### Example, bad
10622     SomeLargeType var;   // ugly CaMeLcAsEvArIaBlE
10624     if (cond)   // some non-trivial condition
10625         Set(&var);
10626     else if (cond2 || !cond3) {
10627         var = Set2(3.14);
10628     }
10629     else {
10630         var = 0;
10631         for (auto& e : something)
10632             var += e;
10633     }
10635     // use var; that this isn't done too early can be enforced statically with only control flow
10637 This would be fine if there was a default initialization for `SomeLargeType` that wasn't too expensive.
10638 Otherwise, a programmer might very well wonder if every possible path through the maze of conditions has been covered.
10639 If not, we have a "use before set" bug. This is a maintenance trap.
10641 For initializers of moderate complexity, including for `const` variables, consider using a lambda to express the initializer; see [ES.28](#Res-lambda-init).
10643 ##### Enforcement
10645 * Flag declarations with default initialization that are assigned to before they are first read.
10646 * Flag any complicated computation after an uninitialized variable and before its use.
10648 ### <a name="Res-list"></a>ES.23: Prefer the `{}`-initializer syntax
10650 ##### Reason
10652 Prefer `{}`. The rules for `{}` initialization are simpler, more general, less ambiguous, and safer than for other forms of initialization.
10654 Use `=` only when you are sure that there can be no narrowing conversions. For built-in arithmetic types, use `=` only with `auto`.
10656 Avoid `()` initialization, which allows parsing ambiguities.
10658 ##### Example
10660     int x {f(99)};
10661     int y = x;
10662     vector<int> v = {1, 2, 3, 4, 5, 6};
10664 ##### Exception
10666 For containers, there is a tradition for using `{...}` for a list of elements and `(...)` for sizes:
10668     vector<int> v1(10);    // vector of 10 elements with the default value 0
10669     vector<int> v2{10};    // vector of 1 element with the value 10
10671     vector<int> v3(1, 2);  // vector of 1 element with the value 2
10672     vector<int> v4{1, 2};  // vector of 2 element with the values 1 and 2
10674 ##### Note
10676 `{}`-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).
10678 ##### Example
10680     int x {7.9};   // error: narrowing
10681     int y = 7.9;   // OK: y becomes 7. Hope for a compiler warning
10682     int z = gsl::narrow_cast<int>(7.9);  // OK: you asked for it
10684 ##### Note
10686 `{}` initialization can be used for nearly all initialization; other forms of initialization can't:
10688     auto p = new vector<int> {1, 2, 3, 4, 5};   // initialized vector
10689     D::D(int a, int b) :m{a, b} {   // member initializer (e.g., m might be a pair)
10690         // ...
10691     };
10692     X var {};   // initialize var to be empty
10693     struct S {
10694         int m {7};   // default initializer for a member
10695         // ...
10696     };
10698 For that reason, `{}`-initialization is often called "uniform initialization"
10699 (though there unfortunately are a few irregularities left).
10701 ##### Note
10703 Initialization of a variable declared using `auto` with a single value, e.g., `{v}`, had surprising results until C++17.
10704 The C++17 rules are somewhat less surprising:
10706     auto x1 {7};        // x1 is an int with the value 7
10707     auto x2 = {7};      // x2 is an initializer_list<int> with an element 7
10709     auto x11 {7, 8};    // error: two initializers
10710     auto x22 = {7, 8};  // x22 is an initializer_list<int> with elements 7 and 8
10712 Use `={...}` if you really want an `initializer_list<T>`
10714     auto fib10 = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};   // fib10 is a list
10716 ##### Note
10718 `={}` gives copy initialization whereas `{}` gives direct initialization.
10719 Like the distinction between copy-initialization and direct-initialization itself, this can lead to surprises.
10720 `{}` accepts `explicit` constructors; `={}` does not. For example:
10722     struct Z { explicit Z() {} };
10724     Z z1{};     // OK: direct initialization, so we use explicit constructor
10725     Z z2 = {};  // error: copy initialization, so we cannot use the explicit constructor
10727 Use plain `{}`-initialization unless you specifically want to disable explicit constructors.
10729 ##### Example
10731     template<typename T>
10732     void f()
10733     {
10734         T x1(1);    // T initialized with 1
10735         T x0();     // bad: function declaration (often a mistake)
10737         T y1 {1};   // T initialized with 1
10738         T y0 {};    // default initialized T
10739         // ...
10740     }
10742 **See also**: [Discussion](#???)
10744 ##### Enforcement
10746 * Flag uses of `=` to initialize arithmetic types where narrowing occurs.
10747 * Flag uses of `()` initialization syntax that are actually declarations. (Many compilers should warn on this already.)
10749 ### <a name="Res-unique"></a>ES.24: Use a `unique_ptr<T>` to hold pointers
10751 ##### Reason
10753 Using `std::unique_ptr` is the simplest way to avoid leaks. It is reliable, it
10754 makes the type system do much of the work to validate ownership safety, it
10755 increases readability, and it has zero or near zero run-time cost.
10757 ##### Example
10759     void use(bool leak)
10760     {
10761         auto p1 = make_unique<int>(7);   // OK
10762         int* p2 = new int{7};            // bad: might leak
10763         // ... no assignment to p2 ...
10764         if (leak) return;
10765         // ... no assignment to p2 ...
10766         vector<int> v(7);
10767         v.at(7) = 0;                    // exception thrown
10768         // ...
10769     }
10771 If `leak == true` the object pointed to by `p2` is leaked and the object pointed to by `p1` is not.
10772 The same is the case when `at()` throws.
10774 ##### Enforcement
10776 Look for raw pointers that are targets of `new`, `malloc()`, or functions that may return such pointers.
10778 ### <a name="Res-const"></a>ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on
10780 ##### Reason
10782 That way you can't change the value by mistake. That way may offer the compiler optimization opportunities.
10784 ##### Example
10786     void f(int n)
10787     {
10788         const int bufmax = 2 * n + 2;  // good: we can't change bufmax by accident
10789         int xmax = n;                  // suspicious: is xmax intended to change?
10790         // ...
10791     }
10793 ##### Enforcement
10795 Look to see if a variable is actually mutated, and flag it if
10796 not. Unfortunately, it may be impossible to detect when a non-`const` was not
10797 *intended* to vary (vs when it merely did not vary).
10799 ### <a name="Res-recycle"></a>ES.26: Don't use a variable for two unrelated purposes
10801 ##### Reason
10803 Readability and safety.
10805 ##### Example, bad
10807     void use()
10808     {
10809         int i;
10810         for (i = 0; i < 20; ++i) { /* ... */ }
10811         for (i = 0; i < 200; ++i) { /* ... */ } // bad: i recycled
10812     }
10814 ##### Note
10816 As an optimization, you may 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.
10818     void write_to_file() {
10819         std::string buffer;             // to avoid reallocations on every loop iteration
10820         for (auto& o : objects)
10821         {
10822             // First part of the work.
10823             generate_first_String(buffer, o);
10824             write_to_file(buffer);
10826             // Second part of the work.
10827             generate_second_string(buffer, o);
10828             write_to_file(buffer);
10830             // etc...
10831         }
10832     }
10834 ##### Enforcement
10836 Flag recycled variables.
10838 ### <a name="Res-stack"></a>ES.27: Use `std::array` or `stack_array` for arrays on the stack
10840 ##### Reason
10842 They are readable and don't implicitly convert to pointers.
10843 They are not confused with non-standard extensions of built-in arrays.
10845 ##### Example, bad
10847     const int n = 7;
10848     int m = 9;
10850     void f()
10851     {
10852         int a1[n];
10853         int a2[m];   // error: not ISO C++
10854         // ...
10855     }
10857 ##### Note
10859 The definition of `a1` is legal C++ and has always been.
10860 There is a lot of such code.
10861 It is error-prone, though, especially when the bound is non-local.
10862 Also, it is a "popular" source of errors (buffer overflow, pointers from array decay, etc.).
10863 The definition of `a2` is C but not C++ and is considered a security risk
10865 ##### Example
10867     const int n = 7;
10868     int m = 9;
10870     void f()
10871     {
10872         array<int, n> a1;
10873         stack_array<int> a2(m);
10874         // ...
10875     }
10877 ##### Enforcement
10879 * Flag arrays with non-constant bounds (C-style VLAs)
10880 * Flag arrays with non-local constant bounds
10882 ### <a name="Res-lambda-init"></a>ES.28: Use lambdas for complex initialization, especially of `const` variables
10884 ##### Reason
10886 It nicely encapsulates local initialization, including cleaning up scratch variables needed only for the initialization, without needing to create a needless nonlocal yet nonreusable function. It also works for variables that should be `const` but only after some initialization work.
10888 ##### Example, bad
10890     widget x;   // should be const, but:
10891     for (auto i = 2; i <= N; ++i) {          // this could be some
10892         x += some_obj.do_something_with(i);  // arbitrarily long code
10893     }                                        // needed to initialize x
10894     // from here, x should be const, but we can't say so in code in this style
10896 ##### Example, good
10898     const widget x = [&]{
10899         widget val;                                // assume that widget has a default constructor
10900         for (auto i = 2; i <= N; ++i) {            // this could be some
10901             val += some_obj.do_something_with(i);  // arbitrarily long code
10902         }                                          // needed to initialize x
10903         return val;
10904     }();
10906 ##### Example
10908     string var = [&]{
10909         if (!in) return "";   // default
10910         string s;
10911         for (char c : in >> c)
10912             s += toupper(c);
10913         return s;
10914     }(); // note ()
10916 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.
10918 ##### Enforcement
10920 Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it.
10922 ### <a name="Res-macros"></a>ES.30: Don't use macros for program text manipulation
10924 ##### Reason
10926 Macros are a major source of bugs.
10927 Macros don't obey the usual scope and type rules.
10928 Macros ensure that the human reader sees something different from what the compiler sees.
10929 Macros complicate tool building.
10931 ##### Example, bad
10933     #define Case break; case   /* BAD */
10935 This innocuous-looking macro makes a single lower case `c` instead of a `C` into a bad flow-control bug.
10937 ##### Note
10939 This rule does not ban the use of macros for "configuration control" use in `#ifdef`s, etc.
10941 In the future, modules are likely to eliminate the need for macros in configuration control.
10943 ##### Note
10945 This rule is meant to also discourage use of `#` for stringification and `##` for concatenation.
10946 As usual for macros, there are uses that are "mostly harmless", but even these can create problems for tools,
10947 such as auto completers, static analyzers, and debuggers.
10948 Often the desire to use fancy macros is a sign of an overly complex design.
10949 Also, `#` and `##` encourages the definition and use of macros:
10951     #define CAT(a, b) a ## b
10952     #define STRINGIFY(a) #a
10954     void f(int x, int y)
10955     {
10956         string CAT(x, y) = "asdf";   // BAD: hard for tools to handle (and ugly)
10957         string sx2 = STRINGIFY(x);
10958         // ...
10959     }
10961 There are workarounds for low-level string manipulation using macros. For example:
10963     string s = "asdf" "lkjh";   // ordinary string literal concatenation
10965     enum E { a, b };
10967     template<int x>
10968     constexpr const char* stringify()
10969     {
10970         switch (x) {
10971         case a: return "a";
10972         case b: return "b";
10973         }
10974     }
10976     void f(int x, int y)
10977     {
10978         string sx = stringify<x>();
10979         // ...
10980     }
10982 This is not as convenient as a macro to define, but as easy to use, has zero overhead, and is typed and scoped.
10984 In the future, static reflection is likely to eliminate the last needs for the preprocessor for program text manipulation.
10986 ##### Enforcement
10988 Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`)
10990 ### <a name="Res-macros2"></a>ES.31: Don't use macros for constants or "functions"
10992 ##### Reason
10994 Macros are a major source of bugs.
10995 Macros don't obey the usual scope and type rules.
10996 Macros don't obey the usual rules for argument passing.
10997 Macros ensure that the human reader sees something different from what the compiler sees.
10998 Macros complicate tool building.
11000 ##### Example, bad
11002     #define PI 3.14
11003     #define SQUARE(a, b) (a * b)
11005 Even if we hadn't left a well-known bug in `SQUARE` there are much better behaved alternatives; for example:
11007     constexpr double pi = 3.14;
11008     template<typename T> T square(T a, T b) { return a * b; }
11010 ##### Enforcement
11012 Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`)
11014 ### <a name="Res-ALL_CAPS"></a>ES.32: Use `ALL_CAPS` for all macro names
11016 ##### Reason
11018 Convention. Readability. Distinguishing macros.
11020 ##### Example
11022     #define forever for (;;)   /* very BAD */
11024     #define FOREVER for (;;)   /* Still evil, but at least visible to humans */
11026 ##### Enforcement
11028 Scream when you see a lower case macro.
11030 ### <a name="Res-MACROS"></a>ES.33: If you must use macros, give them unique names
11032 ##### Reason
11034 Macros do not obey scope rules.
11036 ##### Example
11038     #define MYCHAR        /* BAD, will eventually clash with someone else's MYCHAR*/
11040     #define ZCORP_CHAR    /* Still evil, but less likely to clash */
11042 ##### Note
11044 Avoid macros if you can: [ES.30](#Res-macros), [ES.31](#Res-macros2), and [ES.32](#Res-ALL_CAPS).
11045 However, there are billions of lines of code littered with macros and a long tradition for using and overusing macros.
11046 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.
11048 ##### Enforcement
11050 Warn against short macro names.
11052 ### <a name="Res-ellipses"></a> ES.34: Don't define a (C-style) variadic function
11054 ##### Reason
11056 Not type safe.
11057 Requires messy cast-and-macro-laden code to get working right.
11059 ##### Example
11061     #include <cstdarg>
11063     // "severity" followed by a zero-terminated list of char*s; write the C-style strings to cerr
11064     void error(int severity ...)
11065     {
11066         va_list ap;             // a magic type for holding arguments
11067         va_start(ap, severity); // arg startup: "severity" is the first argument of error()
11069         for (;;) {
11070             // treat the next var as a char*; no checking: a cast in disguise
11071             char* p = va_arg(ap, char*);
11072             if (!p) break;
11073             cerr << p << ' ';
11074         }
11076         va_end(ap);             // arg cleanup (don't forget this)
11078         cerr << '\n';
11079         if (severity) exit(severity);
11080     }
11082     void use()
11083     {
11084         error(7, "this", "is", "an", "error", nullptr);
11085         error(7); // crash
11086         error(7, "this", "is", "an", "error");  // crash
11087         const char* is = "is";
11088         string an = "an";
11089         error(7, "this", "is", an, "error"); // crash
11090     }
11092 **Alternative**: Overloading. Templates. Variadic templates.
11093     #include <iostream>
11095     void error(int severity)
11096     {
11097         std::cerr << '\n';
11098         std::exit(severity);
11099     }
11101     template <typename T, typename... Ts>
11102     constexpr void error(int severity, T head, Ts... tail)
11103     {
11104         std::cerr << head;
11105         error(severity, tail...);
11106     }
11108     void use()
11109     {
11110         error(7); // No crash!
11111         error(5, "this", "is", "not", "an", "error"); // No crash!
11113         std::string an = "an";
11114         error(7, "this", "is", "not", an, "error"); // No crash!
11116         error(5, "oh", "no", nullptr); // Compile error! No need for nullptr.
11117     }
11120 ##### Note
11122 This is basically the way `printf` is implemented.
11124 ##### Enforcement
11126 * Flag definitions of C-style variadic functions.
11127 * Flag `#include <cstdarg>` and `#include <stdarg.h>`
11130 ## ES.expr: Expressions
11132 Expressions manipulate values.
11134 ### <a name="Res-complicated"></a>ES.40: Avoid complicated expressions
11136 ##### Reason
11138 Complicated expressions are error-prone.
11140 ##### Example
11142     // bad: assignment hidden in subexpression
11143     while ((c = getc()) != -1)
11145     // bad: two non-local variables assigned in sub-expressions
11146     while ((cin >> c1, cin >> c2), c1 == c2)
11148     // better, but possibly still too complicated
11149     for (char c1, c2; cin >> c1 >> c2 && c1 == c2;)
11151     // OK: if i and j are not aliased
11152     int x = ++i + ++j;
11154     // OK: if i != j and i != k
11155     v[i] = v[j] + v[k];
11157     // bad: multiple assignments "hidden" in subexpressions
11158     x = a + (b = f()) + (c = g()) * 7;
11160     // bad: relies on commonly misunderstood precedence rules
11161     x = a & b + c * d && e ^ f == 7;
11163     // bad: undefined behavior
11164     x = x++ + x++ + ++x;
11166 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.
11168 ##### Note
11170 C++17 tightens up the rules for the order of evaluation
11171 (left-to-right except right-to-left in assignments, and the order of evaluation of function arguments is unspecified; [see ES.43](#Res-order)),
11172 but that doesn't change the fact that complicated expressions are potentially confusing.
11174 ##### Note
11176 A programmer should know and use the basic rules for expressions.
11178 ##### Example
11180     x = k * y + z;             // OK
11182     auto t1 = k * y;           // bad: unnecessarily verbose
11183     x = t1 + z;
11185     if (0 <= x && x < max)   // OK
11187     auto t1 = 0 <= x;        // bad: unnecessarily verbose
11188     auto t2 = x < max;
11189     if (t1 && t2)            // ...
11191 ##### Enforcement
11193 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:
11195 * 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
11196 * writes to aliased variables
11197 * more than N operators (and what should N be?)
11198 * reliance of subtle precedence rules
11199 * uses undefined behavior (can we catch all undefined behavior?)
11200 * implementation defined behavior?
11201 * ???
11203 ### <a name="Res-parens"></a>ES.41: If in doubt about operator precedence, parenthesize
11205 ##### Reason
11207 Avoid errors. Readability. Not everyone has the operator table memorized.
11209 ##### Example
11211     const unsigned int flag = 2;
11212     unsigned int a = flag;
11214     if (a & flag != 0)  // bad: means a&(flag != 0)
11216 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.
11218     if ((a & flag) != 0)  // OK: works as intended
11220 ##### Note
11222 You should know enough not to need parentheses for:
11224     if (a < 0 || a <= max) {
11225         // ...
11226     }
11228 ##### Enforcement
11230 * Flag combinations of bitwise-logical operators and other operators.
11231 * Flag assignment operators not as the leftmost operator.
11232 * ???
11234 ### <a name="Res-ptr"></a>ES.42: Keep use of pointers simple and straightforward
11236 ##### Reason
11238 Complicated pointer manipulation is a major source of errors.
11240 ##### Note
11242 Use `gsl::span` instead.
11243 Pointers should [only refer to single objects](#Ri-array).
11244 Pointer arithmetic is fragile and easy to get wrong, the source of many, many bad bugs and security violations.
11245 `span` is a bounds-checked, safe type for accessing arrays of data.
11246 Access into an array with known bounds using a constant as a subscript can be validated by the compiler.
11248 ##### Example, bad
11250     void f(int* p, int count)
11251     {
11252         if (count < 2) return;
11254         int* q = p + 1;    // BAD
11256         ptrdiff_t d;
11257         int n;
11258         d = (p - &n);      // OK
11259         d = (q - p);       // OK
11261         int n = *p++;      // BAD
11263         if (count < 6) return;
11265         p[4] = 1;          // BAD
11267         p[count - 1] = 2;  // BAD
11269         use(&p[0], 3);     // BAD
11270     }
11272 ##### Example, good
11274     void f(span<int> a) // BETTER: use span in the function declaration
11275     {
11276         if (a.size() < 2) return;
11278         int n = a[0];      // OK
11280         span<int> q = a.subspan(1); // OK
11282         if (a.size() < 6) return;
11284         a[4] = 1;          // OK
11286         a[a.size() - 1] = 2;  // OK
11288         use(a.data(), 3);  // OK
11289     }
11291 ##### Note
11293 Subscripting with a variable is difficult for both tools and humans to validate as safe.
11294 `span` is a run-time bounds-checked, safe type for accessing arrays of data.
11295 `at()` is another alternative that ensures single accesses are bounds-checked.
11296 If iterators are needed to access an array, use the iterators from a `span` constructed over the array.
11298 ##### Example, bad
11300     void f(array<int, 10> a, int pos)
11301     {
11302         a[pos / 2] = 1; // BAD
11303         a[pos - 1] = 2; // BAD
11304         a[-1] = 3;    // BAD (but easily caught by tools) -- no replacement, just don't do this
11305         a[10] = 4;    // BAD (but easily caught by tools) -- no replacement, just don't do this
11306     }
11308 ##### Example, good
11310 Use a `span`:
11312     void f1(span<int, 10> a, int pos) // A1: Change parameter type to use span
11313     {
11314         a[pos / 2] = 1; // OK
11315         a[pos - 1] = 2; // OK
11316     }
11318     void f2(array<int, 10> arr, int pos) // A2: Add local span and use that
11319     {
11320         span<int> a = {arr.data(), pos};
11321         a[pos / 2] = 1; // OK
11322         a[pos - 1] = 2; // OK
11323     }
11325 Use `at()`:
11327     void f3(array<int, 10> a, int pos) // ALTERNATIVE B: Use at() for access
11328     {
11329         at(a, pos / 2) = 1; // OK
11330         at(a, pos - 1) = 2; // OK
11331     }
11333 ##### Example, bad
11335     void f()
11336     {
11337         int arr[COUNT];
11338         for (int i = 0; i < COUNT; ++i)
11339             arr[i] = i; // BAD, cannot use non-constant indexer
11340     }
11342 ##### Example, good
11344 Use a `span`:
11346     void f1()
11347     {
11348         int arr[COUNT];
11349         span<int> av = arr;
11350         for (int i = 0; i < COUNT; ++i)
11351             av[i] = i;
11352     }
11354 Use a `span` and range-`for`:
11356     void f1a()
11357     {
11358          int arr[COUNT];
11359          span<int, COUNT> av = arr;
11360          int i = 0;
11361          for (auto& e : av)
11362              e = i++;
11363     }
11365 Use `at()` for access:
11367     void f2()
11368     {
11369         int arr[COUNT];
11370         for (int i = 0; i < COUNT; ++i)
11371             at(arr, i) = i;
11372     }
11374 Use a range-`for`:
11376     void f3()
11377     {
11378         int arr[COUNT];
11379         int i = 0;
11380         for (auto& e : arr)
11381              e = i++;
11382     }
11384 ##### Note
11386 Tooling can offer rewrites of array accesses that involve dynamic index expressions to use `at()` instead:
11388     static int a[10];
11390     void f(int i, int j)
11391     {
11392         a[i + j] = 12;      // BAD, could be rewritten as ...
11393         at(a, i + j) = 12;  // OK -- bounds-checked
11394     }
11396 ##### Example
11398 Turning an array into a pointer (as the language does essentially always) removes opportunities for checking, so avoid it
11400     void g(int* p);
11402     void f()
11403     {
11404         int a[5];
11405         g(a);        // BAD: are we trying to pass an array?
11406         g(&a[0]);    // OK: passing one object
11407     }
11409 If you want to pass an array, say so:
11411     void g(int* p, size_t length);  // old (dangerous) code
11413     void g1(span<int> av); // BETTER: get g() changed.
11415     void f2()
11416     {
11417         int a[5];
11418         span<int> av = a;
11420         g(av.data(), av.size());   // OK, if you have no choice
11421         g1(a);                     // OK -- no decay here, instead use implicit span ctor
11422     }
11424 ##### Enforcement
11426 * Flag any arithmetic operation on an expression of pointer type that results in a value of pointer type.
11427 * 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.
11428 * Flag any expression that would rely on implicit conversion of an array type to a pointer type.
11430 This rule is part of the [bounds-safety profile](#SS-bounds).
11433 ### <a name="Res-order"></a>ES.43: Avoid expressions with undefined order of evaluation
11435 ##### Reason
11437 You have no idea what such code does. Portability.
11438 Even if it does something sensible for you, it may do something different on another compiler (e.g., the next release of your compiler) or with a different optimizer setting.
11440 ##### Note
11442 C++17 tightens up the rules for the order of evaluation:
11443 left-to-right except right-to-left in assignments, and the order of evaluation of function arguments is unspecified.
11445 However, remember that your code may be compiled with a pre-C++17 compiler (e.g., through cut-and-paste) so don't be too clever.
11447 ##### Example
11449     v[i] = ++i;   //  the result is undefined
11451 A good rule of thumb is that you should not read a value twice in an expression where you write to it.
11453 ##### Enforcement
11455 Can be detected by a good analyzer.
11457 ### <a name="Res-order-fct"></a>ES.44: Don't depend on order of evaluation of function arguments
11459 ##### Reason
11461 Because that order is unspecified.
11463 ##### Note
11465 C++17 tightens up the rules for the order of evaluation, but the order of evaluation of function arguments is still unspecified.
11467 ##### Example
11469     int i = 0;
11470     f(++i, ++i);
11472 The call will most likely be `f(0, 1)` or `f(1, 0)`, but you don't know which.
11473 Technically, the behavior is undefined.
11474 In C++17, this code does not have undefined behavior, but it is still not specified which argument is evaluated first.
11476 ##### Example
11478 Overloaded operators can lead to order of evaluation problems:
11480     f1()->m(f2());          // m(f1(), f2())
11481     cout << f1() << f2();   // operator<<(operator<<(cout, f1()), f2())
11483 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)
11485     f1() = f2();    // undefined behavior in C++14; in C++17, f2() is evaluated before f1()
11487 ##### Enforcement
11489 Can be detected by a good analyzer.
11491 ### <a name="Res-magic"></a>ES.45: Avoid "magic constants"; use symbolic constants
11493 ##### Reason
11495 Unnamed constants embedded in expressions are easily overlooked and often hard to understand:
11497 ##### Example
11499     for (int m = 1; m <= 12; ++m)   // don't: magic constant 12
11500         cout << month[m] << '\n';
11502 No, we don't all know that there are 12 months, numbered 1..12, in a year. Better:
11504     // months are indexed 1..12
11505     constexpr int first_month = 1;
11506     constexpr int last_month = 12;
11508     for (int m = first_month; m <= last_month; ++m)   // better
11509         cout << month[m] << '\n';
11511 Better still, don't expose constants:
11513     for (auto m : month)
11514         cout << m << '\n';
11516 ##### Enforcement
11518 Flag literals in code. Give a pass to `0`, `1`, `nullptr`, `\n`, `""`, and others on a positive list.
11520 ### <a name="Res-narrowing"></a>ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions
11522 ##### Reason
11524 A narrowing conversion destroys information, often unexpectedly so.
11526 ##### Example, bad
11528 A key example is basic narrowing:
11530     double d = 7.9;
11531     int i = d;    // bad: narrowing: i becomes 7
11532     i = (int) d;  // bad: we're going to claim this is still not explicit enough
11534     void f(int x, long y, double d)
11535     {
11536         char c1 = x;   // bad: narrowing
11537         char c2 = y;   // bad: narrowing
11538         char c3 = d;   // bad: narrowing
11539     }
11541 ##### Note
11543 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 information:
11545     i = narrow_cast<int>(d);   // OK (you asked for it): narrowing: i becomes 7
11546     i = narrow<int>(d);        // OK: throws narrowing_error
11548 We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type:
11550     double d = -7.9;
11551     unsigned u = 0;
11553     u = d;                          // BAD
11554     u = narrow_cast<unsigned>(d);   // OK (you asked for it): u becomes 0
11555     u = narrow<unsigned>(d);        // OK: throws narrowing_error
11557 ##### Enforcement
11559 A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions:
11561 * flag all floating-point to integer conversions (maybe only `float`->`char` and `double`->`int`. Here be dragons! we need data)
11562 * flag all `long`->`char` (I suspect `int`->`char` is very common. Here be dragons! we need data)
11563 * consider narrowing conversions for function arguments especially suspect
11565 ### <a name="Res-nullptr"></a>ES.47: Use `nullptr` rather than `0` or `NULL`
11567 ##### Reason
11569 Readability. Minimize surprises: `nullptr` cannot be confused with an
11570 `int`. `nullptr` also has a well-specified (very restrictive) type, and thus
11571 works in more scenarios where type deduction might do the wrong thing on `NULL`
11572 or `0`.
11574 ##### Example
11576 Consider:
11578     void f(int);
11579     void f(char*);
11580     f(0);         // call f(int)
11581     f(nullptr);   // call f(char*)
11583 ##### Enforcement
11585 Flag uses of `0` and `NULL` for pointers. The transformation may be helped by simple program transformation.
11587 ### <a name="Res-casts"></a>ES.48: Avoid casts
11589 ##### Reason
11591 Casts are a well-known source of errors. Make some optimizations unreliable.
11593 ##### Example, bad
11595     double d = 2;
11596     auto p = (long*)&d;
11597     auto q = (long long*)&d;
11598     cout << d << ' ' << *p << ' ' << *q << '\n';
11600 What would you think this fragment prints? The result is at best implementation defined. I got
11602     2 0 4611686018427387904
11604 Adding
11606     *q = 666;
11607     cout << d << ' ' << *p << ' ' << *q << '\n';
11609 I got
11611     3.29048e-321 666 666
11613 Surprised? I'm just glad I didn't crash the program.
11615 ##### Note
11617 Programmers who write casts typically assume that they know what they are doing,
11618 or that writing a cast makes the program "easier to read".
11619 In fact, they often disable the general rules for using values.
11620 Overload resolution and template instantiation usually pick the right function if there is a right function to pick.
11621 If there is not, maybe there ought to be, rather than applying a local fix (cast).
11623 ##### Note
11625 Casts are necessary in a systems programming language.  For example, how else
11626 would we get the address of a device register into a pointer?  However, casts
11627 are seriously overused as well as a major source of errors.
11629 ##### Note
11631 If you feel the need for a lot of casts, there may be a fundamental design problem.
11633 ##### Exception
11635 Casting to `(void)` is the Standard-sanctioned way to turn off `[[nodiscard]]` warnings. If you are calling a function with a `[[nodiscard]]` return and you deliberately want to discard the 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), but if you still think it's appropriate and your code reviewer agrees, write `(void)` to turn off the warning.
11637 ##### Alternatives
11639 Casts are widely (mis) used. Modern C++ has rules and constructs that eliminate the need for casts in many contexts, such as
11641 * Use templates
11642 * Use `std::variant`
11643 * Rely on the well-defined, safe, implicit conversions between pointer types
11645 ##### Enforcement
11647 * Force the elimination of C-style casts, except on a function with a `[[nodiscard]]` return
11648 * Warn if there are many functional style casts (there is an obvious problem in quantifying 'many')
11649 * The [type profile](#Pro-type-reinterpretcast) bans `reinterpret_cast`.
11650 * Warn against [identity casts](#Pro-type-identitycast) between pointer types, where the source and target types are the same (#Pro-type-identitycast)
11651 * Warn if a pointer cast could be [implicit](#Pro-type-implicitpointercast)
11653 ### <a name="Res-casts-named"></a>ES.49: If you must use a cast, use a named cast
11655 ##### Reason
11657 Readability. Error avoidance.
11658 Named casts are more specific than a C-style or functional cast, allowing the compiler to catch some errors.
11660 The named casts are:
11662 * `static_cast`
11663 * `const_cast`
11664 * `reinterpret_cast`
11665 * `dynamic_cast`
11666 * `std::move`         // `move(x)` is an rvalue reference to `x`
11667 * `std::forward`      // `forward<T>(x)` is an rvalue or an lvalue reference to `x` depending on `T`
11668 * `gsl::narrow_cast`  // `narrow_cast<T>(x)` is `static_cast<T>(x)`
11669 * `gsl::narrow`       // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
11671 ##### Example
11673     class B { /* ... */ };
11674     class D { /* ... */ };
11676     template<typename D> D* upcast(B* pb)
11677     {
11678         D* pd0 = pb;                        // error: no implicit conversion from B* to D*
11679         D* pd1 = (D*)pb;                    // legal, but what is done?
11680         D* pd2 = static_cast<D*>(pb);       // error: D is not derived from B
11681         D* pd3 = reinterpret_cast<D*>(pb);  // OK: on your head be it!
11682         D* pd4 = dynamic_cast<D*>(pb);      // OK: return nullptr
11683         // ...
11684     }
11686 The example was synthesized from real-world bugs where `D` used to be derived from `B`, but someone refactored the hierarchy.
11687 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).
11689 ##### Note
11691 When converting between types with no information loss (e.g. from `float` to
11692 `double` or `int64` from `int32`), brace initialization may be used instead.
11694     double d {some_float};
11695     int64_t i {some_int32};
11697 This makes it clear that the type conversion was intended and also prevents
11698 conversions between types that might result in loss of precision. (It is a
11699 compilation error to try to initialize a `float` from a `double` in this fashion,
11700 for example.)
11702 ##### Note
11704 `reinterpret_cast` can be essential, but the essential uses (e.g., turning a machine address into pointer) are not type safe:
11706     auto p = reinterpret_cast<Device_register>(0x800);  // inherently dangerous
11709 ##### Enforcement
11711 * Flag C-style and functional casts.
11712 * The [type profile](#Pro-type-reinterpretcast) bans `reinterpret_cast`.
11713 * The [type profile](#Pro-type-arithmeticcast) warns when using `static_cast` between arithmetic types.
11715 ### <a name="Res-casts-const"></a>ES.50: Don't cast away `const`
11717 ##### Reason
11719 It makes a lie out of `const`.
11720 If the variable is actually declared `const`, the result of "casting away `const`" is undefined behavior.
11722 ##### Example, bad
11724     void f(const int& x)
11725     {
11726         const_cast<int&>(x) = 42;   // BAD
11727     }
11729     static int i = 0;
11730     static const int j = 0;
11732     f(i); // silent side effect
11733     f(j); // undefined behavior
11735 ##### Example
11737 Sometimes, you may 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:
11739     class Bar;
11741     class Foo {
11742     public:
11743         // BAD, duplicates logic
11744         Bar& get_bar() {
11745             /* complex logic around getting a non-const reference to my_bar */
11746         }
11748         const Bar& get_bar() const {
11749             /* same complex logic around getting a const reference to my_bar */
11750         }
11751     private:
11752         Bar my_bar;
11753     };
11755 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`:
11757     class Foo {
11758     public:
11759         // not great, non-const calls const version but resorts to const_cast
11760         Bar& get_bar() {
11761             return const_cast<Bar&>(static_cast<const Foo&>(*this).get_bar());
11762         }
11763         const Bar& get_bar() const {
11764             /* the complex logic around getting a const reference to my_bar */
11765         }
11766     private:
11767         Bar my_bar;
11768     };
11770 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.
11772 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:
11774     class Foo {
11775     public:                         // good
11776               Bar& get_bar()       { return get_bar_impl(*this); }
11777         const Bar& get_bar() const { return get_bar_impl(*this); }
11778     private:
11779         Bar my_bar;
11781         template<class T>           // good, deduces whether T is const or non-const
11782         static auto get_bar_impl(T& t) -> decltype(t.get_bar())
11783             { /* the complex logic around getting a possibly-const reference to my_bar */ }
11784     };
11786 ##### Exception
11788 You may need to cast away `const` when calling `const`-incorrect functions.
11789 Prefer to wrap such functions in inline `const`-correct wrappers to encapsulate the cast in one place.
11791 ##### Example
11793 Sometimes, "cast away `const`" is to allow the updating of some transient information of an otherwise immutable object.
11794 Examples are caching, memoization, and precomputation.
11795 Such examples are often handled as well or better using `mutable` or an indirection than with a `const_cast`.
11797 Consider keeping previously computed results around for a costly operation:
11799     int compute(int x); // compute a value for x; assume this to be costly
11801     class Cache {   // some type implementing a cache for an int->int operation
11802     public:
11803         pair<bool, int> find(int x) const;   // is there a value for x?
11804         void set(int x, int v);             // make y the value for x
11805         // ...
11806     private:
11807         // ...
11808     };
11810     class X {
11811     public:
11812         int get_val(int x)
11813         {
11814             auto p = cache.find(x);
11815             if (p.first) return p.second;
11816             int val = compute(x);
11817             cache.set(x, val); // insert value for x
11818             return val;
11819         }
11820         // ...
11821     private:
11822         Cache cache;
11823     };
11825 Here, `get_val()` is logically constant, so we would like to make it a `const` member.
11826 To do this we still need to mutate `cache`, so people sometimes resort to a `const_cast`:
11828     class X {   // Suspicious solution based on casting
11829     public:
11830         int get_val(int x) const
11831         {
11832             auto p = cache.find(x);
11833             if (p.first) return p.second;
11834             int val = compute(x);
11835             const_cast<Cache&>(cache).set(x, val);   // ugly
11836             return val;
11837         }
11838         // ...
11839     private:
11840         Cache cache;
11841     };
11843 Fortunately, there is a better solution:
11844 State that `cache` is mutable even for a `const` object:
11846     class X {   // better solution
11847     public:
11848         int get_val(int x) const
11849         {
11850             auto p = cache.find(x);
11851             if (p.first) return p.second;
11852             int val = compute(x);
11853             cache.set(x, val);
11854             return val;
11855         }
11856         // ...
11857     private:
11858         mutable Cache cache;
11859     };
11861 An alternative solution would be to store a pointer to the `cache`:
11863     class X {   // OK, but slightly messier solution
11864     public:
11865         int get_val(int x) const
11866         {
11867             auto p = cache->find(x);
11868             if (p.first) return p.second;
11869             int val = compute(x);
11870             cache->set(x, val);
11871             return val;
11872         }
11873         // ...
11874     private:
11875         unique_ptr<Cache> cache;
11876     };
11878 That solution is the most flexible, but requires explicit construction and destruction of `*cache`
11879 (most likely in the constructor and destructor of `X`).
11881 In any variant, we must guard against data races on the `cache` in multi-threaded code, possibly using a `std::mutex`.
11883 ##### Enforcement
11885 * Flag `const_cast`s.
11886 * This rule is part of the [type-safety profile](#Pro-type-constcast) for the related Profile.
11888 ### <a name="Res-range-checking"></a>ES.55: Avoid the need for range checking
11890 ##### Reason
11892 Constructs that cannot overflow do not overflow (and usually run faster):
11894 ##### Example
11896     for (auto& x : v)      // print all elements of v
11897         cout << x << '\n';
11899     auto p = find(v, x);   // find x in v
11901 ##### Enforcement
11903 Look for explicit range checks and heuristically suggest alternatives.
11905 ### <a name="Res-move"></a>ES.56: Write `std::move()` only when you need to explicitly move an object to another scope
11907 ##### Reason
11909 We move, rather than copy, to avoid duplication and for improved performance.
11911 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).
11913 ##### Notes
11915 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.
11917 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`.
11919 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.
11921 ##### Example, bad
11923     void sink(X&& x);   // sink takes ownership of x
11925     void user()
11926     {
11927         X x;
11928         // error: cannot bind an lvalue to a rvalue reference
11929         sink(x);
11930         // OK: sink takes the contents of x, x must now be assumed to be empty
11931         sink(std::move(x));
11933         // ...
11935         // probably a mistake
11936         use(x);
11937     }
11939 Usually, a `std::move()` is used as an argument to a `&&` parameter.
11940 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.
11942     void f() {
11943         string s1 = "supercalifragilisticexpialidocious";
11945         string s2 = s1;             // ok, takes a copy
11946         assert(s1 == "supercalifragilisticexpialidocious");  // ok
11948         // bad, if you want to keep using s1's value
11949         string s3 = move(s1);
11951         // bad, assert will likely fail, s1 likely changed
11952         assert(s1 == "supercalifragilisticexpialidocious");
11953     }
11955 ##### Example
11957     void sink(unique_ptr<widget> p);  // pass ownership of p to sink()
11959     void f() {
11960         auto w = make_unique<widget>();
11961         // ...
11962         sink(std::move(w));               // ok, give to sink()
11963         // ...
11964         sink(w);    // Error: unique_ptr is carefully designed so that you cannot copy it
11965     }
11967 ##### Notes
11969 `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.
11970 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.
11972 Never write `std::move()` just because you've heard "it's more efficient."
11973 In general, don't believe claims of "efficiency" without data (???).
11974 In general, don't complicate your code without reason (??)
11976 ##### Example, bad
11978     vector<int> make_vector() {
11979         vector<int> result;
11980         // ... load result with data
11981         return std::move(result);       // bad; just write "return result;"
11982     }
11984 Never write `return move(local_variable);`, because the language already knows the variable is a move candidate.
11985 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.
11988 ##### Example, bad
11990     vector<int> v = std::move(make_vector());   // bad; the std::move is entirely redundant
11992 Never write `move` on a returned value such as `x = move(f());` where `f` returns by value.
11993 The language already knows that a returned value is a temporary object that can be moved from.
11995 ##### Example
11997     void mover(X&& x) {
11998         call_something(std::move(x));         // ok
11999         call_something(std::forward<X>(x));   // bad, don't std::forward an rvalue reference
12000         call_something(x);                    // suspicious, why not std::move?
12001     }
12003     template<class T>
12004     void forwarder(T&& t) {
12005         call_something(std::move(t));         // bad, don't std::move a forwarding reference
12006         call_something(std::forward<T>(t));   // ok
12007         call_something(t);                    // suspicious, why not std::forward?
12008     }
12010 ##### Enforcement
12012 * 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.
12013 * Flag functions taking an `S&&` parameter if there is no `const S&` overload to take care of lvalues.
12014 * Flag a `std::move`s argument passed to a parameter, except when the parameter type is one of the following: an `X&&` rvalue reference; a `T&&` forwarding reference where `T` is a template parameter type; or by value and the type is move-only.
12015 * Flag when `std::move` is applied to a forwarding reference (`T&&` where `T` is a template parameter type). Use `std::forward` instead.
12016 * Flag when `std::move` is applied to other than an rvalue reference. (More general case of the previous rule to cover the non-forwarding cases.)
12017 * Flag when `std::forward` is applied to an rvalue reference (`X&&` where `X` is a concrete type). Use `std::move` instead.
12018 * 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.)
12019 * 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.
12021 ### <a name="Res-new"></a>ES.60: Avoid `new` and `delete` outside resource management functions
12023 ##### Reason
12025 Direct resource management in application code is error-prone and tedious.
12027 ##### Note
12029 This is also known as the rule of "No naked `new`!"
12031 ##### Example, bad
12033     void f(int n)
12034     {
12035         auto p = new X[n];   // n default constructed Xs
12036         // ...
12037         delete[] p;
12038     }
12040 There can be code in the `...` part that causes the `delete` never to happen.
12042 **See also**: [R: Resource management](#S-resource)
12044 ##### Enforcement
12046 Flag naked `new`s and naked `delete`s.
12048 ### <a name="Res-del"></a>ES.61: Delete arrays using `delete[]` and non-arrays using `delete`
12050 ##### Reason
12052 That's what the language requires and mistakes can lead to resource release errors and/or memory corruption.
12054 ##### Example, bad
12056     void f(int n)
12057     {
12058         auto p = new X[n];   // n default constructed Xs
12059         // ...
12060         delete p;   // error: just delete the object p, rather than delete the array p[]
12061     }
12063 ##### Note
12065 This example not only violates the [no naked `new` rule](#Res-new) as in the previous example, it has many more problems.
12067 ##### Enforcement
12069 * If the `new` and the `delete` are in the same scope, mistakes can be flagged.
12070 * If the `new` and the `delete` are in a constructor/destructor pair, mistakes can be flagged.
12072 ### <a name="Res-arr2"></a>ES.62: Don't compare pointers into different arrays
12074 ##### Reason
12076 The result of doing so is undefined.
12078 ##### Example, bad
12080     void f()
12081     {
12082         int a1[7];
12083         int a2[9];
12084         if (&a1[5] < &a2[7]) {}       // bad: undefined
12085         if (0 < &a1[5] - &a2[7]) {}   // bad: undefined
12086     }
12088 ##### Note
12090 This example has many more problems.
12092 ##### Enforcement
12096 ### <a name="Res-slice"></a>ES.63: Don't slice
12098 ##### Reason
12100 Slicing -- that is, copying only part of an object using assignment or initialization -- most often leads to errors because
12101 the object was meant to be considered as a whole.
12102 In the rare cases where the slicing was deliberate the code can be surprising.
12104 ##### Example
12106     class Shape { /* ... */ };
12107     class Circle : public Shape { /* ... */ Point c; int r; };
12109     Circle c {{0, 0}, 42};
12110     Shape s {c};    // copy construct only the Shape part of Circle
12111     s = c;          // or copy assign only the Shape part of Circle
12113     void assign(const Shape& src, Shape& dest) {
12114         dest = src;
12115     }
12116     Circle c2 {{1, 1}, 43};
12117     assign(c, c2);   // oops, not the whole state is transferred
12118     assert(c == c2); // if we supply copying, we should also provide comparison,
12119                      // but this will likely return false
12121 The result will be meaningless because the center and radius will not be copied from `c` into `s`.
12122 The first defense against this is to [define the base class `Shape` not to allow this](#Rc-copy-virtual).
12124 ##### Alternative
12126 If you mean to slice, define an explicit operation to do so.
12127 This saves readers from confusion.
12128 For example:
12130     class Smiley : public Circle {
12131         public:
12132         Circle copy_circle();
12133         // ...
12134     };
12136     Smiley sm { /* ... */ };
12137     Circle c1 {sm};  // ideally prevented by the definition of Circle
12138     Circle c2 {sm.copy_circle()};
12140 ##### Enforcement
12142 Warn against slicing.
12144 ### <a name="Res-construct"></a>ES.64: Use the `T{e}`notation for construction
12146 ##### Reason
12148 The `T{e}` construction syntax makes it explicit that construction is desired.
12149 The `T{e}` construction syntax doesn't allow narrowing.
12150 `T{e}` is the only safe and general expression for constructing a value of type `T` from an expression `e`.
12151 The casts notations `T(e)` and `(T)e` are neither safe nor general.
12153 ##### Example
12155 For built-in types, the construction notation protects against narrowing and reinterpretation
12157     void use(char ch, int i, double d, char* p, long long lng)
12158     {
12159         int x1 = int{ch};     // OK, but redundant
12160         int x2 = int{d};      // error: double->int narrowing; use a cast if you need to
12161         int x3 = int{p};      // error: pointer to->int; use a reinterpret_cast if you really need to
12162         int x4 = int{lng};    // error: long long->int narrowing; use a cast if you need to
12164         int y1 = int(ch);     // OK, but redundant
12165         int y2 = int(d);      // bad: double->int narrowing; use a cast if you need to
12166         int y3 = int(p);      // bad: pointer to->int; use a reinterpret_cast if you really need to
12167         int y4 = int(lng);    // bad: long long->int narrowing; use a cast if you need to
12169         int z1 = (int)ch;     // OK, but redundant
12170         int z2 = (int)d;      // bad: double->int narrowing; use a cast if you need to
12171         int z3 = (int)p;      // bad: pointer to->int; use a reinterpret_cast if you really need to
12172         int z4 = (int)lng;    // bad: long long->int narrowing; use a cast if you need to
12173     }
12175 The integer to/from pointer conversions are implementation defined when using the `T(e)` or `(T)e` notations, and non-portable
12176 between platforms with different integer and pointer sizes.
12178 ##### Note
12180 [Avoid casts](#Res-casts) (explicit type conversion) and if you must [prefer named casts](#Res-casts-named).
12182 ##### Note
12184 When unambiguous, the `T` can be left out of `T{e}`.
12186     complex<double> f(complex<double>);
12188     auto z = f({2*pi, 1});
12190 ##### Note
12192 The construction notation is the most general [initializer notation](#Res-list).
12194 ##### Exception
12196 `std::vector` and other containers were defined before we had `{}` as a notation for construction.
12197 Consider:
12199     vector<string> vs {10};                           // ten empty strings
12200     vector<int> vi1 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  // ten elements 1..10
12201     vector<int> vi2 {10};                             // one element with the value 10
12203 How do we get a `vector` of 10 default initialized `int`s?
12205     vector<int> v3(10); // ten elements with value 0
12207 The use of `()` rather than `{}` for number of elements is conventional (going back to the early 1980s), hard to change, but still
12208 a design error: for a container where the element type can be confused with the number of elements, we have an ambiguity that
12209 must be resolved.
12210 The conventional resolution is to interpret `{10}` as a list of one element and use `(10)` to distinguish a size.
12212 This mistake need not be repeated in new code.
12213 We can define a type to represent the number of elements:
12215     struct Count { int n; };
12217     template<typename T>
12218     class Vector {
12219     public:
12220         Vector(Count n);                     // n default-initialized elements
12221         Vector(initializer_list<T> init);    // init.size() elements
12222         // ...
12223     };
12225     Vector<int> v1{10};
12226     Vector<int> v2{Count{10}};
12227     Vector<Count> v3{Count{10}};    // yes, there is still a very minor problem
12229 The main problem left is to find a suitable name for `Count`.
12231 ##### Enforcement
12233 Flag the C-style `(T)e` and functional-style `T(e)` casts.
12236 ### <a name="Res-deref"></a>ES.65: Don't dereference an invalid pointer
12238 ##### Reason
12240 Dereferencing an invalid pointer, such as `nullptr`, is undefined behavior, typically leading to immediate crashes,
12241 wrong results, or memory corruption.
12243 ##### Note
12245 This rule is an obvious and well-known language rule, but can be hard to follow.
12246 It takes good coding style, library support, and static analysis to eliminate violations without major overhead.
12247 This is a major part of the discussion of [C++'s resource- and type-safety model](#Stroustrup15).
12249 **See also**:
12251 * Use [RAII](#Rr-raii) to avoid lifetime problems.
12252 * Use [unique_ptr](#Rf-unique_ptr) to avoid lifetime problems.
12253 * Use [shared_ptr](#Rf-shared_ptr) to avoid lifetime problems.
12254 * Use [references](#Rf-ptr-ref) when `nullptr` isn't a possibility.
12255 * Use [not_null](#Rf-not_null) to catch unexpected `nullptr` early.
12256 * Use the [bounds profile](#SS-bounds) to avoid range errors.
12259 ##### Example
12261     void f()
12262     {
12263         int x = 0;
12264         int* p = &x;
12266         if (condition()) {
12267             int y = 0;
12268             p = &y;
12269         } // invalidates p
12271         *p = 42;            // BAD, p might be invalid if the branch was taken
12272     }
12274 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).
12276     void f1()
12277     {
12278         int x = 0;
12279         int* p = &x;
12281         int y = 0;
12282         if (condition()) {
12283             p = &y;
12284         }
12286         *p = 42;            // OK, p points to x or y and both are still in scope
12287     }
12289 Unfortunately, most invalid pointer problems are harder to spot and harder to fix.
12291 ##### Example
12293     void f(int* p)
12294     {
12295         int x = *p; // BAD: how do we know that p is valid?
12296     }
12298 There is a huge amount of such code.
12299 Most works -- after lots of testing -- but in isolation it is impossible to tell whether `p` could be the `nullptr`.
12300 Consequently, this is also a major source of errors.
12301 There are many approaches to dealing with this potential problem:
12303     void f1(int* p) // deal with nullptr
12304     {
12305         if (!p) {
12306             // deal with nullptr (allocate, return, throw, make p point to something, whatever
12307         }
12308         int x = *p;
12309     }
12311 There are two potential problems with testing for `nullptr`:
12313 * it is not always obvious what to do what to do if we find `nullptr`
12314 * the test can be redundant and/or relatively expensive
12315 * it is not obvious if the test is to protect against a violation or part of the required logic.
12318     void f2(int* p) // state that p is not supposed to be nullptr
12319     {
12320         assert(p);
12321         int x = *p;
12322     }
12324 This would carry a cost only when the assertion checking was enabled and would give a compiler/analyzer useful information.
12325 This would work even better if/when C++ gets direct support for contracts:
12327     void f3(int* p) // state that p is not supposed to be nullptr
12328         [[expects: p]]
12329     {
12330         int x = *p;
12331     }
12333 Alternatively, we could use `gsl::not_null` to ensure that `p` is not the `nullptr`.
12335     void f(not_null<int*> p)
12336     {
12337         int x = *p;
12338     }
12340 These remedies take care of `nullptr` only.
12341 Remember that there are other ways of getting an invalid pointer.
12343 ##### Example
12345     void f(int* p)  // old code, doesn't use owner
12346     {
12347         delete p;
12348     }
12350     void g()        // old code: uses naked new
12351     {
12352         auto q = new int{7};
12353         f(q);
12354         int x = *q; // BAD: dereferences invalid pointer
12355     }
12357 ##### Example
12359     void f()
12360     {
12361         vector<int> v(10);
12362         int* p = &v[5];
12363         v.push_back(99); // could reallocate v's elements
12364         int x = *p; // BAD: dereferences potentially invalid pointer
12365     }
12367 ##### Enforcement
12369 This rule is part of the [lifetime safety profile](#SS-lifetime)
12371 * Flag a dereference of a pointer that points to an object that has gone out of scope
12372 * Flag a dereference of a pointer that may have been invalidated by assigning a `nullptr`
12373 * Flag a dereference of a pointer that may have been invalidated by a `delete`
12374 * Flag a dereference to a pointer to a container element that may have been invalidated by dereference
12377 ## ES.stmt: Statements
12379 Statements control the flow of control (except for function calls and exception throws, which are expressions).
12381 ### <a name="Res-switch-if"></a>ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice
12383 ##### Reason
12385 * Readability.
12386 * Efficiency: A `switch` compares against constants and is usually better optimized than a series of tests in an `if`-`then`-`else` chain.
12387 * A `switch` enables some heuristic consistency checking. For example, have all values of an `enum` been covered? If not, is there a `default`?
12389 ##### Example
12391     void use(int n)
12392     {
12393         switch (n) {   // good
12394         case 0:
12395             // ...
12396             break;
12397         case 7:
12398             // ...
12399             break;
12400         default:
12401             // ...
12402             break;
12403         }
12404     }
12406 rather than:
12408     void use2(int n)
12409     {
12410         if (n == 0)   // bad: if-then-else chain comparing against a set of constants
12411             // ...
12412         else if (n == 7)
12413             // ...
12414     }
12416 ##### Enforcement
12418 Flag `if`-`then`-`else` chains that check against constants (only).
12420 ### <a name="Res-for-range"></a>ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice
12422 ##### Reason
12424 Readability. Error prevention. Efficiency.
12426 ##### Example
12428     for (gsl::index i = 0; i < v.size(); ++i)   // bad
12429             cout << v[i] << '\n';
12431     for (auto p = v.begin(); p != v.end(); ++p)   // bad
12432         cout << *p << '\n';
12434     for (auto& x : v)    // OK
12435         cout << x << '\n';
12437     for (gsl::index i = 1; i < v.size(); ++i) // touches two elements: can't be a range-for
12438         cout << v[i] + v[i - 1] << '\n';
12440     for (gsl::index i = 0; i < v.size(); ++i) // possible side effect: can't be a range-for
12441         cout << f(v, &v[i]) << '\n';
12443     for (gsl::index i = 0; i < v.size(); ++i) { // body messes with loop variable: can't be a range-for
12444         if (i % 2 == 0)
12445             continue;   // skip even elements
12446         else
12447             cout << v[i] << '\n';
12448     }
12450 A human or a good static analyzer may determine that there really isn't a side effect on `v` in `f(v, &v[i])` so that the loop can be rewritten.
12452 "Messing with the loop variable" in the body of a loop is typically best avoided.
12454 ##### Note
12456 Don't use expensive copies of the loop variable of a range-`for` loop:
12458     for (string s : vs) // ...
12460 This will copy each elements of `vs` into `s`. Better:
12462     for (string& s : vs) // ...
12464 Better still, if the loop variable isn't modified or copied:
12466     for (const string& s : vs) // ...
12468 ##### Enforcement
12470 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.
12472 ### <a name="Res-for-while"></a>ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable
12474 ##### Reason
12476 Readability: the complete logic of the loop is visible "up front". The scope of the loop variable can be limited.
12478 ##### Example
12480     for (gsl::index i = 0; i < vec.size(); i++) {
12481         // do work
12482     }
12484 ##### Example, bad
12486     int i = 0;
12487     while (i < vec.size()) {
12488         // do work
12489         i++;
12490     }
12492 ##### Enforcement
12496 ### <a name="Res-while-for"></a>ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable
12498 ##### Reason
12500 Readability.
12502 ##### Example
12504     int events = 0;
12505     for (; wait_for_event(); ++events) {  // bad, confusing
12506         // ...
12507     }
12509 The "event loop" is misleading because the `events` counter has nothing to do with the loop condition (`wait_for_event()`).
12510 Better
12512     int events = 0;
12513     while (wait_for_event()) {      // better
12514         ++events;
12515         // ...
12516     }
12518 ##### Enforcement
12520 Flag actions in `for`-initializers and `for`-increments that do not relate to the `for`-condition.
12522 ### <a name="Res-for-init"></a>ES.74: Prefer to declare a loop variable in the initializer part of a `for`-statement
12524 ##### Reason
12526 Limit the loop variable visibility to the scope of the loop.
12527 Avoid using the loop variable for other purposes after the loop.
12529 ##### Example
12531     for (int i = 0; i < 100; ++i) {   // GOOD: i var is visible only inside the loop
12532         // ...
12533     }
12535 ##### Example, don't
12537     int j;                            // BAD: j is visible outside the loop
12538     for (j = 0; j < 100; ++j) {
12539         // ...
12540     }
12541     // j is still visible here and isn't needed
12543 **See also**: [Don't use a variable for two unrelated purposes](#Res-recycle)
12545 ##### Example
12547     for (string s; cin >> s; ) {
12548         cout << s << '\n';
12549     }
12551 ##### Enforcement
12553 Warn when a variable modified inside the `for`-statement is declared outside the loop and not being used outside the loop.
12555 **Discussion**: Scoping the loop variable to the loop body also helps code optimizers greatly. Recognizing that the induction variable
12556 is only accessible in the loop body unblocks optimizations such as hoisting, strength reduction, loop-invariant code motion, etc.
12558 ### <a name="Res-do"></a>ES.75: Avoid `do`-statements
12560 ##### Reason
12562 Readability, avoidance of errors.
12563 The termination condition is at the end (where it can be overlooked) and the condition is not checked the first time through.
12565 ##### Example
12567     int x;
12568     do {
12569         cin >> x;
12570         // ...
12571     } while (x < 0);
12573 ##### Note
12575 Yes, there are genuine examples where a `do`-statement is a clear statement of a solution, but also many bugs.
12577 ##### Enforcement
12579 Flag `do`-statements.
12581 ### <a name="Res-goto"></a>ES.76: Avoid `goto`
12583 ##### Reason
12585 Readability, avoidance of errors. There are better control structures for humans; `goto` is for machine generated code.
12587 ##### Exception
12589 Breaking out of a nested loop.
12590 In that case, always jump forwards.
12592     for (int i = 0; i < imax; ++i)
12593         for (int j = 0; j < jmax; ++j) {
12594             if (a[i][j] > elem_max) goto finished;
12595             // ...
12596         }
12597     finished:
12598     // ...
12600 ##### Example, bad
12602 There is a fair amount of use of the C goto-exit idiom:
12604     void f()
12605     {
12606         // ...
12607             goto exit;
12608         // ...
12609             goto exit;
12610         // ...
12611     exit:
12612         // ... common cleanup code ...
12613     }
12615 This is an ad-hoc simulation of destructors.
12616 Declare your resources with handles with destructors that clean up.
12617 If for some reason you cannot handle all cleanup with destructors for the variables used,
12618 consider `gsl::finally()` as a cleaner and more reliable alternative to `goto exit`
12620 ##### Enforcement
12622 * 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.
12624 ### <a name="Res-continue"></a>ES.77: Minimize the use of `break` and `continue` in loops
12626 ##### Reason
12628  In a non-trivial loop body, it is easy to overlook a `break` or a `continue`.
12630  A `break` in a loop has a dramatically different meaning than a `break` in a `switch`-statement
12631  (and you can have `switch`-statement in a loop and a loop in a `switch`-case).
12633 ##### Example
12635     ???
12637 ##### Alternative
12639 Often, a loop that requires a `break` is a good candidate for a function (algorithm), in which case the `break` becomes a `return`.
12641     ???
12643 Often, a loop that uses `continue` can equivalently and as clearly be expressed by an `if`-statement.
12645     ???
12647 ##### Note
12649 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):
12652 ##### Enforcement
12656 ### <a name="Res-break"></a>ES.78: Always end a non-empty `case` with a `break`
12658 ##### Reason
12660 Accidentally leaving out a `break` is a fairly common bug.
12661 A deliberate fallthrough can be a maintenance hazard and should be rare and explicit.
12663 ##### Example
12665     switch (eventType) {
12666     case Information:
12667         update_status_bar();
12668         break;
12669     case Warning:
12670         write_event_log();
12671         // Bad - implicit fallthrough
12672     case Error:
12673         display_error_window();
12674         break;
12675     }
12677 Multiple case labels of a single statement is OK:
12679     switch (x) {
12680     case 'a':
12681     case 'b':
12682     case 'f':
12683         do_something(x);
12684         break;
12685     }
12687 ##### Exceptions
12689 In rare cases if fallthrough is deemed appropriate, be explicit and use the `[[fallthrough]]` annotation:
12691     switch (eventType) {
12692     case Information:
12693         update_status_bar();
12694         break;
12695     case Warning:
12696         write_event_log();
12697         [[fallthrough]];
12698     case Error:
12699         display_error_window();
12700         break;
12701     }
12703 ##### Note
12705 ##### Enforcement
12707 Flag all implicit fallthroughs from non-empty `case`s.
12710 ### <a name="Res-default"></a>ES.79: Use `default` to handle common cases (only)
12712 ##### Reason
12714  Code clarity.
12715  Improved opportunities for error detection.
12717 ##### Example
12719     enum E { a, b, c , d };
12721     void f1(E x)
12722     {
12723         switch (x) {
12724         case a:
12725             do_something();
12726             break;
12727         case b:
12728             do_something_else();
12729             break;
12730         default:
12731             take_the_default_action();
12732             break;
12733         }
12734     }
12736 Here it is clear that there is a default action and that cases `a` and `b` are special.
12738 ##### Example
12740 But what if there is no default action and you mean to handle only specific cases?
12741 In that case, have an empty default or else it is impossible to know if you meant to handle all cases:
12743     void f2(E x)
12744     {
12745         switch (x) {
12746         case a:
12747             do_something();
12748             break;
12749         case b:
12750             do_something_else();
12751             break;
12752         default:
12753             // do nothing for the rest of the cases
12754             break;
12755         }
12756     }
12758 If you leave out the `default`, a maintainer and/or a compiler may reasonably assume that you intended to handle all cases:
12760     void f2(E x)
12761     {
12762         switch (x) {
12763         case a:
12764             do_something();
12765             break;
12766         case b:
12767         case c:
12768             do_something_else();
12769             break;
12770         }
12771     }
12773 Did you forget case `d` or deliberately leave it out?
12774 Forgetting a case typically happens when a case is added to an enumeration and the person doing so fails to add it to every
12775 switch over the enumerators.
12777 ##### Enforcement
12779 Flag `switch`-statements over an enumeration that don't handle all enumerators and do not have a `default`.
12780 This may yield too many false positives in some code bases; if so, flag only `switch`es that handle most but not all cases
12781 (that was the strategy of the very first C++ compiler).
12783 ### <a name="Res-noname"></a>ES.84: Don't try to declare a local variable with no name
12785 ##### Reason
12787 There is no such thing.
12788 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.
12790 ##### Example, bad
12792     void f()
12793     {
12794         lock<mutex>{mx};   // Bad
12795         // ...
12796     }
12798 This declares an unnamed `lock` object that immediately goes out of scope at the point of the semicolon.
12799 This is not an uncommon mistake.
12800 In particular, this particular example can lead to hard-to find race conditions.
12802 ##### Note
12804 Unnamed function arguments are fine.
12806 ##### Enforcement
12808 Flag statements that are just a temporary.
12810 ### <a name="Res-empty"></a>ES.85: Make empty statements visible
12812 ##### Reason
12814 Readability.
12816 ##### Example
12818     for (i = 0; i < max; ++i);   // BAD: the empty statement is easily overlooked
12819     v[i] = f(v[i]);
12821     for (auto x : v) {           // better
12822         // nothing
12823     }
12824     v[i] = f(v[i]);
12826 ##### Enforcement
12828 Flag empty statements that are not blocks and don't contain comments.
12830 ### <a name="Res-loop-counter"></a>ES.86: Avoid modifying loop control variables inside the body of raw for-loops
12832 ##### Reason
12834 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.
12836 ##### Example
12838     for (int i = 0; i < 10; ++i) {
12839         // no updates to i -- ok
12840     }
12842     for (int i = 0; i < 10; ++i) {
12843         //
12844         if (/* something */) ++i; // BAD
12845         //
12846     }
12848     bool skip = false;
12849     for (int i = 0; i < 10; ++i) {
12850         if (skip) { skip = false; continue; }
12851         //
12852         if (/* something */) skip = true;  // Better: using two variables for two concepts.
12853         //
12854     }
12856 ##### Enforcement
12858 Flag variables that are potentially updated (have a non-`const` use) in both the loop control iteration-expression and the loop body.
12861 ### <a name="Res-if"></a>ES.87: Don't add redundant `==` or `!=` to conditions
12863 ##### Reason
12865 Doing so avoids verbosity and eliminates some opportunities for mistakes.
12866 Helps make style consistent and conventional.
12868 ##### Example
12870 By definition, a condition in an `if`-statement, `while`-statement, or a `for`-statement selects between `true` and `false`.
12871 A numeric value is compared to `0` and a pointer value to `nullptr`.
12873     // These all mean "if `p` is not `nullptr`"
12874     if (p) { ... }            // good
12875     if (p != 0) { ... }       // redundant `!=0`; bad: don't use 0 for pointers
12876     if (p != nullptr) { ... } // redundant `!=nullptr`, not recommended
12878 Often, `if (p)` is read as "if `p` is valid" which is a direct expression of the programmers intent,
12879 whereas `if (p != nullptr)` would be a long-winded workaround.
12881 ##### Example
12883 This rule is especially useful when a declaration is used as a condition
12885     if (auto pc = dynamic_cast<Circle>(ps)) { ... } // execute if ps points to a kind of Circle, good
12887     if (auto pc = dynamic_cast<Circle>(ps); pc != nullptr) { ... } // not recommended
12889 ##### Example
12891 Note that implicit conversions to bool are applied in conditions.
12892 For example:
12894     for (string s; cin >> s; ) v.push_back(s);
12896 This invokes `istream`'s `operator bool()`.
12898 ##### Note
12900 Explicit comparison of an integer to `0` is in general not redundant.
12901 The reason is that (as opposed to pointers and Booleans) an integer often has more than two reasonable values.
12902 Furthermore `0` (zero) is often used to indicate success.
12903 Consequently, it is best to be specific about the comparison.
12905     void f(int i)
12906     {
12907         if (i)            // suspect
12908         // ...
12909         if (i == success) // possibly better
12910         // ...
12911     }
12913 Always remember that an integer can have more than two values.
12915 ##### Example, bad
12917 It has been noted that
12919     if(strcmp(p1, p2)) { ... }   // are the two C-style strings equal? (mistake!)
12921 is a common beginners error.
12922 If you use C-style strings, you must know the `<cstring>` functions well.
12923 Being verbose and writing
12925     if(strcmp(p1, p2) != 0) { ... }   // are the two C-style strings equal? (mistake!)
12927 would not in itself save you.
12929 ##### Note
12931 The opposite condition is most easily expressed using a negation:
12933     // These all mean "if `p` is `nullptr`"
12934     if (!p) { ... }           // good
12935     if (p == 0) { ... }       // redundant `== 0`; bad: don't use `0` for pointers
12936     if (p == nullptr) { ... } // redundant `== nullptr`, not recommended
12938 ##### Enforcement
12940 Easy, just check for redundant use of `!=` and `==` in conditions.
12944 ## <a name="SS-numbers"></a>Arithmetic
12946 ### <a name="Res-mix"></a>ES.100: Don't mix signed and unsigned arithmetic
12948 ##### Reason
12950 Avoid wrong results.
12952 ##### Example
12954     int x = -3;
12955     unsigned int y = 7;
12957     cout << x - y << '\n';  // unsigned result, possibly 4294967286
12958     cout << x + y << '\n';  // unsigned result: 4
12959     cout << x * y << '\n';  // unsigned result, possibly 4294967275
12961 It is harder to spot the problem in more realistic examples.
12963 ##### Note
12965 Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts.
12966 This precludes consistency. Use `gsl::index` for subscripts; [see ES.107](#Res-subscripts).
12968 ##### Enforcement
12970 * Compilers already know and sometimes warn.
12971 * (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`.
12974 ### <a name="Res-unsigned"></a>ES.101: Use unsigned types for bit manipulation
12976 ##### Reason
12978 Unsigned types support bit manipulation without surprises from sign bits.
12980 ##### Example
12982     unsigned char x = 0b1010'1010;
12983     unsigned char y = ~x;   // y == 0b0101'0101;
12985 ##### Note
12987 Unsigned types can also be useful for modulo arithmetic.
12988 However, if you want modulo arithmetic add
12989 comments as necessary noting the reliance on wraparound behavior, as such code
12990 can be surprising for many programmers.
12992 ##### Enforcement
12994 * Just about impossible in general because of the use of unsigned subscripts in the standard library
12995 * ???
12997 ### <a name="Res-signed"></a>ES.102: Use signed types for arithmetic
12999 ##### Reason
13001 Because most arithmetic is assumed to be signed;
13002 `x - y` yields a negative number when `y > x` except in the rare cases where you really want modulo arithmetic.
13004 ##### Example
13006 Unsigned arithmetic can yield surprising results if you are not expecting it.
13007 This is even more true for mixed signed and unsigned arithmetic.
13009     template<typename T, typename T2>
13010     T subtract(T x, T2 y)
13011     {
13012         return x - y;
13013     }
13015     void test()
13016     {
13017         int s = 5;
13018         unsigned int us = 5;
13019         cout << subtract(s, 7) << '\n';       // -2
13020         cout << subtract(us, 7u) << '\n';     // 4294967294
13021         cout << subtract(s, 7u) << '\n';      // -2
13022         cout << subtract(us, 7) << '\n';      // 4294967294
13023         cout << subtract(s, us + 2) << '\n';  // -2
13024         cout << subtract(us, s + 2) << '\n';  // 4294967294
13025     }
13027 Here we have been very explicit about what's happening,
13028 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`?
13030 ##### Exception
13032 Use unsigned types if you really want modulo arithmetic - add
13033 comments as necessary noting the reliance on overflow behavior, as such code
13034 is going to be surprising for many programmers.
13036 ##### Example
13038 The standard library uses unsigned types for subscripts.
13039 The built-in array uses signed types for subscripts.
13040 This makes surprises (and bugs) inevitable.
13042     int a[10];
13043     for (int i = 0; i < 10; ++i) a[i] = i;
13044     vector<int> v(10);
13045     // compares signed to unsigned; some compilers warn, but we should not
13046     for (gsl::index i = 0; i < v.size(); ++i) v[i] = i;
13048     int a2[-2];         // error: negative size
13050     // OK, but the number of ints (4294967294) is so large that we should get an exception
13051     vector<int> v2(-2);
13053  Use `gsl::index` for subscripts; [see ES.107](#Res-subscripts).
13055 ##### Enforcement
13057 * Flag mixed signed and unsigned arithmetic
13058 * Flag results of unsigned arithmetic assigned to or printed as signed.
13059 * Flag negative literals (e.g. `-2`) used as container subscripts.
13060 * (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`.
13063 ### <a name="Res-overflow"></a>ES.103: Don't overflow
13065 ##### Reason
13067 Overflow usually makes your numeric algorithm meaningless.
13068 Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.
13070 ##### Example, bad
13072     int a[10];
13073     a[10] = 7;   // bad
13075     int n = 0;
13076     while (n++ < 10)
13077         a[n - 1] = 9; // bad (twice)
13079 ##### Example, bad
13081     int n = numeric_limits<int>::max();
13082     int m = n + 1;   // bad
13084 ##### Example, bad
13086     int area(int h, int w) { return h * w; }
13088     auto a = area(10'000'000, 100'000'000);   // bad
13090 ##### Exception
13092 Use unsigned types if you really want modulo arithmetic.
13094 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
13096 ##### Enforcement
13100 ### <a name="Res-underflow"></a>ES.104: Don't underflow
13102 ##### Reason
13104 Decrementing a value beyond a minimum value can lead to memory corruption and undefined behavior.
13106 ##### Example, bad
13108     int a[10];
13109     a[-2] = 7;   // bad
13111     int n = 101;
13112     while (n--)
13113         a[n - 1] = 9;   // bad (twice)
13115 ##### Exception
13117 Use unsigned types if you really want modulo arithmetic.
13119 ##### Enforcement
13123 ### <a name="Res-zero"></a>ES.105: Don't divide by zero
13125 ##### Reason
13127 The result is undefined and probably a crash.
13129 ##### Note
13131 This also applies to `%`.
13133 ##### Example, bad
13135     double divide(int a, int b) {
13136         // BAD, should be checked (e.g., in a precondition)
13137         return a / b;
13138     }
13140 ##### Example, good
13142     double divide(int a, int b) {
13143         // good, address via precondition (and replace with contracts once C++ gets them)
13144         Expects(b != 0);
13145         return a / b;
13146     }
13148     double divide(int a, int b) {
13149         // good, address via check
13150         return b ? a / b : quiet_NaN<double>();
13151     }
13153 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
13155 ##### Enforcement
13157 * Flag division by an integral value that could be zero
13160 ### <a name="Res-nonnegative"></a>ES.106: Don't try to avoid negative values by using `unsigned`
13162 ##### Reason
13164 Choosing `unsigned` implies many changes to the usual behavior of integers, including modulo arithmetic,
13165 can suppress warnings related to overflow,
13166 and opens the door for errors related to signed/unsigned mixes.
13167 Using `unsigned` doesn't actually eliminate the possibility of negative values.
13169 ##### Example
13171     unsigned int u1 = -2;   // Valid: the value of u1 is 4294967294
13172     int i1 = -2;
13173     unsigned int u2 = i1;   // Valid: the value of u2 is 4294967294
13174     int i2 = u2;            // Valid: the value of i2 is -2
13176 These problems with such (perfectly legal) constructs are hard to spot in real code and are the source of many real-world errors.
13177 Consider:
13179     unsigned area(unsigned height, unsigned width) { return height*width; } // [see also](#Ri-expects)
13180     // ...
13181     int height;
13182     cin >> height;
13183     auto a = area(height, 2);   // if the input is -2 a becomes 4294967292
13185 Remember that `-1` when assigned to an `unsigned int` becomes the largest `unsigned int`.
13186 Also, since unsigned arithmetic is modulo arithmetic the multiplication didn't overflow, it wrapped around.
13188 ##### Example
13190     unsigned max = 100000;    // "accidental typo", I mean to say 10'000
13191     unsigned short x = 100;
13192     while (x < max) x += 100; // infinite loop
13194 Had `x` been a signed `short`, we could have warned about the undefined behavior upon overflow.
13196 ##### Alternatives
13198 * use signed integers and check for `x >= 0`
13199 * use a positive integer type
13200 * use an integer subrange type
13201 * `Assert(-1 < x)`
13203 For example
13205     struct Positive {
13206         int val;
13207         Positive(int x) :val{x} { Assert(0 < x); }
13208         operator int() { return val; }
13209     };
13211     int f(Positive arg) { return arg; }
13213     int r1 = f(2);
13214     int r2 = f(-2);  // throws
13216 ##### Note
13220 ##### Enforcement
13222 See ES.100 Enforcements.
13225 ### <a name="Res-subscripts"></a>ES.107: Don't use `unsigned` for subscripts, prefer `gsl::index`
13227 ##### Reason
13229 To avoid signed/unsigned confusion.
13230 To enable better optimization.
13231 To enable better error detection.
13232 To avoid the pitfalls with `auto` and `int`.
13234 ##### Example, bad
13236     vector<int> vec = /*...*/;
13238     for (int i = 0; i < vec.size(); i += 2)                    // may not be big enough
13239         cout << vec[i] << '\n';
13240     for (unsigned i = 0; i < vec.size(); i += 2)               // risk wraparound
13241         cout << vec[i] << '\n';
13242     for (auto i = 0; i < vec.size(); i += 2)                   // may not be big enough
13243         cout << vec[i] << '\n';
13244     for (vector<int>::size_type i = 0; i < vec.size(); i += 2) // verbose
13245         cout << vec[i] << '\n';
13246     for (auto i = vec.size()-1; i >= 0; i -= 2)                // bug
13247         cout << vec[i] << '\n';
13248     for (int i = vec.size()-1; i >= 0; i -= 2)                 // may not be big enough
13249         cout << vec[i] << '\n';
13251 ##### Example, good
13253     vector<int> vec = /*...*/;
13255     for (gsl::index i = 0; i < vec.size(); i += 2)             // ok
13256         cout << vec[i] << '\n';
13257     for (gsl::index i = vec.size()-1; i >= 0; i -= 2)          // ok
13258         cout << vec[i] << '\n';
13260 ##### Note
13262 The built-in array uses signed subscripts.
13263 The standard-library containers use unsigned subscripts.
13264 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).
13265 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`.
13267 ##### Example
13269     template<typename T>
13270     struct My_container {
13271     public:
13272         // ...
13273         T& operator[](gsl::index i);    // not unsigned
13274         // ...
13275     };
13277 ##### Example
13279     ??? demonstrate improved code generation and potential for error detection ???
13281 ##### Alternatives
13283 Alternatives for users
13285 * use algorithms
13286 * use range-for
13287 * use iterators/pointers
13289 ##### Enforcement
13291 * Very tricky as long as the standard-library containers get it wrong.
13292 * (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`.
13297 # <a name="S-performance"></a>Per: Performance
13299 ??? should this section be in the main guide???
13301 This section contains rules for people who need high performance or low-latency.
13302 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.
13303 The rules in this section are more restrictive and intrusive than what is needed for many (most) applications.
13304 Do not blindly try to follow them in general code: achieving the goals of low latency requires extra work.
13306 Performance rule summary:
13308 * [Per.1: Don't optimize without reason](#Rper-reason)
13309 * [Per.2: Don't optimize prematurely](#Rper-Knuth)
13310 * [Per.3: Don't optimize something that's not performance critical](#Rper-critical)
13311 * [Per.4: Don't assume that complicated code is necessarily faster than simple code](#Rper-simple)
13312 * [Per.5: Don't assume that low-level code is necessarily faster than high-level code](#Rper-low)
13313 * [Per.6: Don't make claims about performance without measurements](#Rper-measure)
13314 * [Per.7: Design to enable optimization](#Rper-efficiency)
13315 * [Per.10: Rely on the static type system](#Rper-type)
13316 * [Per.11: Move computation from run time to compile time](#Rper-Comp)
13317 * [Per.12: Eliminate redundant aliases](#Rper-alias)
13318 * [Per.13: Eliminate redundant indirections](#Rper-indirect)
13319 * [Per.14: Minimize the number of allocations and deallocations](#Rper-alloc)
13320 * [Per.15: Do not allocate on a critical branch](#Rper-alloc0)
13321 * [Per.16: Use compact data structures](#Rper-compact)
13322 * [Per.17: Declare the most used member of a time-critical struct first](#Rper-struct)
13323 * [Per.18: Space is time](#Rper-space)
13324 * [Per.19: Access memory predictably](#Rper-access)
13325 * [Per.30: Avoid context switches on the critical path](#Rper-context)
13327 ### <a name="Rper-reason"></a>Per.1: Don't optimize without reason
13329 ##### Reason
13331 If there is no need for optimization, the main result of the effort will be more errors and higher maintenance costs.
13333 ##### Note
13335 Some people optimize out of habit or because it's fun.
13339 ### <a name="Rper-Knuth"></a>Per.2: Don't optimize prematurely
13341 ##### Reason
13343 Elaborately optimized code is usually larger and harder to change than unoptimized code.
13347 ### <a name="Rper-critical"></a>Per.3: Don't optimize something that's not performance critical
13349 ##### Reason
13351 Optimizing a non-performance-critical part of a program has no effect on system performance.
13353 ##### Note
13355 If your program spends most of its time waiting for the web or for a human, optimization of in-memory computation is probably useless.
13357 Put another way: If your program spends 4% of its processing time doing
13358 computation A and 40% of its time doing computation B, a 50% improvement on A is
13359 only as impactful as a 5% improvement on B. (If you don't even know how much
13360 time is spent on A or B, see <a href="#Rper-reason">Per.1</a> and <a
13361 href="#Rper-Knuth">Per.2</a>.)
13363 ### <a name="Rper-simple"></a>Per.4: Don't assume that complicated code is necessarily faster than simple code
13365 ##### Reason
13367 Simple code can be very fast. Optimizers sometimes do marvels with simple code
13369 ##### Example, good
13371     // clear expression of intent, fast execution
13373     vector<uint8_t> v(100000);
13375     for (auto& c : v)
13376         c = ~c;
13378 ##### Example, bad
13380     // intended to be faster, but is actually slower
13382     vector<uint8_t> v(100000);
13384     for (size_t i = 0; i < v.size(); i += sizeof(uint64_t))
13385     {
13386         uint64_t& quad_word = *reinterpret_cast<uint64_t*>(&v[i]);
13387         quad_word = ~quad_word;
13388     }
13390 ##### Note
13396 ### <a name="Rper-low"></a>Per.5: Don't assume that low-level code is necessarily faster than high-level code
13398 ##### Reason
13400 Low-level code sometimes inhibits optimizations. Optimizers sometimes do marvels with high-level code.
13402 ##### Note
13408 ### <a name="Rper-measure"></a>Per.6: Don't make claims about performance without measurements
13410 ##### Reason
13412 The field of performance is littered with myth and bogus folklore.
13413 Modern hardware and optimizers defy naive assumptions; even experts are regularly surprised.
13415 ##### Note
13417 Getting good performance measurements can be hard and require specialized tools.
13419 ##### Note
13421 A few simple microbenchmarks using Unix `time` or the standard-library `<chrono>` can help dispel the most obvious myths.
13422 If you can't measure your complete system accurately, at least try to measure a few of your key operations and algorithms.
13423 A profiler can help tell you which parts of your system are performance critical.
13424 Often, you will be surprised.
13428 ### <a name="Rper-efficiency"></a>Per.7: Design to enable optimization
13430 ##### Reason
13432 Because we often need to optimize the initial design.
13433 Because a design that ignores the possibility of later improvement is hard to change.
13435 ##### Example
13437 From the C (and C++) standard:
13439     void qsort (void* base, size_t num, size_t size, int (*compar)(const void*, const void*));
13441 When did you even want to sort memory?
13442 Really, we sort sequences of elements, typically stored in containers.
13443 A call to `qsort` throws away much useful information (e.g., the element type), forces the user to repeat information
13444 already known (e.g., the element size), and forces the user to write extra code (e.g., a function to compare `double`s).
13445 This implies added work for the programmer, is error-prone, and deprives the compiler of information needed for optimization.
13447     double data[100];
13448     // ... fill a ...
13450     // 100 chunks of memory of sizeof(double) starting at
13451     // address data using the order defined by compare_doubles
13452     qsort(data, 100, sizeof(double), compare_doubles);
13454 From the point of view of interface design is that `qsort` throws away useful information.
13456 We can do better (in C++98)
13458     template<typename Iter>
13459         void sort(Iter b, Iter e);  // sort [b:e)
13461     sort(data, data + 100);
13463 Here, we use the compiler's knowledge about the size of the array, the type of elements, and how to compare `double`s.
13465 With C++11 plus [concepts](#SS-concepts), we can do better still
13467     // Sortable specifies that c must be a
13468     // random-access sequence of elements comparable with <
13469     void sort(Sortable& c);
13471     sort(c);
13473 The key is to pass sufficient information for a good implementation to be chosen.
13474 In this, the `sort` interfaces shown here still have a weakness:
13475 They implicitly rely on the element type having less-than (`<`) defined.
13476 To complete the interface, we need a second version that accepts a comparison criteria:
13478     // compare elements of c using p
13479     void sort(Sortable& c, Predicate<Value_type<Sortable>> p);
13481 The standard-library specification of `sort` offers those two versions,
13482 but the semantics is expressed in English rather than code using concepts.
13484 ##### Note
13486 Premature optimization is said to be [the root of all evil](#Rper-Knuth), but that's not a reason to despise performance.
13487 It is never premature to consider what makes a design amenable to improvement, and improved performance is a commonly desired improvement.
13488 Aim to build a set of habits that by default results in efficient, maintainable, and optimizable code.
13489 In particular, when you write a function that is not a one-off implementation detail, consider
13491 * Information passing:
13492 Prefer clean [interfaces](#S-interfaces) carrying sufficient information for later improvement of implementation.
13493 Note that information flows into and out of an implementation through the interfaces we provide.
13494 * Compact data: By default, [use compact data](#Rper-compact), such as `std::vector` and [access it in a systematic fashion](#Rper-access).
13495 If you think you need a linked structure, try to craft the interface so that this structure isn't seen by users.
13496 * Function argument passing and return:
13497 Distinguish between mutable and non-mutable data.
13498 Don't impose a resource management burden on your users.
13499 Don't impose spurious run-time indirections on your users.
13500 Use [conventional ways](#Rf-conventional) of passing information through an interface;
13501 unconventional and/or "optimized" ways of passing data can seriously complicate later reimplementation.
13502 * Abstraction:
13503 Don't overgeneralize; a design that tries to cater for every possible use (and misuse) and defers every design decision for later
13504 (using compile-time or run-time indirections) is usually a complicated, bloated, hard-to-understand mess.
13505 Generalize from concrete examples, preserving performance as we generalize.
13506 Do not generalize based on mere speculation about future needs.
13507 The ideal is zero-overhead generalization.
13508 * Libraries:
13509 Use libraries with good interfaces.
13510 If no library is available build one yourself and imitate the interface style from a good library.
13511 The [standard library](#S-stdlib) is a good first place to look for inspiration.
13512 * Isolation:
13513 Isolate your code from messy and/or old-style code by providing an interface of your choosing to it.
13514 This is sometimes called "providing a wrapper" for the useful/necessary but messy code.
13515 Don't let bad designs "bleed into" your code.
13517 ##### Example
13519 Consider:
13521     template <class ForwardIterator, class T>
13522     bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
13524 `binary_search(begin(c), end(c), 7)` will tell you whether `7` is in `c` or not.
13525 However, it will not tell you where that `7` is or whether there are more than one `7`.
13527 Sometimes, just passing the minimal amount of information back (here, `true` or `false`) is sufficient, but a good interface passes
13528 needed information back to the caller. Therefore, the standard library also offers
13530     template <class ForwardIterator, class T>
13531     ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val);
13533 `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.
13535 However, `lower_bound` still doesn't return enough information for all uses, so the standard library also offers
13537     template <class ForwardIterator, class T>
13538     pair<ForwardIterator, ForwardIterator>
13539     equal_range(ForwardIterator first, ForwardIterator last, const T& val);
13541 `equal_range` returns a `pair` of iterators specifying the first and one beyond last match.
13543     auto r = equal_range(begin(c), end(c), 7);
13544     for (auto p = r.first; p != r.second; ++p)
13545         cout << *p << '\n';
13547 Obviously, these three interfaces are implemented by the same basic code.
13548 They are simply three ways of presenting the basic binary search algorithm to users,
13549 ranging from the simplest ("make simple things simple!")
13550 to returning complete, but not always needed, information ("don't hide useful information").
13551 Naturally, crafting such a set of interfaces requires experience and domain knowledge.
13553 ##### Note
13555 Do not simply craft the interface to match the first implementation and the first use case you think of.
13556 Once your first initial implementation is complete, review it; once you deploy it, mistakes will be hard to remedy.
13558 ##### Note
13560 A need for efficiency does not imply a need for [low-level code](#Rper-low).
13561 High-level code does not imply slow or bloated.
13563 ##### Note
13565 Things have costs.
13566 Don't be paranoid about costs (modern computers really are very fast),
13567 but have a rough idea of the order of magnitude of cost of what you use.
13568 For example, have a rough idea of the cost of
13569 a memory access,
13570 a function call,
13571 a string comparison,
13572 a system call,
13573 a disk access,
13574 and a message through a network.
13576 ##### Note
13578 If you can only think of one implementation, you probably don't have something for which you can devise a stable interface.
13579 Maybe, it is just an implementation detail - not every piece of code needs a stable interface - but pause and consider.
13580 One question that can be useful is
13581 "what interface would be needed if this operation should be implemented using multiple threads? be vectorized?"
13583 ##### Note
13585 This rule does not contradict the [Don't optimize prematurely](#Rper-Knuth) rule.
13586 It complements it encouraging developers enable later - appropriate and non-premature - optimization, if and where needed.
13588 ##### Enforcement
13590 Tricky.
13591 Maybe looking for `void*` function arguments will find examples of interfaces that hinder later optimization.
13593 ### <a name="Rper-type"></a>Per.10: Rely on the static type system
13595 ##### Reason
13597 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.
13601 ### <a name="Rper-Comp"></a>Per.11: Move computation from run time to compile time
13603 ##### Reason
13605 To decrease code size and run time.
13606 To avoid data races by using constants.
13607 To catch errors at compile time (and thus eliminate the need for error-handling code).
13609 ##### Example
13611     double square(double d) { return d*d; }
13612     static double s2 = square(2);    // old-style: dynamic initialization
13614     constexpr double ntimes(double d, int n)   // assume 0 <= n
13615     {
13616             double m = 1;
13617             while (n--) m *= d;
13618             return m;
13619     }
13620     constexpr double s3 {ntimes(2, 3)};  // modern-style: compile-time initialization
13622 Code like the initialization of `s2` isn't uncommon, especially for initialization that's a bit more complicated than `square()`.
13623 However, compared to the initialization of `s3` there are two problems:
13625 * we suffer the overhead of a function call at run time
13626 * `s2` just might be accessed by another thread before the initialization happens.
13628 Note: you can't have a data race on a constant.
13630 ##### Example
13632 Consider a popular technique for providing a handle for storing small objects in the handle itself and larger ones on the heap.
13634     constexpr int on_stack_max = 20;
13636     template<typename T>
13637     struct Scoped {     // store a T in Scoped
13638             // ...
13639         T obj;
13640     };
13642     template<typename T>
13643     struct On_heap {    // store a T on the free store
13644             // ...
13645             T* objp;
13646     };
13648     template<typename T>
13649     using Handle = typename std::conditional<(sizeof(T) <= on_stack_max),
13650                         Scoped<T>,      // first alternative
13651                         On_heap<T>      // second alternative
13652                    >::type;
13654     void f()
13655     {
13656         Handle<double> v1;                   // the double goes on the stack
13657         Handle<std::array<double, 200>> v2;  // the array goes on the free store
13658         // ...
13659     }
13661 Assume that `Scoped` and `On_heap` provide compatible user interfaces.
13662 Here we compute the optimal type to use at compile time.
13663 There are similar techniques for selecting the optimal function to call.
13665 ##### Note
13667 The ideal is {not} to try execute everything at compile time.
13668 Obviously, most computations depend on inputs so they can't be moved to compile time,
13669 but beyond that logical constraint is the fact that complex compile-time computation can seriously increase compile times
13670 and complicate debugging.
13671 It is even possible to slow down code by compile-time computation.
13672 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.
13674 ##### Enforcement
13676 * Look for simple functions that might be constexpr (but are not).
13677 * Look for functions called with all constant-expression arguments.
13678 * Look for macros that could be constexpr.
13680 ### <a name="Rper-alias"></a>Per.12: Eliminate redundant aliases
13684 ### <a name="Rper-indirect"></a>Per.13: Eliminate redundant indirections
13688 ### <a name="Rper-alloc"></a>Per.14: Minimize the number of allocations and deallocations
13692 ### <a name="Rper-alloc0"></a>Per.15: Do not allocate on a critical branch
13696 ### <a name="Rper-compact"></a>Per.16: Use compact data structures
13698 ##### Reason
13700 Performance is typically dominated by memory access times.
13704 ### <a name="Rper-struct"></a>Per.17: Declare the most used member of a time-critical struct first
13708 ### <a name="Rper-space"></a>Per.18: Space is time
13710 ##### Reason
13712 Performance is typically dominated by memory access times.
13716 ### <a name="Rper-access"></a>Per.19: Access memory predictably
13718 ##### Reason
13720 Performance is very sensitive to cache performance and cache algorithms favor simple (usually linear) access to adjacent data.
13722 ##### Example
13724     int matrix[rows][cols];
13726     // bad
13727     for (int c = 0; c < cols; ++c)
13728         for (int r = 0; r < rows; ++r)
13729             sum += matrix[r][c];
13731     // good
13732     for (int r = 0; r < rows; ++r)
13733         for (int c = 0; c < cols; ++c)
13734             sum += matrix[r][c];
13736 ### <a name="Rper-context"></a>Per.30: Avoid context switches on the critical path
13740 # <a name="S-concurrency"></a>CP: Concurrency and parallelism
13742 We often want our computers to do many tasks at the same time (or at least appear to do them at the same time).
13743 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)
13744 and so do the basic facilities for expressing concurrency and parallelism.
13745 Here, we articulate principles and rules for using the ISO standard C++ facilities for expressing basic concurrency and parallelism.
13747 Threads are the machine-level foundation for concurrent and parallel programming.
13748 Threads allow running multiple sections of a program independently, while sharing
13749 the same memory. Concurrent programming is tricky,
13750 because protecting shared data between threads is easier said than done.
13751 Making existing single-threaded code execute concurrently can be
13752 as trivial as adding `std::async` or `std::thread` strategically, or it can
13753 necessitate a full rewrite, depending on whether the original code was written
13754 in a thread-friendly way.
13756 The concurrency/parallelism rules in this document are designed with three goals
13757 in mind:
13759 * To help in writing code that is amenable to being used in a threaded
13760   environment
13761 * To show clean, safe ways to use the threading primitives offered by the
13762   standard library
13763 * To offer guidance on what to do when concurrency and parallelism aren't giving
13764   the performance gains needed
13766 It is also important to note that concurrency in C++ is an unfinished
13767 story. C++11 introduced many core concurrency primitives, C++14 and C++17 improved on
13768 them, and there is much interest in making the writing of
13769 concurrent programs in C++ even easier. We expect some of the library-related
13770 guidance here to change significantly over time.
13772 This section needs a lot of work (obviously).
13773 Please note that we start with rules for relative non-experts.
13774 Real experts must wait a bit;
13775 contributions are welcome,
13776 but please think about the majority of programmers who are struggling to get their concurrent programs correct and performant.
13778 Concurrency and parallelism rule summary:
13780 * [CP.1: Assume that your code will run as part of a multi-threaded program](#Rconc-multi)
13781 * [CP.2: Avoid data races](#Rconc-races)
13782 * [CP.3: Minimize explicit sharing of writable data](#Rconc-data)
13783 * [CP.4: Think in terms of tasks, rather than threads](#Rconc-task)
13784 * [CP.8: Don't try to use `volatile` for synchronization](#Rconc-volatile)
13785 * [CP.9: Whenever feasible use tools to validate your concurrent code](#Rconc-tools)
13787 **See also**:
13789 * [CP.con: Concurrency](#SScp-con)
13790 * [CP.par: Parallelism](#SScp-par)
13791 * [CP.mess: Message passing](#SScp-mess)
13792 * [CP.vec: Vectorization](#SScp-vec)
13793 * [CP.free: Lock-free programming](#SScp-free)
13794 * [CP.etc: Etc. concurrency rules](#SScp-etc)
13796 ### <a name="Rconc-multi"></a>CP.1: Assume that your code will run as part of a multi-threaded program
13798 ##### Reason
13800 It's hard to be certain that concurrency isn't used now or won't be used sometime in the future.
13801 Code gets reused.
13802 Libraries not using threads may be used from some other part of a program that does use threads.
13803 Note that this rule applies most urgently to library code and least urgently to stand-alone applications.
13804 However, over time, code fragments can turn up in unexpected places.
13806 ##### Example, bad
13808     double cached_computation(double x)
13809     {
13810         // bad: these two statics cause data races in multi-threaded usage
13811         static double cached_x = 0.0;
13812         static double cached_result = COMPUTATION_OF_ZERO;
13813         double result;
13815         if (cached_x == x)
13816             return cached_result;
13817         result = computation(x);
13818         cached_x = x;
13819         cached_result = result;
13820         return result;
13821     }
13823 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.
13825 There are several ways that this example could be made safe for a multi-threaded environment:
13827 * Delegate concurrency concerns upwards to the caller.
13828 * Mark the `static` variables as `thread_local` (which might make caching less effective).
13829 * Implement concurrency control, for example, protecting the two `static` variables with a `static` lock (which might reduce performance).
13830 * Have the caller provide the memory to be used for the cache, thereby delegating both memory allocation and concurrency concerns upwards to the caller.
13831 * Refuse to build and/or run in a multi-threaded environment.
13832 * Provide two implementations, one which is used in single-threaded environments and another which is used in multi-threaded environments.
13834 ##### Exception
13836 Code that is never run in a multi-threaded environment.
13838 Be careful: there are many examples where code that was "known" to never run in a multi-threaded program
13839 was run as part of a multi-threaded program, often years later.
13840 Typically, such programs lead to a painful effort to remove data races.
13841 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.
13843 ### <a name="Rconc-races"></a>CP.2: Avoid data races
13845 ##### Reason
13847 Unless you do, nothing is guaranteed to work and subtle errors will persist.
13849 ##### Note
13851 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.
13852 For further information of how to use synchronization well to eliminate data races, please consult a good book about concurrency.
13854 ##### Example, bad
13856 There are many examples of data races that exist, some of which are running in
13857 production software at this very moment. One very simple example:
13859     int get_id() {
13860       static int id = 1;
13861       return id++;
13862     }
13864 The increment here is an example of a data race. This can go wrong in many ways,
13865 including:
13867 * Thread A loads the value of `id`, the OS context switches A out for some
13868   period, during which other threads create hundreds of IDs. Thread A is then
13869   allowed to run again, and `id` is written back to that location as A's read of
13870   `id` plus one.
13871 * Thread A and B load `id` and increment it simultaneously.  They both get the
13872   same ID.
13874 Local static variables are a common source of data races.
13876 ##### Example, bad:
13878     void f(fstream&  fs, regex pattern)
13879     {
13880         array<double, max> buf;
13881         int sz = read_vec(fs, buf, max);            // read from fs into buf
13882         gsl::span<double> s {buf};
13883         // ...
13884         auto h1 = async([&]{ sort(std::execution::par, s); });     // spawn a task to sort
13885         // ...
13886         auto h2 = async([&]{ return find_all(buf, sz, pattern); });   // spawn a task to find matches
13887         // ...
13888     }
13890 Here, we have a (nasty) data race on the elements of `buf` (`sort` will both read and write).
13891 All data races are nasty.
13892 Here, we managed to get a data race on data on the stack.
13893 Not all data races are as easy to spot as this one.
13895 ##### Example, bad:
13897     // code not controlled by a lock
13899     unsigned val;
13901     if (val < 5) {
13902         // ... other thread can change val here ...
13903         switch (val) {
13904         case 0: // ...
13905         case 1: // ...
13906         case 2: // ...
13907         case 3: // ...
13908         case 4: // ...
13909         }
13910     }
13912 Now, a compiler that does not know that `val` can change will  most likely implement that `switch` using a jump table with five entries.
13913 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.
13914 Really, "all bets are off" if you get a data race.
13915 Actually, it can be worse still: by looking at the generated code you may be able to determine where the stray jump will go for a given value;
13916 this can be a security risk.
13918 ##### Enforcement
13920 Some is possible, do at least something.
13921 There are commercial and open-source tools that try to address this problem,
13922 but be aware that solutions have costs and blind spots.
13923 Static tools often have many false positives and run-time tools often have a significant cost.
13924 We hope for better tools.
13925 Using multiple tools can catch more problems than a single one.
13927 There are other ways you can mitigate the chance of data races:
13929 * Avoid global data
13930 * Avoid `static` variables
13931 * More use of value types on the stack (and don't pass pointers around too much)
13932 * More use of immutable data (literals, `constexpr`, and `const`)
13934 ### <a name="Rconc-data"></a>CP.3: Minimize explicit sharing of writable data
13936 ##### Reason
13938 If you don't share writable data, you can't have a data race.
13939 The less sharing you do, the less chance you have to forget to synchronize access (and get data races).
13940 The less sharing you do, the less chance you have to wait on a lock (so performance can improve).
13942 ##### Example
13944     bool validate(const vector<Reading>&);
13945     Graph<Temp_node> temperature_gradiants(const vector<Reading>&);
13946     Image altitude_map(const vector<Reading>&);
13947     // ...
13949     void process_readings(const vector<Reading>& surface_readings)
13950     {
13951         auto h1 = async([&] { if (!validate(surface_readings)) throw Invalid_data{}; });
13952         auto h2 = async([&] { return temperature_gradiants(surface_readings); });
13953         auto h3 = async([&] { return altitude_map(surface_readings); });
13954         // ...
13955         h1.get();
13956         auto v2 = h2.get();
13957         auto v3 = h3.get();
13958         // ...
13959     }
13961 Without those `const`s, we would have to review every asynchronously invoked function for potential data races on `surface_readings`.
13962 Making `surface_readings` be `const` (with respect to this function) allow reasoning using only the function body.
13964 ##### Note
13966 Immutable data can be safely and efficiently shared.
13967 No locking is needed: You can't have a data race on a constant.
13968 See also [CP.mess: Message Passing](#SScp-mess) and [CP.31: prefer pass by value](#Rconc-data-by-value).
13970 ##### Enforcement
13975 ### <a name="Rconc-task"></a>CP.4: Think in terms of tasks, rather than threads
13977 ##### Reason
13979 A `thread` is an implementation concept, a way of thinking about the machine.
13980 A task is an application notion, something you'd like to do, preferably concurrently with other tasks.
13981 Application concepts are easier to reason about.
13983 ##### Example
13985     void some_fun() {
13986         std::string msg, msg2;
13987         std::thread publisher([&] { msg = "Hello"; });       // bad: less expressive
13988                                                              //      and more error-prone
13989         auto pubtask = std::async([&] { msg2 = "Hello"; });  // OK
13990         // ...
13991         publisher.join();
13992     }
13994 ##### Note
13996 With the exception of `async()`, the standard-library facilities are low-level, machine-oriented, threads-and-lock level.
13997 This is a necessary foundation, but we have to try to raise the level of abstraction: for productivity, for reliability, and for performance.
13998 This is a potent argument for using higher level, more applications-oriented libraries (if possibly, built on top of standard-library facilities).
14000 ##### Enforcement
14004 ### <a name="Rconc-volatile"></a>CP.8: Don't try to use `volatile` for synchronization
14006 ##### Reason
14008 In C++, unlike some other languages, `volatile` does not provide atomicity, does not synchronize between threads,
14009 and does not prevent instruction reordering (neither compiler nor hardware).
14010 It simply has nothing to do with concurrency.
14012 ##### Example, bad:
14014     int free_slots = max_slots; // current source of memory for objects
14016     Pool* use()
14017     {
14018         if (int n = free_slots--) return &pool[n];
14019     }
14021 Here we have a problem:
14022 This is perfectly good code in a single-threaded program, but have two threads execute this and
14023 there is a race condition on `free_slots` so that two threads might get the same value and `free_slots`.
14024 That's (obviously) a bad data race, so people trained in other languages may try to fix it like this:
14026     volatile int free_slots = max_slots; // current source of memory for objects
14028     Pool* use()
14029     {
14030         if (int n = free_slots--) return &pool[n];
14031     }
14033 This has no effect on synchronization: The data race is still there!
14035 The C++ mechanism for this is `atomic` types:
14037     atomic<int> free_slots = max_slots; // current source of memory for objects
14039     Pool* use()
14040     {
14041         if (int n = free_slots--) return &pool[n];
14042     }
14044 Now the `--` operation is atomic,
14045 rather than a read-increment-write sequence where another thread might get in-between the individual operations.
14047 ##### Alternative
14049 Use `atomic` types where you might have used `volatile` in some other language.
14050 Use a `mutex` for more complicated examples.
14052 ##### See also
14054 [(rare) proper uses of `volatile`](#Rconc-volatile2)
14056 ### <a name="Rconc-tools"></a>CP.9: Whenever feasible use tools to validate your concurrent code
14058 Experience shows that concurrent code is exceptionally hard to get right
14059 and that compile-time checking, run-time checks, and testing are less effective at finding concurrency errors
14060 than they are at finding errors in sequential code.
14061 Subtle concurrency errors can have dramatically bad effects, including memory corruption and deadlocks.
14063 ##### Example
14065     ???
14067 ##### Note
14069 Thread safety is challenging, often getting the better of experienced programmers: tooling is an important strategy to mitigate those risks.
14070 There are many tools "out there", both commercial and open-source tools, both research and production tools.
14071 Unfortunately people's needs and constraints differ so dramatically that we cannot make specific recommendations,
14072 but we can mention:
14074 * Static enforcement tools: both [clang](http://clang.llvm.org/docs/ThreadSafetyAnalysis.html)
14075 and some older versions of [GCC](https://gcc.gnu.org/wiki/ThreadSafetyAnnotation)
14076 have some support for static annotation of thread safety properties.
14077 Consistent use of this technique turns many classes of thread-safety errors into compile-time errors.
14078 The annotations are generally local (marking a particular member variable as guarded by a particular mutex),
14079 and are usually easy to learn. However, as with many static tools, it can often present false negatives;
14080 cases that should have been caught but were allowed.
14082 * dynamic enforcement tools: Clang's [Thread Sanitizer](http://clang.llvm.org/docs/ThreadSanitizer.html) (aka TSAN)
14083 is a powerful example of dynamic tools: it changes the build and execution of your program to add bookkeeping on memory access,
14084 absolutely identifying data races in a given execution of your binary.
14085 The cost for this is both memory (5-10x in most cases) and CPU slowdown (2-20x).
14086 Dynamic tools like this are best when applied to integration tests, canary pushes, or unittests that operate on multiple threads.
14087 Workload matters: When TSAN identifies a problem, it is effectively always an actual data race,
14088 but it can only identify races seen in a given execution.
14090 ##### Enforcement
14092 It is up to an application builder to choose which support tools are valuable for a particular applications.
14094 ## <a name="SScp-con"></a>CP.con: Concurrency
14096 This section focuses on relatively ad-hoc uses of multiple threads communicating through shared data.
14098 * For parallel algorithms, see [parallelism](#SScp-par)
14099 * For inter-task communication without explicit sharing, see [messaging](#SScp-mess)
14100 * For vector parallel code, see [vectorization](#SScp-vec)
14101 * For lock-free programming, see [lock free](#SScp-free)
14103 Concurrency rule summary:
14105 * [CP.20: Use RAII, never plain `lock()`/`unlock()`](#Rconc-raii)
14106 * [CP.21: Use `std::lock()` or `std::scoped_lock` to acquire multiple `mutex`es](#Rconc-lock)
14107 * [CP.22: Never call unknown code while holding a lock (e.g., a callback)](#Rconc-unknown)
14108 * [CP.23: Think of a joining `thread` as a scoped container](#Rconc-join)
14109 * [CP.24: Think of a `thread` as a global container](#Rconc-detach)
14110 * [CP.25: Prefer `gsl::joining_thread` over `std::thread`](#Rconc-joining_thread)
14111 * [CP.26: Don't `detach()` a thread](#Rconc-detached_thread)
14112 * [CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer](#Rconc-data-by-value)
14113 * [CP.32: To share ownership between unrelated `thread`s use `shared_ptr`](#Rconc-shared)
14114 * [CP.40: Minimize context switching](#Rconc-switch)
14115 * [CP.41: Minimize thread creation and destruction](#Rconc-create)
14116 * [CP.42: Don't `wait` without a condition](#Rconc-wait)
14117 * [CP.43: Minimize time spent in a critical section](#Rconc-time)
14118 * [CP.44: Remember to name your `lock_guard`s and `unique_lock`s](#Rconc-name)
14119 * [CP.50: Define a `mutex` together with the data it guards. Use `synchronized_value<T>` where possible](#Rconc-mutex)
14120 * ??? when to use a spinlock
14121 * ??? when to use `try_lock()`
14122 * ??? when to prefer `lock_guard` over `unique_lock`
14123 * ??? Time multiplexing
14124 * ??? when/how to use `new thread`
14126 ### <a name="Rconc-raii"></a>CP.20: Use RAII, never plain `lock()`/`unlock()`
14128 ##### Reason
14130 Avoids nasty errors from unreleased locks.
14132 ##### Example, bad
14134     mutex mtx;
14136     void do_stuff()
14137     {
14138         mtx.lock();
14139         // ... do stuff ...
14140         mtx.unlock();
14141     }
14143 Sooner or later, someone will forget the `mtx.unlock()`, place a `return` in the `... do stuff ...`, throw an exception, or something.
14145     mutex mtx;
14147     void do_stuff()
14148     {
14149         unique_lock<mutex> lck {mtx};
14150         // ... do stuff ...
14151     }
14153 ##### Enforcement
14155 Flag calls of member `lock()` and `unlock()`.  ???
14158 ### <a name="Rconc-lock"></a>CP.21: Use `std::lock()` or `std::scoped_lock` to acquire multiple `mutex`es
14160 ##### Reason
14162 To avoid deadlocks on multiple `mutex`es.
14164 ##### Example
14166 This is asking for deadlock:
14168     // thread 1
14169     lock_guard<mutex> lck1(m1);
14170     lock_guard<mutex> lck2(m2);
14172     // thread 2
14173     lock_guard<mutex> lck2(m2);
14174     lock_guard<mutex> lck1(m1);
14176 Instead, use `lock()`:
14178     // thread 1
14179     lock(m1, m2);
14180     lock_guard<mutex> lck1(m1, adopt_lock);
14181     lock_guard<mutex> lck2(m2, adopt_lock);
14183     // thread 2
14184     lock(m2, m1);
14185     lock_guard<mutex> lck2(m2, adopt_lock);
14186     lock_guard<mutex> lck1(m1, adopt_lock);
14188 or (better, but C++17 only):
14190     // thread 1
14191     scoped_lock<mutex, mutex> lck1(m1, m2);
14193     // thread 2
14194     scoped_lock<mutex, mutex> lck2(m2, m1);
14196 Here, the writers of `thread1` and `thread2` are still not agreeing on the order of the `mutex`es, but order no longer matters.
14198 ##### Note
14200 In real code, `mutex`es are rarely named to conveniently remind the programmer of an intended relation and intended order of acquisition.
14201 In real code, `mutex`es are not always conveniently acquired on consecutive lines.
14203 In C++17 it's possible to write plain
14205     lock_guard lck1(m1, adopt_lock);
14207 and have the `mutex` type deduced.
14209 ##### Enforcement
14211 Detect the acquisition of multiple `mutex`es.
14212 This is undecidable in general, but catching common simple examples (like the one above) is easy.
14215 ### <a name="Rconc-unknown"></a>CP.22: Never call unknown code while holding a lock (e.g., a callback)
14217 ##### Reason
14219 If you don't know what a piece of code does, you are risking deadlock.
14221 ##### Example
14223     void do_this(Foo* p)
14224     {
14225         lock_guard<mutex> lck {my_mutex};
14226         // ... do something ...
14227         p->act(my_data);
14228         // ...
14229     }
14231 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),
14232 it may call `do_this` (recursively) and cause a deadlock on `my_mutex`.
14233 Maybe it will lock on a different mutex and not return in a reasonable time, causing delays to any code calling `do_this`.
14235 ##### Example
14237 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.
14238 Such problem can often be solved by using a `recursive_mutex`. For example:
14240     recursive_mutex my_mutex;
14242     template<typename Action>
14243     void do_something(Action f)
14244     {
14245         unique_lock<recursive_mutex> lck {my_mutex};
14246         // ... do something ...
14247         f(this);    // f will do something to *this
14248         // ...
14249     }
14251 If, as it is likely, `f()` invokes operations on `*this`, we must make sure that the object's invariant holds before the call.
14253 ##### Enforcement
14255 * Flag calling a virtual function with a non-recursive `mutex` held
14256 * Flag calling a callback with a non-recursive `mutex` held
14259 ### <a name="Rconc-join"></a>CP.23: Think of a joining `thread` as a scoped container
14261 ##### Reason
14263 To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a `thread`.
14264 If a `thread` joins, we can safely pass pointers to objects in the scope of the `thread` and its enclosing scopes.
14266 ##### Example
14268     void f(int* p)
14269     {
14270         // ...
14271         *p = 99;
14272         // ...
14273     }
14274     int glob = 33;
14276     void some_fct(int* p)
14277     {
14278         int x = 77;
14279         joining_thread t0(f, &x);           // OK
14280         joining_thread t1(f, p);            // OK
14281         joining_thread t2(f, &glob);        // OK
14282         auto q = make_unique<int>(99);
14283         joining_thread t3(f, q.get());      // OK
14284         // ...
14285     }
14287 A `gsl::joining_thread` is a `std::thread` with a destructor that joins and that cannot be `detached()`.
14288 By "OK" we mean that the object will be in scope ("live") for as long as a `thread` can use the pointer to it.
14289 The fact that `thread`s run concurrently doesn't affect the lifetime or ownership issues here;
14290 these `thread`s can be seen as just a function object called from `some_fct`.
14292 ##### Enforcement
14294 Ensure that `joining_thread`s don't `detach()`.
14295 After that, the usual lifetime and ownership (for local objects) enforcement applies.
14297 ### <a name="Rconc-detach"></a>CP.24: Think of a `thread` as a global container
14299 ##### Reason
14301 To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a `thread`.
14302 If a `thread` is detached, we can safely pass pointers to static and free store objects (only).
14304 ##### Example
14306     void f(int* p)
14307     {
14308         // ...
14309         *p = 99;
14310         // ...
14311     }
14313     int glob = 33;
14315     void some_fct(int* p)
14316     {
14317         int x = 77;
14318         std::thread t0(f, &x);           // bad
14319         std::thread t1(f, p);            // bad
14320         std::thread t2(f, &glob);        // OK
14321         auto q = make_unique<int>(99);
14322         std::thread t3(f, q.get());      // bad
14323         // ...
14324         t0.detach();
14325         t1.detach();
14326         t2.detach();
14327         t3.detach();
14328         // ...
14329     }
14331 By "OK" we mean that the object will be in scope ("live") for as long as a `thread` can use the pointers to it.
14332 By "bad" we mean that a `thread` may use a pointer after the pointed-to object is destroyed.
14333 The fact that `thread`s run concurrently doesn't affect the lifetime or ownership issues here;
14334 these `thread`s can be seen as just a function object called from `some_fct`.
14336 ##### Note
14338 Even objects with static storage duration can be problematic if used from detached threads: if the
14339 thread continues until the end of the program, it might be running concurrently with the destruction
14340 of objects with static storage duration, and thus accesses to such objects might race.
14342 ##### Note
14344 This rule is redundant if you [don't `detach()`](#Rconc-detached_thread) and [use `gsl::joining_thread`](#Rconc-joining_thread).
14345 However, converting code to follow those guidelines could be difficult and even impossible for third-party libraries.
14346 In such cases, the rule becomes essential for lifetime safety and type safety.
14349 In general, it is undecidable whether a `detach()` is executed for a `thread`, but simple common cases are easily detected.
14350 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;
14351 After that, the usual lifetime and ownership (for global objects) enforcement applies.
14353 ##### Enforcement
14355 Flag attempts to pass local variables to a thread that might `detach()`.
14357 ### <a name="Rconc-joining_thread"></a>CP.25: Prefer `gsl::joining_thread` over `std::thread`
14359 ##### Reason
14361 A `joining_thread` is a thread that joins at the end of its scope.
14362 Detached threads are hard to monitor.
14363 It is harder to ensure absence of errors in detached threads (and potentially detached threads)
14365 ##### Example, bad
14367     void f() { std::cout << "Hello "; }
14369     struct F {
14370         void operator()() { std::cout << "parallel world "; }
14371     };
14373     int main()
14374     {
14375         std::thread t1{f};      // f() executes in separate thread
14376         std::thread t2{F()};    // F()() executes in separate thread
14377     }  // spot the bugs
14379 ##### Example
14381     void f() { std::cout << "Hello "; }
14383     struct F {
14384         void operator()() { std::cout << "parallel world "; }
14385     };
14387     int main()
14388     {
14389         std::thread t1{f};      // f() executes in separate thread
14390         std::thread t2{F()};    // F()() executes in separate thread
14392         t1.join();
14393         t2.join();
14394     }  // one bad bug left
14397 ##### Example, bad
14399 The code determining whether to `join()` or `detach()` may be complicated and even decided in the thread of functions called from it or functions called by the function that creates a thread:
14401     void tricky(thread* t, int n)
14402     {
14403         // ...
14404         if (is_odd(n))
14405             t->detach();
14406         // ...
14407     }
14409     void use(int n)
14410     {
14411         thread t { tricky, this, n };
14412         // ...
14413         // ... should I join here? ...
14414     }
14416 This seriously complicates lifetime analysis, and in not too unlikely cases makes lifetime analysis impossible.
14417 This implies that we cannot safely refer to local objects in `use()` from the thread or refer to local objects in the thread from `use()`.
14419 ##### Note
14421 Make "immortal threads" globals, put them in an enclosing scope, or put them on the free store rather than `detach()`.
14422 [don't `detach`](#Rconc-detached_thread).
14424 ##### Note
14426 Because of old code and third party libraries using `std::thread` this rule can be hard to introduce.
14428 ##### Enforcement
14430 Flag uses of `std::thread`:
14432 * Suggest use of `gsl::joining_thread`.
14433 * Suggest ["exporting ownership"](#Rconc-detached_thread) to an enclosing scope if it detaches.
14434 * Seriously warn if it is not obvious whether if joins of detaches.
14436 ### <a name="Rconc-detached_thread"></a>CP.26: Don't `detach()` a thread
14438 ##### Reason
14440 Often, the need to outlive the scope of its creation is inherent in the `thread`s task,
14441 but implementing that idea by `detach` makes it harder to monitor and communicate with the detached thread.
14442 In particular, it is harder (though not impossible) to ensure that the thread completed as expected or lives for as long as expected.
14444 ##### Example
14446     void heartbeat();
14448     void use()
14449     {
14450         std::thread t(heartbeat);             // don't join; heartbeat is meant to run forever
14451         t.detach();
14452         // ...
14453     }
14455 This is a reasonable use of a thread, for which `detach()` is commonly used.
14456 There are problems, though.
14457 How do we monitor the detached thread to see if it is alive?
14458 Something might go wrong with the heartbeat, and losing a heartbeat can be very serious in a system for which it is needed.
14459 So, we need to communicate with the heartbeat thread
14460 (e.g., through a stream of messages or notification events using a `condition_variable`).
14462 An alternative, and usually superior solution is to control its lifetime by placing it in a scope outside its point of creation (or activation).
14463 For example:
14465     void heartbeat();
14467     gsl::joining_thread t(heartbeat);             // heartbeat is meant to run "forever"
14469 This heartbeat will (barring error, hardware problems, etc.) run for as long as the program does.
14471 Sometimes, we need to separate the point of creation from the point of ownership:
14473     void heartbeat();
14475     unique_ptr<gsl::joining_thread> tick_tock {nullptr};
14477     void use()
14478     {
14479         // heartbeat is meant to run as long as tick_tock lives
14480         tick_tock = make_unique<gsl::joining_thread>(heartbeat);
14481         // ...
14482     }
14484 #### Enforcement
14486 Flag `detach()`.
14489 ### <a name="Rconc-data-by-value"></a>CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer
14491 ##### Reason
14493 Copying a small amount of data is cheaper to copy and access than to share it using some locking mechanism.
14494 Copying naturally gives unique ownership (simplifies code) and eliminates the possibility of data races.
14496 ##### Note
14498 Defining "small amount" precisely is impossible.
14500 ##### Example
14502     string modify1(string);
14503     void modify2(string&);
14505     void fct(string& s)
14506     {
14507         auto res = async(modify1, s);
14508         async(modify2, s);
14509     }
14511 The call of `modify1` involves copying two `string` values; the call of `modify2` does not.
14512 On the other hand, the implementation of `modify1` is exactly as we would have written it for single-threaded code,
14513 whereas the implementation of `modify2` will need some form of locking to avoid data races.
14514 If the string is short (say 10 characters), the call of `modify1` can be surprisingly fast;
14515 essentially all the cost is in the `thread` switch. If the string is long (say 1,000,000 characters), copying it twice
14516 is probably not a good idea.
14518 Note that this argument has nothing to do with `async` as such. It applies equally to considerations about whether to use
14519 message passing or shared memory.
14521 ##### Enforcement
14526 ### <a name="Rconc-shared"></a>CP.32: To share ownership between unrelated `thread`s use `shared_ptr`
14528 ##### Reason
14530 If threads are unrelated (that is, not known to be in the same scope or one within the lifetime of the other)
14531 and they need to share free store memory that needs to be deleted, a `shared_ptr` (or equivalent) is the only
14532 safe way to ensure proper deletion.
14534 ##### Example
14536     ???
14538 ##### Note
14540 * 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.
14541 * An object on free store that is never to be deleted can be shared.
14542 * An object owned by one thread can be safely shared with another as long as that second thread doesn't outlive the owner.
14544 ##### Enforcement
14549 ### <a name="Rconc-switch"></a>CP.40: Minimize context switching
14551 ##### Reason
14553 Context switches are expensive.
14555 ##### Example
14557     ???
14559 ##### Enforcement
14564 ### <a name="Rconc-create"></a>CP.41: Minimize thread creation and destruction
14566 ##### Reason
14568 Thread creation is expensive.
14570 ##### Example
14572     void worker(Message m)
14573     {
14574         // process
14575     }
14577     void master(istream& is)
14578     {
14579         for (Message m; is >> m; )
14580             run_list.push_back(new thread(worker, m));
14581     }
14583 This spawns a `thread` per message, and the `run_list` is presumably managed to destroy those tasks once they are finished.
14585 Instead, we could have a set of pre-created worker threads processing the messages
14587     Sync_queue<Message> work;
14589     void master(istream& is)
14590     {
14591         for (Message m; is >> m; )
14592             work.put(m);
14593     }
14595     void worker()
14596     {
14597         for (Message m; m = work.get(); ) {
14598             // process
14599         }
14600     }
14602     void workers()  // set up worker threads (specifically 4 worker threads)
14603     {
14604         joining_thread w1 {worker};
14605         joining_thread w2 {worker};
14606         joining_thread w3 {worker};
14607         joining_thread w4 {worker};
14608     }
14610 ##### Note
14612 If your system has a good thread pool, use it.
14613 If your system has a good message queue, use it.
14615 ##### Enforcement
14620 ### <a name="Rconc-wait"></a>CP.42: Don't `wait` without a condition
14622 ##### Reason
14624 A `wait` without a condition can miss a wakeup or wake up simply to find that there is no work to do.
14626 ##### Example, bad
14628     std::condition_variable cv;
14629     std::mutex mx;
14631     void thread1()
14632     {
14633         while (true) {
14634             // do some work ...
14635             std::unique_lock<std::mutex> lock(mx);
14636             cv.notify_one();    // wake other thread
14637         }
14638     }
14640     void thread2()
14641     {
14642         while (true) {
14643             std::unique_lock<std::mutex> lock(mx);
14644             cv.wait(lock);    // might block forever
14645             // do work ...
14646         }
14647     }
14649 Here, if some other `thread` consumes `thread1`'s notification, `thread2` can wait forever.
14651 ##### Example
14653     template<typename T>
14654     class Sync_queue {
14655     public:
14656         void put(const T& val);
14657         void put(T&& val);
14658         void get(T& val);
14659     private:
14660         mutex mtx;
14661         condition_variable cond;    // this controls access
14662         list<T> q;
14663     };
14665     template<typename T>
14666     void Sync_queue<T>::put(const T& val)
14667     {
14668         lock_guard<mutex> lck(mtx);
14669         q.push_back(val);
14670         cond.notify_one();
14671     }
14673     template<typename T>
14674     void Sync_queue<T>::get(T& val)
14675     {
14676         unique_lock<mutex> lck(mtx);
14677         cond.wait(lck, [this]{ return !q.empty(); });    // prevent spurious wakeup
14678         val = q.front();
14679         q.pop_front();
14680     }
14682 Now if the queue is empty when a thread executing `get()` wakes up (e.g., because another thread has gotten to `get()` before it),
14683 it will immediately go back to sleep, waiting.
14685 ##### Enforcement
14687 Flag all `wait`s without conditions.
14690 ### <a name="Rconc-time"></a>CP.43: Minimize time spent in a critical section
14692 ##### Reason
14694 The less time is spent with a `mutex` taken, the less chance that another `thread` has to wait,
14695 and `thread` suspension and resumption are expensive.
14697 ##### Example
14699     void do_something() // bad
14700     {
14701         unique_lock<mutex> lck(my_lock);
14702         do0();  // preparation: does not need lock
14703         do1();  // transaction: needs locking
14704         do2();  // cleanup: does not need locking
14705     }
14707 Here, we are holding the lock for longer than necessary:
14708 We should not have taken the lock before we needed it and should have released it again before starting the cleanup.
14709 We could rewrite this to
14711     void do_something() // bad
14712     {
14713         do0();  // preparation: does not need lock
14714         my_lock.lock();
14715         do1();  // transaction: needs locking
14716         my_lock.unlock();
14717         do2();  // cleanup: does not need locking
14718     }
14720 But that compromises safety and violates the [use RAII](#Rconc-raii) rule.
14721 Instead, add a block for the critical section:
14723     void do_something() // OK
14724     {
14725         do0();  // preparation: does not need lock
14726         {
14727             unique_lock<mutex> lck(my_lock);
14728             do1();  // transaction: needs locking
14729         }
14730         do2();  // cleanup: does not need locking
14731     }
14733 ##### Enforcement
14735 Impossible in general.
14736 Flag "naked" `lock()` and `unlock()`.
14739 ### <a name="Rconc-name"></a>CP.44: Remember to name your `lock_guard`s and `unique_lock`s
14741 ##### Reason
14743 An unnamed local objects is a temporary that immediately goes out of scope.
14745 ##### Example
14747     unique_lock<mutex>(m1);
14748     lock_guard<mutex> {m2};
14749     lock(m1, m2);
14751 This looks innocent enough, but it isn't.
14753 ##### Enforcement
14755 Flag all unnamed `lock_guard`s and `unique_lock`s.
14759 ### <a name="Rconc-mutex"></a>CP.50: Define a `mutex` together with the data it guards. Use `synchronized_value<T>` where possible
14761 ##### Reason
14763 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.
14765 Using a `synchronized_value<T>` ensures that the data has a mutex, and the right mutex is locked when the data is accessed.
14766 See the [WG21 proposal](http://wg21.link/p0290) to add `synchronized_value` to a future TS or revision of the C++ standard.
14768 ##### Example
14770     struct Record {
14771         std::mutex m;   // take this mutex before accessing other members
14772         // ...
14773     };
14775     class MyClass {
14776         struct DataRecord {
14777            // ...
14778         };
14779         synchronized_value<DataRecord> data; // Protect the data with a mutex
14780     };
14782 ##### Enforcement
14784 ??? Possible?
14787 ## <a name="SScp-par"></a>CP.par: Parallelism
14789 By "parallelism" we refer to performing a task (more or less) simultaneously ("in parallel with") on many data items.
14791 Parallelism rule summary:
14793 * ???
14794 * ???
14795 * Where appropriate, prefer the standard-library parallel algorithms
14796 * Use algorithms that are designed for parallelism, not algorithms with unnecessary dependency on linear evaluation
14800 ## <a name="SScp-mess"></a>CP.mess: Message passing
14802 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.
14803 Most people shouldn't work at this level: it's error-prone and development is slow.
14804 If possible, use a higher level facility: messaging libraries, parallel algorithms, and vectorization.
14805 This section looks at passing messages so that a programmer doesn't have to do explicit synchronization.
14807 Message passing rules summary:
14809 * [CP.60: Use a `future` to return a value from a concurrent task](#Rconc-future)
14810 * [CP.61: Use an `async()` to spawn a concurrent task](#Rconc-async)
14811 * message queues
14812 * messaging libraries
14814 ???? should there be a "use X rather than `std::async`" where X is something that would use a better specified thread pool?
14816 ??? 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?
14819 ### <a name="Rconc-future"></a>CP.60: Use a `future` to return a value from a concurrent task
14821 ##### Reason
14823 A `future` preserves the usual function call return semantics for asynchronous tasks.
14824 There is no explicit locking and both correct (value) return and error (exception) return are handled simply.
14826 ##### Example
14828     ???
14830 ##### Note
14834 ##### Enforcement
14838 ### <a name="Rconc-async"></a>CP.61: Use an `async()` to spawn a concurrent task
14840 ##### Reason
14842 A `future` preserves the usual function call return semantics for asynchronous tasks.
14843 There is no explicit locking and both correct (value) return and error (exception) return are handled simply.
14845 ##### Example
14847     ???
14849 ##### Note
14851 Unfortunately, `async()` is not perfect.
14852 For example, there is no guarantee that a thread pool is used to minimize thread construction.
14853 In fact, most current `async()` implementations don't.
14854 However, `async()` is simple and logically correct so until something better comes along
14855 and unless you really need to optimize for many asynchronous tasks, stick with `async()`.
14857 ##### Enforcement
14862 ## <a name="SScp-vec"></a>CP.vec: Vectorization
14864 Vectorization is a technique for executing a number of tasks concurrently without introducing explicit synchronization.
14865 An operation is simply applied to elements of a data structure (a vector, an array, etc.) in parallel.
14866 Vectorization has the interesting property of often requiring no non-local changes to a program.
14867 However, vectorization works best with simple data structures and with algorithms specifically crafted to enable it.
14869 Vectorization rule summary:
14871 * ???
14872 * ???
14874 ## <a name="SScp-free"></a>CP.free: Lock-free programming
14876 Synchronization using `mutex`es and `condition_variable`s can be relatively expensive.
14877 Furthermore, it can lead to deadlock.
14878 For performance and to eliminate the possibility of deadlock, we sometimes have to use the tricky low-level "lock-free" facilities
14879 that rely on briefly gaining exclusive ("atomic") access to memory.
14880 Lock-free programming is also used to implement higher-level concurrency mechanisms, such as `thread`s and `mutex`es.
14882 Lock-free programming rule summary:
14884 * [CP.100: Don't use lock-free programming unless you absolutely have to](#Rconc-lockfree)
14885 * [CP.101: Distrust your hardware/compiler combination](#Rconc-distrust)
14886 * [CP.102: Carefully study the literature](#Rconc-literature)
14887 * how/when to use atomics
14888 * avoid starvation
14889 * use a lock-free data structure rather than hand-crafting specific lock-free access
14890 * [CP.110: Do not write your own double-checked locking for initialization](#Rconc-double)
14891 * [CP.111: Use a conventional pattern if you really need double-checked locking](#Rconc-double-pattern)
14892 * how/when to compare and swap
14895 ### <a name="Rconc-lockfree"></a>CP.100: Don't use lock-free programming unless you absolutely have to
14897 ##### Reason
14899 It's error-prone and requires expert level knowledge of language features, machine architecture, and data structures.
14901 ##### Example, bad
14903     extern atomic<Link*> head;        // the shared head of a linked list
14905     Link* nh = new Link(data, nullptr);    // make a link ready for insertion
14906     Link* h = head.load();                 // read the shared head of the list
14908     do {
14909         if (h->data <= data) break;        // if so, insert elsewhere
14910         nh->next = h;                      // next element is the previous head
14911     } while (!head.compare_exchange_weak(h, nh));    // write nh to head or to h
14913 Spot the bug.
14914 It would be really hard to find through testing.
14915 Read up on the ABA problem.
14917 ##### Exception
14919 [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.
14921 ##### Note
14923 Higher-level concurrency mechanisms, such as `thread`s and `mutex`es are implemented using lock-free programming.
14925 **Alternative**: Use lock-free data structures implemented by others as part of some library.
14928 ### <a name="Rconc-distrust"></a>CP.101: Distrust your hardware/compiler combination
14930 ##### Reason
14932 The low-level hardware interfaces used by lock-free programming are among the hardest to implement well and among
14933 the areas where the most subtle portability problems occur.
14934 If you are doing lock-free programming for performance, you need to check for regressions.
14936 ##### Note
14938 Instruction reordering (static and dynamic) makes it hard for us to think effectively at this level (especially if you use relaxed memory models).
14939 Experience, (semi)formal models and model checking can be useful.
14940 Testing - often to an extreme extent - is essential.
14941 "Don't fly too close to the sun."
14943 ##### Enforcement
14945 Have strong rules for re-testing in place that covers any change in hardware, operating system, compiler, and libraries.
14948 ### <a name="Rconc-literature"></a>CP.102: Carefully study the literature
14950 ##### Reason
14952 With the exception of atomics and a few use standard patterns, lock-free programming is really an expert-only topic.
14953 Become an expert before shipping lock-free code for others to use.
14955 ##### References
14957 * Anthony Williams: C++ concurrency in action. Manning Publications.
14958 * Boehm, Adve, You Don't Know Jack About Shared Variables or Memory Models , Communications of the ACM, Feb 2012.
14959 * Boehm, "Threads Basics", HPL TR 2009-259.
14960 * Adve, Boehm, "Memory Models: A Case for Rethinking Parallel Languages and Hardware", Communications of the ACM, August 2010.
14961 * Boehm, Adve, "Foundations of the C++ Concurrency Memory Model", PLDI 08.
14962 * Mark Batty, Scott Owens, Susmit Sarkar, Peter Sewell, and Tjark Weber, "Mathematizing C++ Concurrency", POPL 2011.
14963 * 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.
14964 * Damian Dechev and Bjarne Stroustrup: Scalable Non-blocking Concurrent Objects for Mission Critical Code. ACM OOPSLA'09. October 2009
14965 * 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.
14968 ### <a name="Rconc-double"></a>CP.110: Do not write your own double-checked locking for initialization
14970 ##### Reason
14972 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.
14974 ##### Example
14976 Example with std::call_once.
14978     void f()
14979     {
14980         static std::once_flag my_once_flag;
14981         std::call_once(my_once_flag, []()
14982         {
14983             // do this only once
14984         });
14985         // ...
14986     }
14988 Example with thread-safe static local variables of C++11.
14990     void f()
14991     {
14992         // Assuming the compiler is compliant with C++11
14993         static My_class my_object; // Constructor called only once
14994         // ...
14995     }
14997     class My_class
14998     {
14999     public:
15000         My_class()
15001         {
15002             // do this only once
15003         }
15004     };
15006 ##### Enforcement
15008 ??? Is it possible to detect the idiom?
15011 ### <a name="Rconc-double-pattern"></a>CP.111: Use a conventional pattern if you really need double-checked locking
15013 ##### Reason
15015 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.
15017 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.
15019 ##### Example, bad
15021 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)
15023     mutex action_mutex;
15024     volatile bool action_needed;
15026     if (action_needed) {
15027         std::lock_guard<std::mutex> lock(action_mutex);
15028         if (action_needed) {
15029             take_action();
15030             action_needed = false;
15031         }
15032     }
15034 ##### Example, good
15036     mutex action_mutex;
15037     atomic<bool> action_needed;
15039     if (action_needed) {
15040         std::lock_guard<std::mutex> lock(action_mutex);
15041         if (action_needed) {
15042             take_action();
15043             action_needed = false;
15044         }
15045     }
15047 Fine-tuned memory order may be beneficial where acquire load is more efficient than sequentially-consistent load
15049     mutex action_mutex;
15050     atomic<bool> action_needed;
15052     if (action_needed.load(memory_order_acquire)) {
15053         lock_guard<std::mutex> lock(action_mutex);
15054         if (action_needed.load(memory_order_relaxed)) {
15055             take_action();
15056             action_needed.store(false, memory_order_release);
15057         }
15058     }
15060 ##### Enforcement
15062 ??? Is it possible to detect the idiom?
15065 ## <a name="SScp-etc"></a>CP.etc: Etc. concurrency rules
15067 These rules defy simple categorization:
15069 * [CP.200: Use `volatile` only to talk to non-C++ memory](#Rconc-volatile2)
15070 * [CP.201: ??? Signals](#Rconc-signal)
15072 ### <a name="Rconc-volatile2"></a>CP.200: Use `volatile` only to talk to non-C++ memory
15074 ##### Reason
15076 `volatile` is used to refer to objects that are shared with "non-C++" code or hardware that does not follow the C++ memory model.
15078 ##### Example
15080     const volatile long clock;
15082 This describes a register constantly updated by a clock circuit.
15083 `clock` is `volatile` because its value will change without any action from the C++ program that uses it.
15084 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:
15086     long t1 = clock;
15087     // ... no use of clock here ...
15088     long t2 = clock;
15090 `clock` is `const` because the program should not try to write to `clock`.
15092 ##### Note
15094 Unless you are writing the lowest level code manipulating hardware directly, consider `volatile` an esoteric feature that is best avoided.
15096 ##### Example
15098 Usually C++ code receives `volatile` memory that is owned elsewhere (hardware or another language):
15100     int volatile* vi = get_hardware_memory_location();
15101         // note: we get a pointer to someone else's memory here
15102         // volatile says "treat this with extra respect"
15104 Sometimes C++ code allocates the `volatile` memory and shares it with "elsewhere" (hardware or another language) by deliberately escaping a pointer:
15106     static volatile long vl;
15107     please_use_this(&vl);   // escape a reference to this to "elsewhere" (not C++)
15109 ##### Example, bad
15111 `volatile` local variables are nearly always wrong -- how can they be shared with other languages or hardware if they're ephemeral?
15112 The same applies almost as strongly to member variables, for the same reason.
15114     void f() {
15115         volatile int i = 0; // bad, volatile local variable
15116         // etc.
15117     }
15119     class My_type {
15120         volatile int i = 0; // suspicious, volatile member variable
15121         // etc.
15122     };
15124 ##### Note
15126 In C++, unlike in some other languages, `volatile` has [nothing to do with synchronization](#Rconc-volatile).
15128 ##### Enforcement
15130 * Flag `volatile T` local and member variables; almost certainly you intended to use `atomic<T>` instead.
15131 * ???
15133 ### <a name="Rconc-signal"></a>CP.201: ??? Signals
15135 ???UNIX signal handling???. May be worth reminding how little is async-signal-safe, and how to communicate with a signal handler (best is probably "not at all")
15138 # <a name="S-errors"></a>E: Error handling
15140 Error handling involves:
15142 * Detecting an error
15143 * Transmitting information about an error to some handler code
15144 * Preserving a valid state of the program
15145 * Avoiding resource leaks
15147 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.
15149 The rules are designed to help avoid several kinds of errors:
15151 * Type violations (e.g., misuse of `union`s and casts)
15152 * Resource leaks (including memory leaks)
15153 * Bounds errors
15154 * Lifetime errors (e.g., accessing an object after is has been `delete`d)
15155 * Complexity errors (logical errors made likely by overly complex expression of ideas)
15156 * Interface errors (e.g., an unexpected value is passed through an interface)
15158 Error-handling rule summary:
15160 * [E.1: Develop an error-handling strategy early in a design](#Re-design)
15161 * [E.2: Throw an exception to signal that a function can't perform its assigned task](#Re-throw)
15162 * [E.3: Use exceptions for error handling only](#Re-errors)
15163 * [E.4: Design your error-handling strategy around invariants](#Re-design-invariants)
15164 * [E.5: Let a constructor establish an invariant, and throw if it cannot](#Re-invariant)
15165 * [E.6: Use RAII to prevent leaks](#Re-raii)
15166 * [E.7: State your preconditions](#Re-precondition)
15167 * [E.8: State your postconditions](#Re-postcondition)
15169 * [E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable](#Re-noexcept)
15170 * [E.13: Never throw while being the direct owner of an object](#Re-never-throw)
15171 * [E.14: Use purpose-designed user-defined types as exceptions (not built-in types)](#Re-exception-types)
15172 * [E.15: Catch exceptions from a hierarchy by reference](#Re-exception-ref)
15173 * [E.16: Destructors, deallocation, and `swap` must never fail](#Re-never-fail)
15174 * [E.17: Don't try to catch every exception in every function](#Re-not-always)
15175 * [E.18: Minimize the use of explicit `try`/`catch`](#Re-catch)
15176 * [E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available](#Re-finally)
15178 * [E.25: If you can't throw exceptions, simulate RAII for resource management](#Re-no-throw-raii)
15179 * [E.26: If you can't throw exceptions, consider failing fast](#Re-no-throw-crash)
15180 * [E.27: If you can't throw exceptions, use error codes systematically](#Re-no-throw-codes)
15181 * [E.28: Avoid error handling based on global state (e.g. `errno`)](#Re-no-throw)
15183 * [E.30: Don't use exception specifications](#Re-specifications)
15184 * [E.31: Properly order your `catch`-clauses](#Re_catch)
15186 ### <a name="Re-design"></a>E.1: Develop an error-handling strategy early in a design
15188 ##### Reason
15190 A consistent and complete strategy for handling errors and resource leaks is hard to retrofit into a system.
15192 ### <a name="Re-throw"></a>E.2: Throw an exception to signal that a function can't perform its assigned task
15194 ##### Reason
15196 To make error handling systematic, robust, and non-repetitive.
15198 ##### Example
15200     struct Foo {
15201         vector<Thing> v;
15202         File_handle f;
15203         string s;
15204     };
15206     void use()
15207     {
15208         Foo bar {{Thing{1}, Thing{2}, Thing{monkey}}, {"my_file", "r"}, "Here we go!"};
15209         // ...
15210     }
15212 Here, `vector` and `string`s constructors may not be able to allocate sufficient memory for their elements, `vector`s constructor may not be able copy the `Thing`s in its initializer list, and `File_handle` may not be able to open the required file.
15213 In each case, they throw an exception for `use()`'s caller to handle.
15214 If `use()` could handle the failure to construct `bar` it can take control using `try`/`catch`.
15215 In either case, `Foo`'s constructor correctly destroys constructed members before passing control to whatever tried to create a `Foo`.
15216 Note that there is no return value that could contain an error code.
15218 The `File_handle` constructor might be defined like this:
15220     File_handle::File_handle(const string& name, const string& mode)
15221         :f{fopen(name.c_str(), mode.c_str())}
15222     {
15223         if (!f)
15224             throw runtime_error{"File_handle: could not open " + name + " as " + mode};
15225     }
15227 ##### Note
15229 It is often said that exceptions are meant to signal exceptional events and failures.
15230 However, that's a bit circular because "what is exceptional?"
15231 Examples:
15233 * A precondition that cannot be met
15234 * A constructor that cannot construct an object (failure to establish its class's [invariant](#Rc-struct))
15235 * An out-of-range error (e.g., `v[v.size()] = 7`)
15236 * Inability to acquire a resource (e.g., the network is down)
15238 In contrast, termination of an ordinary loop is not exceptional.
15239 Unless the loop was meant to be infinite, termination is normal and expected.
15241 ##### Note
15243 Don't use a `throw` as simply an alternative way of returning a value from a function.
15245 ##### Exception
15247 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`.
15249 **See also**: [RAII](#Re-raii)
15251 **See also**: [discussion](#Sd-noexcept)
15253 ##### Note
15255 Before deciding that you cannot afford or don't like exception-based error handling, have a look at the [alternatives](#Re-no-throw-raii);
15256 they have their own complexities and problems.
15257 Also, as far as possible, measure before making claims about efficiency.
15259 ### <a name="Re-errors"></a>E.3: Use exceptions for error handling only
15261 ##### Reason
15263 To keep error handling separated from "ordinary code."
15264 C++ implementations tend to be optimized based on the assumption that exceptions are rare.
15266 ##### Example, don't
15268     // don't: exception not used for error handling
15269     int find_index(vector<string>& vec, const string& x)
15270     {
15271         try {
15272             for (gsl::index i = 0; i < vec.size(); ++i)
15273                 if (vec[i] == x) throw i;  // found x
15274         } catch (int i) {
15275             return i;
15276         }
15277         return -1;   // not found
15278     }
15280 This is more complicated and most likely runs much slower than the obvious alternative.
15281 There is nothing exceptional about finding a value in a `vector`.
15283 ##### Enforcement
15285 Would need to be heuristic.
15286 Look for exception values "leaked" out of `catch` clauses.
15288 ### <a name="Re-design-invariants"></a>E.4: Design your error-handling strategy around invariants
15290 ##### Reason
15292 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.
15294 ##### Note
15296 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.
15298 ##### Enforcement
15302 ### <a name="Re-invariant"></a>E.5: Let a constructor establish an invariant, and throw if it cannot
15304 ##### Reason
15306 Leaving an object without its invariant established is asking for trouble.
15307 Not all member functions can be called.
15309 ##### Example
15311     class Vector {  // very simplified vector of doubles
15312         // if elem != nullptr then elem points to sz doubles
15313     public:
15314         Vector() : elem{nullptr}, sz{0}{}
15315         Vector(int s) : elem{new double[s]}, sz{s} { /* initialize elements */ }
15316         ~Vector() { delete [] elem; }
15317         double& operator[](int s) { return elem[s]; }
15318         // ...
15319     private:
15320         owner<double*> elem;
15321         int sz;
15322     };
15324 The class invariant - here stated as a comment - is established by the constructors.
15325 `new` throws if it cannot allocate the required memory.
15326 The operators, notably the subscript operator, relies on the invariant.
15328 **See also**: [If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
15330 ##### Enforcement
15332 Flag classes with `private` state without a constructor (public, protected, or private).
15334 ### <a name="Re-raii"></a>E.6: Use RAII to prevent leaks
15336 ##### Reason
15338 Leaks are typically unacceptable.
15339 Manual resource release is error-prone.
15340 RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks.
15342 ##### Example
15344     void f1(int i)   // Bad: possible leak
15345     {
15346         int* p = new int[12];
15347         // ...
15348         if (i < 17) throw Bad{"in f()", i};
15349         // ...
15350     }
15352 We could carefully release the resource before the throw:
15354     void f2(int i)   // Clumsy and error-prone: explicit release
15355     {
15356         int* p = new int[12];
15357         // ...
15358         if (i < 17) {
15359             delete[] p;
15360             throw Bad{"in f()", i};
15361         }
15362         // ...
15363     }
15365 This is verbose. In larger code with multiple possible `throw`s explicit releases become repetitive and error-prone.
15367     void f3(int i)   // OK: resource management done by a handle (but see below)
15368     {
15369         auto p = make_unique<int[]>(12);
15370         // ...
15371         if (i < 17) throw Bad{"in f()", i};
15372         // ...
15373     }
15375 Note that this works even when the `throw` is implicit because it happened in a called function:
15377     void f4(int i)   // OK: resource management done by a handle (but see below)
15378     {
15379         auto p = make_unique<int[]>(12);
15380         // ...
15381         helper(i);   // may throw
15382         // ...
15383     }
15385 Unless you really need pointer semantics, use a local resource object:
15387     void f5(int i)   // OK: resource management done by local object
15388     {
15389         vector<int> v(12);
15390         // ...
15391         helper(i);   // may throw
15392         // ...
15393     }
15395 That's even simpler and safer, and often more efficient.
15397 ##### Note
15399 If there is no obvious resource handle and for some reason defining a proper RAII object/handle is infeasible,
15400 as a last resort, cleanup actions can be represented by a [`final_action`](#Re-finally) object.
15402 ##### Note
15404 But what do we do if we are writing a program where exceptions cannot be used?
15405 First challenge that assumption; there are many anti-exceptions myths around.
15406 We know of only a few good reasons:
15408 * We are on a system so small that the exception support would eat up most of our 2K memory.
15409 * 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.
15410 * We are in a system with tons of legacy code using lots of pointers in difficult-to-understand ways
15411   (in particular without a recognizable ownership strategy) so that exceptions could cause leaks.
15412 * Our implementation of the C++ exception mechanisms is unreasonably poor
15413 (slow, memory consuming, failing to work correctly for dynamically linked libraries, etc.).
15414 Complain to your implementation purveyor; if no user complains, no improvement will happen.
15415 * We get fired if we challenge our manager's ancient wisdom.
15417 Only the first of these reasons is fundamental, so whenever possible, use exceptions to implement RAII, or design your RAII objects to never fail.
15418 When exceptions cannot be used, simulate RAII.
15419 That is, systematically check that objects are valid after construction and still release all resources in the destructor.
15420 One strategy is to add a `valid()` operation to every resource handle:
15422     void f()
15423     {
15424         vector<string> vs(100);   // not std::vector: valid() added
15425         if (!vs.valid()) {
15426             // handle error or exit
15427         }
15429         ifstream fs("foo");   // not std::ifstream: valid() added
15430         if (!fs.valid()) {
15431             // handle error or exit
15432         }
15434         // ...
15435     } // destructors clean up as usual
15437 Obviously, this increases the size of the code, doesn't allow for implicit propagation of "exceptions" (`valid()` checks), and `valid()` checks can be forgotten.
15438 Prefer to use exceptions.
15440 **See also**: [Use of `noexcept`](#Se-noexcept)
15442 ##### Enforcement
15446 ### <a name="Re-precondition"></a>E.7: State your preconditions
15448 ##### Reason
15450 To avoid interface errors.
15452 **See also**: [precondition rule](#Ri-pre)
15454 ### <a name="Re-postcondition"></a>E.8: State your postconditions
15456 ##### Reason
15458 To avoid interface errors.
15460 **See also**: [postcondition rule](#Ri-post)
15462 ### <a name="Re-noexcept"></a>E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable
15464 ##### Reason
15466 To make error handling systematic, robust, and efficient.
15468 ##### Example
15470     double compute(double d) noexcept
15471     {
15472         return log(sqrt(d <= 0 ? 1 : d));
15473     }
15475 Here, we know that `compute` will not throw because it is composed out of operations that don't throw.
15476 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`.
15478 ##### Note
15480 Many standard-library functions are `noexcept` including all the standard-library functions "inherited" from the C Standard Library.
15482 ##### Example
15484     vector<double> munge(const vector<double>& v) noexcept
15485     {
15486         vector<double> v2(v.size());
15487         // ... do something ...
15488     }
15490 The `noexcept` here states that I am not willing or able to handle the situation where I cannot construct the local `vector`.
15491 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.
15493 ##### Note
15495 Do not use traditional [exception-specifications](#Re-specifications).
15497 ##### See also
15499 [discussion](#Sd-noexcept).
15501 ### <a name="Re-never-throw"></a>E.13: Never throw while being the direct owner of an object
15503 ##### Reason
15505 That would be a leak.
15507 ##### Example
15509     void leak(int x)   // don't: may leak
15510     {
15511         auto p = new int{7};
15512         if (x < 0) throw Get_me_out_of_here{};  // may leak *p
15513         // ...
15514         delete p;   // we may never get here
15515     }
15517 One way of avoiding such problems is to use resource handles consistently:
15519     void no_leak(int x)
15520     {
15521         auto p = make_unique<int>(7);
15522         if (x < 0) throw Get_me_out_of_here{};  // will delete *p if necessary
15523         // ...
15524         // no need for delete p
15525     }
15527 Another solution (often better) would be to use a local variable to eliminate explicit use of pointers:
15529     void no_leak_simplified(int x)
15530     {
15531         vector<int> v(7);
15532         // ...
15533     }
15535 ##### Note
15537 If you have local "things" that requires cleanup, but is not represented by an object with a destructor, such cleanup must
15538 also be done before a `throw`.
15539 Sometimes, [`finally()`](#Re-finally) can make such unsystematic cleanup a bit more manageable.
15541 ### <a name="Re-exception-types"></a>E.14: Use purpose-designed user-defined types as exceptions (not built-in types)
15543 ##### Reason
15545 A user-defined type is unlikely to clash with other people's exceptions.
15547 ##### Example
15549     void my_code()
15550     {
15551         // ...
15552         throw Moonphase_error{};
15553         // ...
15554     }
15556     void your_code()
15557     {
15558         try {
15559             // ...
15560             my_code();
15561             // ...
15562         }
15563         catch(const Bufferpool_exhausted&) {
15564             // ...
15565         }
15566     }
15568 ##### Example, don't
15570     void my_code()     // Don't
15571     {
15572         // ...
15573         throw 7;       // 7 means "moon in the 4th quarter"
15574         // ...
15575     }
15577     void your_code()   // Don't
15578     {
15579         try {
15580             // ...
15581             my_code();
15582             // ...
15583         }
15584         catch(int i) {  // i == 7 means "input buffer too small"
15585             // ...
15586         }
15587     }
15589 ##### Note
15591 The standard-library classes derived from `exception` should be used only as base classes or for exceptions that require only "generic" handling. Like built-in types, their use could clash with other people's use of them.
15593 ##### Example, don't
15595     void my_code()   // Don't
15596     {
15597         // ...
15598         throw runtime_error{"moon in the 4th quarter"};
15599         // ...
15600     }
15602     void your_code()   // Don't
15603     {
15604         try {
15605             // ...
15606             my_code();
15607             // ...
15608         }
15609         catch(const runtime_error&) {   // runtime_error means "input buffer too small"
15610             // ...
15611         }
15612     }
15614 **See also**: [Discussion](#Sd-???)
15616 ##### Enforcement
15618 Catch `throw` and `catch` of a built-in type. Maybe warn about `throw` and `catch` using a standard-library `exception` type. Obviously, exceptions derived from the `std::exception` hierarchy are fine.
15620 ### <a name="Re-exception-ref"></a>E.15: Catch exceptions from a hierarchy by reference
15622 ##### Reason
15624 To prevent slicing.
15626 ##### Example
15628     void f()
15629     {
15630         try {
15631             // ...
15632         }
15633         catch (exception e) {   // don't: may slice
15634             // ...
15635         }
15636     }
15638 Instead, use a reference:
15640     catch (exception& e) { /* ... */ }
15642 of - typically better still - a `const` reference:
15644     catch (const exception& e) { /* ... */ }
15646 Most handlers do not modify their exception and in general we [recommend use of `const`](#Res-const).
15648 ##### Note
15650 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`) instead of rethrowing the original exception of type `std::runtime_error`. (But keep [Don't try to catch every exception in every function](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Re-not-always) and [Minimize the use of explicit `try`/`catch`](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Re-catch) in mind.)
15652 ##### Enforcement
15654 Flag by-value exceptions if their types are part of a hierarchy (could require whole-program analysis to be perfect).
15656 ### <a name="Re-never-fail"></a>E.16: Destructors, deallocation, and `swap` must never fail
15658 ##### Reason
15660 We don't know how to write reliable programs if a destructor, a swap, or a memory deallocation fails; that is, if it exits by an exception or simply doesn't perform its required action.
15662 ##### Example, don't
15664     class Connection {
15665         // ...
15666     public:
15667         ~Connection()   // Don't: very bad destructor
15668         {
15669             if (cannot_disconnect()) throw I_give_up{information};
15670             // ...
15671         }
15672     };
15674 ##### Note
15676 Many have tried to write reliable code violating this rule for examples, such as a network connection that "refuses to close".
15677 To the best of our knowledge nobody has found a general way of doing this.
15678 Occasionally, for very specific examples, you can get away with setting some state for future cleanup.
15679 For example, we might put a socket that does not want to close on a "bad socket" list,
15680 to be examined by a regular sweep of the system state.
15681 Every example we have seen of this is error-prone, specialized, and often buggy.
15683 ##### Note
15685 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.
15687 ##### Note
15689 Deallocation functions, including `operator delete`, must be `noexcept`. `swap` functions must be `noexcept`.
15690 Most destructors are implicitly `noexcept` by default.
15691 Also, [make move operations `noexcept`](#Rc-move-noexcept).
15693 ##### Enforcement
15695 Catch destructors, deallocation operations, and `swap`s that `throw`.
15696 Catch such operations that are not `noexcept`.
15698 **See also**: [discussion](#Sd-never-fail)
15700 ### <a name="Re-not-always"></a>E.17: Don't try to catch every exception in every function
15702 ##### Reason
15704 Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste.
15705 Let an exception propagate until it reaches a function that can handle it.
15706 Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii).
15708 ##### Example, don't
15710     void f()   // bad
15711     {
15712         try {
15713             // ...
15714         }
15715         catch (...) {
15716             // no action
15717             throw;   // propagate exception
15718         }
15719     }
15721 ##### Enforcement
15723 * Flag nested try-blocks.
15724 * Flag source code files with a too high ratio of try-blocks to functions. (??? Problem: define "too high")
15726 ### <a name="Re-catch"></a>E.18: Minimize the use of explicit `try`/`catch`
15728 ##### Reason
15730  `try`/`catch` is verbose and non-trivial uses error-prone.
15731  `try`/`catch` can be a sign of unsystematic and/or low-level resource management or error handling.
15733 ##### Example, Bad
15735     void f(zstring s)
15736     {
15737         Gadget* p;
15738         try {
15739             p = new Gadget(s);
15740             // ...
15741             delete p;
15742         }
15743         catch (Gadget_construction_failure) {
15744             delete p;
15745             throw;
15746         }
15747     }
15749 This code is messy.
15750 There could be a leak from the naked pointer in the `try` block.
15751 Not all exceptions are handled.
15752 `deleting` an object that failed to construct is almost certainly a mistake.
15753 Better:
15755     void f2(zstring s)
15756     {
15757         Gadget g {s};
15758     }
15760 ##### Alternatives
15762 * proper resource handles and [RAII](#Re-raii)
15763 * [`finally`](#Re-finally)
15765 ##### Enforcement
15767 ??? hard, needs a heuristic
15769 ### <a name="Re-finally"></a>E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available
15771 ##### Reason
15773 `finally` is less verbose and harder to get wrong than `try`/`catch`.
15775 ##### Example
15777     void f(int n)
15778     {
15779         void* p = malloc(n);
15780         auto _ = finally([p] { free(p); });
15781         // ...
15782     }
15784 ##### Note
15786 `finally` is not as messy as `try`/`catch`, but it is still ad-hoc.
15787 Prefer [proper resource management objects](#Re-raii).
15788 Consider `finally` a last resort.
15790 ##### Note
15792 Use of `finally` is a systematic and reasonably clean alternative to the old [`goto exit;` technique](#Re-no-throw-codes)
15793 for dealing with cleanup where resource management is not systematic.
15795 ##### Enforcement
15797 Heuristic: Detect `goto exit;`
15799 ### <a name="Re-no-throw-raii"></a>E.25: If you can't throw exceptions, simulate RAII for resource management
15801 ##### Reason
15803 Even without exceptions, [RAII](#Re-raii) is usually the best and most systematic way of dealing with resources.
15805 ##### Note
15807 Error handling using exceptions is the only complete and systematic way of handling non-local errors in C++.
15808 In particular, non-intrusively signaling failure to construct an object requires an exception.
15809 Signaling errors in a way that cannot be ignored requires exceptions.
15810 If you can't use exceptions, simulate their use as best you can.
15812 A lot of fear of exceptions is misguided.
15813 When used for exceptional circumstances in code that is not littered with pointers and complicated control structures,
15814 exception handling is almost always affordable (in time and space) and almost always leads to better code.
15815 This, of course, assumes a good implementation of the exception handling mechanisms, which is not available on all systems.
15816 There are also cases where the problems above do not apply, but exceptions cannot be used for other reasons.
15817 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.
15818 In the absence of appropriate time estimation tools, this is hard to guarantee for exceptions.
15819 Such systems (e.g. flight control software) typically also ban the use of dynamic (heap) memory.
15821 So, the primary guideline for error handling is "use exceptions and [RAII](#Re-raii)."
15822 This section deals with the cases where you either do not have an efficient implementation of exceptions,
15823 or have such a rat's nest of old-style code
15824 (e.g., lots of pointers, ill-defined ownership, and lots of unsystematic error handling based on tests of error codes)
15825 that it is infeasible to introduce simple and systematic exception handling.
15827 Before condemning exceptions or complaining too much about their cost, consider examples of the use of [error codes](#Re-no-throw-codes).
15828 Consider the cost and complexity of the use of error codes.
15829 If performance is your worry, measure.
15831 ##### Example
15833 Assume you wanted to write
15835     void func(zstring arg)
15836     {
15837         Gadget g {arg};
15838         // ...
15839     }
15841 If the `gadget` isn't correctly constructed, `func` exits with an exception.
15842 If we cannot throw an exception, we can simulate this RAII style of resource handling by adding a `valid()` member function to `Gadget`:
15844     error_indicator func(zstring arg)
15845     {
15846         Gadget g {arg};
15847         if (!g.valid()) return gadget_construction_error;
15848         // ...
15849         return 0;   // zero indicates "good"
15850     }
15852 The problem is of course that the caller now has to remember to test the return value.
15854 **See also**: [Discussion](#Sd-???)
15856 ##### Enforcement
15858 Possible (only) for specific versions of this idea: e.g., test for systematic test of `valid()` after resource handle construction
15860 ### <a name="Re-no-throw-crash"></a>E.26: If you can't throw exceptions, consider failing fast
15862 ##### Reason
15864 If you can't do a good job at recovering, at least you can get out before too much consequential damage is done.
15866 **See also**: [Simulating RAII](#Re-no-throw-raii)
15868 ##### Note
15870 If you cannot be systematic about error handling, consider "crashing" as a response to any error that cannot be handled locally.
15871 That is, if you cannot recover from an error in the context of the function that detected it, call `abort()`, `quick_exit()`,
15872 or a similar function that will trigger some sort of system restart.
15874 In systems where you have lots of processes and/or lots of computers, you need to expect and handle fatal crashes anyway,
15875 say from hardware failures.
15876 In such cases, "crashing" is simply leaving error handling to the next level of the system.
15878 ##### Example
15880     void f(int n)
15881     {
15882         // ...
15883         p = static_cast<X*>(malloc(n * sizeof(X)));
15884         if (!p) abort();     // abort if memory is exhausted
15885         // ...
15886     }
15888 Most programs cannot handle memory exhaustion gracefully anyway. This is roughly equivalent to
15890     void f(int n)
15891     {
15892         // ...
15893         p = new X[n];    // throw if memory is exhausted (by default, terminate)
15894         // ...
15895     }
15897 Typically, it is a good idea to log the reason for the "crash" before exiting.
15899 ##### Enforcement
15901 Awkward
15903 ### <a name="Re-no-throw-codes"></a>E.27: If you can't throw exceptions, use error codes systematically
15905 ##### Reason
15907 Systematic use of any error-handling strategy minimizes the chance of forgetting to handle an error.
15909 **See also**: [Simulating RAII](#Re-no-throw-raii)
15911 ##### Note
15913 There are several issues to be addressed:
15915 * how do you transmit an error indicator from out of a function?
15916 * how do you release all resources from a function before doing an error exit?
15917 * What do you use as an error indicator?
15919 In general, returning an error indicator implies returning two values: The result and an error indicator.
15920 The error indicator can be part of the object, e.g. an object can have a `valid()` indicator
15921 or a pair of values can be returned.
15923 ##### Example
15925     Gadget make_gadget(int n)
15926     {
15927         // ...
15928     }
15930     void user()
15931     {
15932         Gadget g = make_gadget(17);
15933         if (!g.valid()) {
15934                 // error handling
15935         }
15936         // ...
15937     }
15939 This approach fits with [simulated RAII resource management](#Re-no-throw-raii).
15940 The `valid()` function could return an `error_indicator` (e.g. a member of an `error_indicator` enumeration).
15942 ##### Example
15944 What if we cannot or do not want to modify the `Gadget` type?
15945 In that case, we must return a pair of values.
15946 For example:
15948     std::pair<Gadget, error_indicator> make_gadget(int n)
15949     {
15950         // ...
15951     }
15953     void user()
15954     {
15955         auto r = make_gadget(17);
15956         if (!r.second) {
15957                 // error handling
15958         }
15959         Gadget& g = r.first;
15960         // ...
15961     }
15963 As shown, `std::pair` is a possible return type.
15964 Some people prefer a specific type.
15965 For example:
15967     Gval make_gadget(int n)
15968     {
15969         // ...
15970     }
15972     void user()
15973     {
15974         auto r = make_gadget(17);
15975         if (!r.err) {
15976                 // error handling
15977         }
15978         Gadget& g = r.val;
15979         // ...
15980     }
15982 One reason to prefer a specific return type is to have names for its members, rather than the somewhat cryptic `first` and `second`
15983 and to avoid confusion with other uses of `std::pair`.
15985 ##### Example
15987 In general, you must clean up before an error exit.
15988 This can be messy:
15990     std::pair<int, error_indicator> user()
15991     {
15992         Gadget g1 = make_gadget(17);
15993         if (!g1.valid()) {
15994                 return {0, g1_error};
15995         }
15997         Gadget g2 = make_gadget(17);
15998         if (!g2.valid()) {
15999                 cleanup(g1);
16000                 return {0, g2_error};
16001         }
16003         // ...
16005         if (all_foobar(g1, g2)) {
16006             cleanup(g1);
16007             cleanup(g2);
16008             return {0, foobar_error};
16009         // ...
16011         cleanup(g1);
16012         cleanup(g2);
16013         return {res, 0};
16014     }
16016 Simulating RAII can be non-trivial, especially in functions with multiple resources and multiple possible errors.
16017 A not uncommon technique is to gather cleanup at the end of the function to avoid repetition (note the extra scope around `g2` is undesirable but necessary to make the `goto` version compile):
16019     std::pair<int, error_indicator> user()
16020     {
16021         error_indicator err = 0;
16023         Gadget g1 = make_gadget(17);
16024         if (!g1.valid()) {
16025                 err = g1_error;
16026                 goto exit;
16027         }
16029         {
16030         Gadget g2 = make_gadget(17);
16031         if (!g2.valid()) {
16032                 err = g2_error;
16033                 goto exit;
16034         }
16036         if (all_foobar(g1, g2)) {
16037             err = foobar_error;
16038             goto exit;
16039         }
16040         // ...
16041         }
16043     exit:
16044       if (g1.valid()) cleanup(g1);
16045       if (g2.valid()) cleanup(g2);
16046       return {res, err};
16047     }
16049 The larger the function, the more tempting this technique becomes.
16050 `finally` can [ease the pain a bit](#Re-finally).
16051 Also, the larger the program becomes the harder it is to apply an error-indicator-based error-handling strategy systematically.
16053 We [prefer exception-based error handling](#Re-throw) and recommend [keeping functions short](#Rf-single).
16055 **See also**: [Discussion](#Sd-???)
16057 **See also**: [Returning multiple values](#Rf-out-multi)
16059 ##### Enforcement
16061 Awkward.
16063 ### <a name="Re-no-throw"></a>E.28: Avoid error handling based on global state (e.g. `errno`)
16065 ##### Reason
16067 Global state is hard to manage and it is easy to forget to check it.
16068 When did you last test the return value of `printf()`?
16070 **See also**: [Simulating RAII](#Re-no-throw-raii)
16072 ##### Example, bad
16074     int last_err;
16076     void f(int n)
16077     {
16078         // ...
16079         p = static_cast<X*>(malloc(n * sizeof(X)));
16080         if (!p) last_err = -1;     // error if memory is exhausted
16081         // ...
16082     }
16084 ##### Note
16086 C-style error handling is based on the global variable `errno`, so it is essentially impossible to avoid this style completely.
16088 ##### Enforcement
16090 Awkward.
16093 ### <a name="Re-specifications"></a>E.30: Don't use exception specifications
16095 ##### Reason
16097 Exception specifications make error handling brittle, impose a run-time cost, and have been removed from the C++ standard.
16099 ##### Example
16101     int use(int arg)
16102         throw(X, Y)
16103     {
16104         // ...
16105         auto x = f(arg);
16106         // ...
16107     }
16109 If `f()` throws an exception different from `X` and `Y` the unexpected handler is invoked, which by default terminates.
16110 That's OK, but say that we have checked that this cannot happen and `f` is changed to throw a new exception `Z`,
16111 we now have a crash on our hands unless we change `use()` (and re-test everything).
16112 The snag is that `f()` may be in a library we do not control and the new exception is not anything that `use()` can do
16113 anything about or is in any way interested in.
16114 We can change `use()` to pass `Z` through, but now `use()`'s callers probably needs to be modified.
16115 This quickly becomes unmanageable.
16116 Alternatively, we can add a `try`-`catch` to `use()` to map `Z` into an acceptable exception.
16117 This too, quickly becomes unmanageable.
16118 Note that changes to the set of exceptions often happens at the lowest level of a system
16119 (e.g., because of changes to a network library or some middleware), so changes "bubble up" through long call chains.
16120 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.
16121 If `use()` is part of a library, it may not be possible to update it because a change could affect unknown clients.
16123 The policy of letting exceptions propagate until they reach a function that potentially can handle it has proven itself over the years.
16125 ##### Note
16127 No. This would not be any better had exception specifications been statically enforced.
16128 For example, see [Stroustrup94](#Stroustrup94).
16130 ##### Note
16132 If no exception may be thrown, use [`noexcept`](#Re-noexcept) or its equivalent `throw()`.
16134 ##### Enforcement
16136 Flag every exception specification.
16138 ### <a name="Re_catch"></a>E.31: Properly order your `catch`-clauses
16140 ##### Reason
16142 `catch`-clauses are evaluated in the order they appear and one clause can hide another.
16144 ##### Example
16146     void f()
16147     {
16148         // ...
16149         try {
16150                 // ...
16151         }
16152         catch (Base& b) { /* ... */ }
16153         catch (Derived& d) { /* ... */ }
16154         catch (...) { /* ... */ }
16155         catch (std::exception& e){ /* ... */ }
16156     }
16158 If `Derived`is derived from `Base` the `Derived`-handler will never be invoked.
16159 The "catch everything" handler ensured that the `std::exception`-handler will never be invoked.
16161 ##### Enforcement
16163 Flag all "hiding handlers".
16165 # <a name="S-const"></a>Con: Constants and immutability
16167 You can't have a race condition on a constant.
16168 It is easier to reason about a program when many of the objects cannot change their values.
16169 Interfaces that promises "no change" of objects passed as arguments greatly increase readability.
16171 Constant rule summary:
16173 * [Con.1: By default, make objects immutable](#Rconst-immutable)
16174 * [Con.2: By default, make member functions `const`](#Rconst-fct)
16175 * [Con.3: By default, pass pointers and references to `const`s](#Rconst-ref)
16176 * [Con.4: Use `const` to define objects with values that do not change after construction](#Rconst-const)
16177 * [Con.5: Use `constexpr` for values that can be computed at compile time](#Rconst-constexpr)
16179 ### <a name="Rconst-immutable"></a>Con.1: By default, make objects immutable
16181 ##### Reason
16183 Immutable objects are easier to reason about, so make objects non-`const` only when there is a need to change their value.
16184 Prevents accidental or hard-to-notice change of value.
16186 ##### Example
16188     for (const int i : c) cout << i << '\n';    // just reading: const
16190     for (int i : c) cout << i << '\n';          // BAD: just reading
16192 ##### Exception
16194 Function arguments are rarely mutated, but also rarely declared const.
16195 To avoid confusion and lots of false positives, don't enforce this rule for function arguments.
16197     void f(const char* const p); // pedantic
16198     void g(const int i);        // pedantic
16200 Note that function parameter is a local variable so changes to it are local.
16202 ##### Enforcement
16204 * Flag non-`const` variables that are not modified (except for parameters to avoid many false positives)
16206 ### <a name="Rconst-fct"></a>Con.2: By default, make member functions `const`
16208 ##### Reason
16210 A member function should be marked `const` unless it changes the object's observable state.
16211 This gives a more precise statement of design intent, better readability, more errors caught by the compiler, and sometimes more optimization opportunities.
16213 ##### Example, bad
16215     class Point {
16216         int x, y;
16217     public:
16218         int getx() { return x; }    // BAD, should be const as it doesn't modify the object's state
16219         // ...
16220     };
16222     void f(const Point& pt) {
16223         int x = pt.getx();          // ERROR, doesn't compile because getx was not marked const
16224     }
16226 ##### Note
16228 It is not inherently bad to pass a pointer or reference to non-`const`,
16229 but that should be done only when the called function is supposed to modify the object.
16230 A reader of code must assume that a function that takes a "plain" `T*` or `T&` will modify the object referred to.
16231 If it doesn't now, it might do so later without forcing recompilation.
16233 ##### Note
16235 There are code/libraries that offer functions that declare a`T*` even though
16236 those function do not modify that `T`.
16237 This is a problem for people modernizing code.
16238 You can
16240 * update the library to be `const`-correct; preferred long-term solution
16241 * "cast away `const`"; [best avoided](#Res-casts-const)
16242 * provide a wrapper function
16244 Example:
16246     void f(int* p);   // old code: f() does not modify `*p`
16247     void f(const int* p) { f(const_cast<int*>(p)); } // wrapper
16249 Note that this wrapper solution is a patch that should be used only when the declaration of `f()` cannot be modified,
16250 e.g. because it is in a library that you cannot modify.
16252 ##### Note
16254 A `const` member function can modify the value of an object that is `mutable` or accessed through a pointer member.
16255 A common use is to maintain a cache rather than repeatedly do a complicated computation.
16256 For example, here is a `Date` that caches (memoizes) its string representation to simplify repeated uses:
16258     class Date {
16259     public:
16260         // ...
16261         const string& string_ref() const
16262         {
16263             if (string_val == "") compute_string_rep();
16264             return string_val;
16265         }
16266         // ...
16267     private:
16268         void compute_string_rep() const;    // compute string representation and place it in string_val
16269         mutable string string_val;
16270         // ...
16271     };
16273 Another way of saying this is that `const`ness is not transitive.
16274 It is possible for a `const` member function to change the value of `mutable` members and the value of objects accessed
16275 through non-`const` pointers.
16276 It is the job of the class to ensure such mutation is done only when it makes sense according to the semantics (invariants)
16277 it offers to its users.
16279 **See also**: [Pimpl](#Ri-pimpl)
16281 ##### Enforcement
16283 * Flag a member function that is not marked `const`, but that does not perform a non-`const` operation on any member variable.
16285 ### <a name="Rconst-ref"></a>Con.3: By default, pass pointers and references to `const`s
16287 ##### Reason
16289  To avoid a called function unexpectedly changing the value.
16290  It's far easier to reason about programs when called functions don't modify state.
16292 ##### Example
16294     void f(char* p);        // does f modify *p? (assume it does)
16295     void g(const char* p);  // g does not modify *p
16297 ##### Note
16299 It is not inherently bad to pass a pointer or reference to non-`const`,
16300 but that should be done only when the called function is supposed to modify the object.
16302 ##### Note
16304 [Do not cast away `const`](#Res-casts-const).
16306 ##### Enforcement
16308 * Flag function that does not modify an object passed by  pointer or reference to non-`const`
16309 * Flag a function that (using a cast) modifies an object passed by pointer or reference to `const`
16311 ### <a name="Rconst-const"></a>Con.4: Use `const` to define objects with values that do not change after construction
16313 ##### Reason
16315  Prevent surprises from unexpectedly changed object values.
16317 ##### Example
16319     void f()
16320     {
16321         int x = 7;
16322         const int y = 9;
16324         for (;;) {
16325             // ...
16326         }
16327         // ...
16328     }
16330 As `x` is not `const`, we must assume that it is modified somewhere in the loop.
16332 ##### Enforcement
16334 * Flag unmodified non-`const` variables.
16336 ### <a name="Rconst-constexpr"></a>Con.5: Use `constexpr` for values that can be computed at compile time
16338 ##### Reason
16340 Better performance, better compile-time checking, guaranteed compile-time evaluation, no possibility of race conditions.
16342 ##### Example
16344     double x = f(2);            // possible run-time evaluation
16345     const double y = f(2);      // possible run-time evaluation
16346     constexpr double z = f(2);  // error unless f(2) can be evaluated at compile time
16348 ##### Note
16350 See F.4.
16352 ##### Enforcement
16354 * Flag `const` definitions with constant expression initializers.
16356 # <a name="S-templates"></a>T: Templates and generic programming
16358 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
16359 In C++, generic programming is supported by the `template` language mechanisms.
16361 Arguments to generic functions are characterized by sets of requirements on the argument types and values involved.
16362 In C++, these requirements are expressed by compile-time predicates called concepts.
16364 Templates can also be used for meta-programming; that is, programs that compose code at compile time.
16366 A central notion in generic programming is "concepts"; that is, requirements on template arguments presented as compile-time predicates.
16367 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
16368 A draft of a set of standard-library concepts can be found in another ISO TS: [ranges](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf)
16369 Concepts are supported in GCC 6.1 and later.
16370 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
16371 If you use GCC 6.1 or later, you can uncomment them.
16373 Template use rule summary:
16375 * [T.1: Use templates to raise the level of abstraction of code](#Rt-raise)
16376 * [T.2: Use templates to express algorithms that apply to many argument types](#Rt-algo)
16377 * [T.3: Use templates to express containers and ranges](#Rt-cont)
16378 * [T.4: Use templates to express syntax tree manipulation](#Rt-expr)
16379 * [T.5: Combine generic and OO techniques to amplify their strengths, not their costs](#Rt-generic-oo)
16381 Concept use rule summary:
16383 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
16384 * [T.11: Whenever possible use standard concepts](#Rt-std-concepts)
16385 * [T.12: Prefer concept names over `auto` for local variables](#Rt-auto)
16386 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
16387 * ???
16389 Concept definition rule summary:
16391 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
16392 * [T.21: Require a complete set of operations for a concept](#Rt-complete)
16393 * [T.22: Specify axioms for concepts](#Rt-axiom)
16394 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
16395 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
16396 * [T.25: Avoid complementary constraints](#Rt-not)
16397 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
16398 * [T.30: Use concept negation (`!C<T>`) sparingly to express a minor difference](#Rt-not)
16399 * [T.31: Use concept disjunction (`C1<T> || C2<T>`) sparingly to express alternatives](#Rt-or)
16400 * ???
16402 Template interface rule summary:
16404 * [T.40: Use function objects to pass operations to algorithms](#Rt-fo)
16405 * [T.41: Require only essential properties in a template's concepts](#Rt-essential)
16406 * [T.42: Use template aliases to simplify notation and hide implementation details](#Rt-alias)
16407 * [T.43: Prefer `using` over `typedef` for defining aliases](#Rt-using)
16408 * [T.44: Use function templates to deduce class template argument types (where feasible)](#Rt-deduce)
16409 * [T.46: Require template arguments to be at least `Regular` or `SemiRegular`](#Rt-regular)
16410 * [T.47: Avoid highly visible unconstrained templates with common names](#Rt-visible)
16411 * [T.48: If your compiler does not support concepts, fake them with `enable_if`](#Rt-concept-def)
16412 * [T.49: Where possible, avoid type-erasure](#Rt-erasure)
16414 Template definition rule summary:
16416 * [T.60: Minimize a template's context dependencies](#Rt-depend)
16417 * [T.61: Do not over-parameterize members (SCARY)](#Rt-scary)
16418 * [T.62: Place non-dependent class template members in a non-templated base class](#Rt-nondependent)
16419 * [T.64: Use specialization to provide alternative implementations of class templates](#Rt-specialization)
16420 * [T.65: Use tag dispatch to provide alternative implementations of functions](#Rt-tag-dispatch)
16421 * [T.67: Use specialization to provide alternative implementations for irregular types](#Rt-specialization2)
16422 * [T.68: Use `{}` rather than `()` within templates to avoid ambiguities](#Rt-cast)
16423 * [T.69: Inside a template, don't make an unqualified nonmember function call unless you intend it to be a customization point](#Rt-customization)
16425 Template and hierarchy rule summary:
16427 * [T.80: Do not naively templatize a class hierarchy](#Rt-hier)
16428 * [T.81: Do not mix hierarchies and arrays](#Rt-array) // ??? somewhere in "hierarchies"
16429 * [T.82: Linearize a hierarchy when virtual functions are undesirable](#Rt-linear)
16430 * [T.83: Do not declare a member function template virtual](#Rt-virtual)
16431 * [T.84: Use a non-template core implementation to provide an ABI-stable interface](#Rt-abi)
16432 * [T.??: ????](#Rt-???)
16434 Variadic template rule summary:
16436 * [T.100: Use variadic templates when you need a function that takes a variable number of arguments of a variety of types](#Rt-variadic)
16437 * [T.101: ??? How to pass arguments to a variadic template ???](#Rt-variadic-pass)
16438 * [T.102: ??? How to process arguments to a variadic template ???](#Rt-variadic-process)
16439 * [T.103: Don't use variadic templates for homogeneous argument lists](#Rt-variadic-not)
16440 * [T.??: ????](#Rt-???)
16442 Metaprogramming rule summary:
16444 * [T.120: Use template metaprogramming only when you really need to](#Rt-metameta)
16445 * [T.121: Use template metaprogramming primarily to emulate concepts](#Rt-emulate)
16446 * [T.122: Use templates (usually template aliases) to compute types at compile time](#Rt-tmp)
16447 * [T.123: Use `constexpr` functions to compute values at compile time](#Rt-fct)
16448 * [T.124: Prefer to use standard-library TMP facilities](#Rt-std-tmp)
16449 * [T.125: If you need to go beyond the standard-library TMP facilities, use an existing library](#Rt-lib)
16450 * [T.??: ????](#Rt-???)
16452 Other template rules summary:
16454 * [T.140: Name all operations with potential for reuse](#Rt-name)
16455 * [T.141: Use an unnamed lambda if you need a simple function object in one place only](#Rt-lambda)
16456 * [T.142: Use template variables to simplify notation](#Rt-var)
16457 * [T.143: Don't write unintentionally nongeneric code](#Rt-nongeneric)
16458 * [T.144: Don't specialize function templates](#Rt-specialize-function)
16459 * [T.150: Check that a class matches a concept using `static_assert`](#Rt-check-class)
16460 * [T.??: ????](#Rt-???)
16462 ## <a name="SS-GP"></a>T.gp: Generic programming
16464 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
16466 ### <a name="Rt-raise"></a>T.1: Use templates to raise the level of abstraction of code
16468 ##### Reason
16470 Generality. Reuse. Efficiency. Encourages consistent definition of user types.
16472 ##### Example, bad
16474 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":
16476     template<typename T>
16477         // requires Incrementable<T>
16478     T sum1(vector<T>& v, T s)
16479     {
16480         for (auto x : v) s += x;
16481         return s;
16482     }
16484     template<typename T>
16485         // requires Simple_number<T>
16486     T sum2(vector<T>& v, T s)
16487     {
16488         for (auto x : v) s = s + x;
16489         return s;
16490     }
16492 Assuming that `Incrementable` does not support `+` and `Simple_number` does not support `+=`, we have overconstrained implementers of `sum1` and `sum2`.
16493 And, in this case, missed an opportunity for a generalization.
16495 ##### Example
16497     template<typename T>
16498         // requires Arithmetic<T>
16499     T sum(vector<T>& v, T s)
16500     {
16501         for (auto x : v) s += x;
16502         return s;
16503     }
16505 Assuming that `Arithmetic` requires both `+` and `+=`, we have constrained the user of `sum` to provide a complete arithmetic type.
16506 That is not a minimal requirement, but it gives the implementer of algorithms much needed freedom and ensures that any `Arithmetic` type
16507 can be used for a wide variety of algorithms.
16509 For additional generality and reusability, we could also use a more general `Container` or `Range` concept instead of committing to only one container, `vector`.
16511 ##### Note
16513 If we define a template to require exactly the operations required for a single implementation of a single algorithm
16514 (e.g., requiring just `+=` rather than also `=` and `+`) and only those, we have overconstrained maintainers.
16515 We aim to minimize requirements on template arguments, but the absolutely minimal requirements of an implementation is rarely a meaningful concept.
16517 ##### Note
16519 Templates can be used to express essentially everything (they are Turing complete), but the aim of generic programming (as expressed using templates)
16520 is to efficiently generalize operations/algorithms over a set of types with similar semantic properties.
16522 ##### Note
16524 The `requires` in the comments are uses of `concepts`.
16525 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
16526 Concepts are supported in GCC 6.1 and later.
16527 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
16528 If you use GCC 6.1 or later, you can uncomment them.
16530 ##### Enforcement
16532 * Flag algorithms with "overly simple" requirements, such as direct use of specific operators without a concept.
16533 * Do not flag the definition of the "overly simple" concepts themselves; they may simply be building blocks for more useful concepts.
16535 ### <a name="Rt-algo"></a>T.2: Use templates to express algorithms that apply to many argument types
16537 ##### Reason
16539 Generality. Minimizing the amount of source code. Interoperability. Reuse.
16541 ##### Example
16543 That's the foundation of the STL. A single `find` algorithm easily works with any kind of input range:
16545     template<typename Iter, typename Val>
16546         // requires Input_iterator<Iter>
16547         //       && Equality_comparable<Value_type<Iter>, Val>
16548     Iter find(Iter b, Iter e, Val v)
16549     {
16550         // ...
16551     }
16553 ##### Note
16555 Don't use a template unless you have a realistic need for more than one template argument type.
16556 Don't overabstract.
16558 ##### Enforcement
16560 ??? tough, probably needs a human
16562 ### <a name="Rt-cont"></a>T.3: Use templates to express containers and ranges
16564 ##### Reason
16566 Containers need an element type, and expressing that as a template argument is general, reusable, and type safe.
16567 It also avoids brittle or inefficient workarounds. Convention: That's the way the STL does it.
16569 ##### Example
16571     template<typename T>
16572         // requires Regular<T>
16573     class Vector {
16574         // ...
16575         T* elem;   // points to sz Ts
16576         int sz;
16577     };
16579     Vector<double> v(10);
16580     v[7] = 9.9;
16582 ##### Example, bad
16584     class Container {
16585         // ...
16586         void* elem;   // points to size elements of some type
16587         int sz;
16588     };
16590     Container c(10, sizeof(double));
16591     ((double*) c.elem)[7] = 9.9;
16593 This doesn't directly express the intent of the programmer and hides the structure of the program from the type system and optimizer.
16595 Hiding the `void*` behind macros simply obscures the problems and introduces new opportunities for confusion.
16597 **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.
16598 See [Stable base](#Rt-abi).
16600 ##### Enforcement
16602 * Flag uses of `void*`s and casts outside low-level implementation code
16604 ### <a name="Rt-expr"></a>T.4: Use templates to express syntax tree manipulation
16606 ##### Reason
16608  ???
16610 ##### Example
16612     ???
16614 **Exceptions**: ???
16616 ### <a name="Rt-generic-oo"></a>T.5: Combine generic and OO techniques to amplify their strengths, not their costs
16618 ##### Reason
16620 Generic and OO techniques are complementary.
16622 ##### Example
16624 Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces.
16626     class Command {
16627         // pure virtual functions
16628     };
16630     // implementations
16631     template</*...*/>
16632     class ConcreteCommand : public Command {
16633         // implement virtuals
16634     };
16636 ##### Example
16638 Dynamic helps static: Offer a generic, comfortable, statically bound interface, but internally dispatch dynamically, so you offer a uniform object layout.
16639 Examples include type erasure as with `std::shared_ptr`'s deleter (but [don't overuse type erasure](#Rt-erasure)).
16641 ##### Note
16643 In a class template, nonvirtual functions are only instantiated if they're used -- but virtual functions are instantiated every time.
16644 This can bloat code size, and may overconstrain a generic type by instantiating functionality that is never needed.
16645 Avoid this, even though the standard-library facets made this mistake.
16647 ##### See also
16649 * ref ???
16650 * ref ???
16651 * ref ???
16653 ##### Enforcement
16655 See the reference to more specific rules.
16657 ## <a name="SS-concepts"></a>T.concepts: Concept rules
16659 Concepts is a facility for specifying requirements for template arguments.
16660 It is an [ISO technical specification](#Ref-conceptsTS), but currently supported only by GCC.
16661 Concepts are, however, crucial in the thinking about generic programming and the basis of much work on future C++ libraries
16662 (standard and other).
16664 This section assumes concept support
16666 Concept use rule summary:
16668 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
16669 * [T.11: Whenever possible use standard concepts](#Rt-std-concepts)
16670 * [T.12: Prefer concept names over `auto`](#Rt-auto)
16671 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
16672 * ???
16674 Concept definition rule summary:
16676 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
16677 * [T.21: Require a complete set of operations for a concept](#Rt-complete)
16678 * [T.22: Specify axioms for concepts](#Rt-axiom)
16679 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
16680 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
16681 * [T.25: Avoid complimentary constraints](#Rt-not)
16682 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
16683 * ???
16685 ## <a name="SS-concept-use"></a>T.con-use: Concept use
16687 ### <a name="Rt-concepts"></a>T.10: Specify concepts for all template arguments
16689 ##### Reason
16691 Correctness and readability.
16692 The assumed meaning (syntax and semantics) of a template argument is fundamental to the interface of a template.
16693 A concept dramatically improves documentation and error handling for the template.
16694 Specifying concepts for template arguments is a powerful design tool.
16696 ##### Example
16698     template<typename Iter, typename Val>
16699     //    requires Input_iterator<Iter>
16700     //             && Equality_comparable<Value_type<Iter>, Val>
16701     Iter find(Iter b, Iter e, Val v)
16702     {
16703         // ...
16704     }
16706 or equivalently and more succinctly:
16708     template<Input_iterator Iter, typename Val>
16709     //    requires Equality_comparable<Value_type<Iter>, Val>
16710     Iter find(Iter b, Iter e, Val v)
16711     {
16712         // ...
16713     }
16715 ##### Note
16717 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
16718 A draft of a set of standard-library concepts can be found in another ISO TS: [ranges](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf)
16719 Concepts are supported in GCC 6.1 and later.
16720 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
16721 If you use GCC 6.1 or later, you can uncomment them:
16723     template<typename Iter, typename Val>
16724         requires Input_iterator<Iter>
16725                && Equality_comparable<Value_type<Iter>, Val>
16726     Iter find(Iter b, Iter e, Val v)
16727     {
16728         // ...
16729     }
16731 ##### Note
16733 Plain `typename` (or `auto`) is the least constraining concept.
16734 It should be used only rarely when nothing more than "it's a type" can be assumed.
16735 This is typically only needed when (as part of template metaprogramming code) we manipulate pure expression trees, postponing type checking.
16737 **References**: TC++PL4, Palo Alto TR, Sutton
16739 ##### Enforcement
16741 Flag template type arguments without concepts
16743 ### <a name="Rt-std-concepts"></a>T.11: Whenever possible use standard concepts
16745 ##### Reason
16747  "Standard" concepts (as provided by the [GSL](#S-GSL) and the [Ranges TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf), and hopefully soon the ISO standard itself)
16748 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.
16750 ##### Note
16752 Unless you are creating a new generic library, most of the concepts you need will already be defined by the standard library.
16754 ##### Example (using TS concepts)
16756     template<typename T>
16757         // don't define this: Sortable is in the GSL
16758     concept Ordered_container = Sequence<T> && Random_access<Iterator<T>> && Ordered<Value_type<T>>;
16760     void sort(Ordered_container& s);
16762 This `Ordered_container` is quite plausible, but it is very similar to the `Sortable` concept in the GSL (and the Range TS).
16763 Is it better? Is it right? Does it accurately reflect the standard's requirements for `sort`?
16764 It is better and simpler just to use `Sortable`:
16766     void sort(Sortable& s);   // better
16768 ##### Note
16770 The set of "standard" concepts is evolving as we approach an ISO standard including concepts.
16772 ##### Note
16774 Designing a useful concept is challenging.
16776 ##### Enforcement
16778 Hard.
16780 * Look for unconstrained arguments, templates that use "unusual"/non-standard concepts, templates that use "homebrew" concepts without axioms.
16781 * Develop a concept-discovery tool (e.g., see [an early experiment](http://www.stroustrup.com/sle2010_webversion.pdf)).
16783 ### <a name="Rt-auto"></a>T.12: Prefer concept names over `auto` for local variables
16785 ##### Reason
16787  `auto` is the weakest concept. Concept names convey more meaning than just `auto`.
16789 ##### Example (using TS concepts)
16791     vector<string> v{ "abc", "xyz" };
16792     auto& x = v.front();     // bad
16793     String& s = v.front();   // good (String is a GSL concept)
16795 ##### Enforcement
16797 * ???
16799 ### <a name="Rt-shorthand"></a>T.13: Prefer the shorthand notation for simple, single-type argument concepts
16801 ##### Reason
16803 Readability. Direct expression of an idea.
16805 ##### Example (using TS concepts)
16807 To say "`T` is `Sortable`":
16809     template<typename T>       // Correct but verbose: "The parameter is
16810     //    requires Sortable<T>   // of type T which is the name of a type
16811     void sort(T&);             // that is Sortable"
16813     template<Sortable T>       // Better (assuming support for concepts): "The parameter is of type T
16814     void sort(T&);             // which is Sortable"
16816     void sort(Sortable&);      // Best (assuming support for concepts): "The parameter is Sortable"
16818 The shorter versions better match the way we speak. Note that many templates don't need to use the `template` keyword.
16820 ##### Note
16822 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
16823 A draft of a set of standard-library concepts can be found in another ISO TS: [ranges](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf)
16824 Concepts are supported in GCC 6.1 and later.
16825 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
16826 If you use a compiler that supports concepts (e.g., GCC 6.1 or later), you can remove the `//`.
16828 ##### Enforcement
16830 * Not feasible in the short term when people convert from the `<typename T>` and `<class T`> notation.
16831 * Later, flag declarations that first introduce a typename and then constrain it with a simple, single-type-argument concept.
16833 ## <a name="SS-concepts-def"></a>T.concepts.def: Concept definition rules
16835 Defining good concepts is non-trivial.
16836 Concepts are meant to represent fundamental concepts in an application domain (hence the name "concepts").
16837 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
16838 and will not give the full benefits of the mechanism.
16840 Obviously, defining concepts will be most useful for code that can use an implementation (e.g., GCC 6.1 or later),
16841 but defining concepts is in itself a useful design technique and help catch conceptual errors and clean up the concepts (sic!) of an implementation.
16843 ### <a name="Rt-low"></a>T.20: Avoid "concepts" without meaningful semantics
16845 ##### Reason
16847 Concepts are meant to express semantic notions, such as "a number", "a range" of elements, and "totally ordered."
16848 Simple constraints, such as "has a `+` operator" and "has a `>` operator" cannot be meaningfully specified in isolation
16849 and should be used only as building blocks for meaningful concepts, rather than in user code.
16851 ##### Example, bad (using TS concepts)
16853     template<typename T>
16854     concept Addable = has_plus<T>;    // bad; insufficient
16856     template<Addable N> auto algo(const N& a, const N& b) // use two numbers
16857     {
16858         // ...
16859         return a + b;
16860     }
16862     int x = 7;
16863     int y = 9;
16864     auto z = algo(x, y);   // z = 16
16866     string xx = "7";
16867     string yy = "9";
16868     auto zz = algo(xx, yy);   // zz = "79"
16870 Maybe the concatenation was expected. More likely, it was an accident. Defining minus equivalently would give dramatically different sets of accepted types.
16871 This `Addable` violates the mathematical rule that addition is supposed to be commutative: `a+b == b+a`.
16873 ##### Note
16875 The ability to specify a meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint.
16877 ##### Example (using TS concepts)
16879     template<typename T>
16880     // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
16881     concept Number = has_plus<T>
16882                      && has_minus<T>
16883                      && has_multiply<T>
16884                      && has_divide<T>;
16886     template<Number N> auto algo(const N& a, const N& b)
16887     {
16888         // ...
16889         return a + b;
16890     }
16892     int x = 7;
16893     int y = 9;
16894     auto z = algo(x, y);   // z = 16
16896     string xx = "7";
16897     string yy = "9";
16898     auto zz = algo(xx, yy);   // error: string is not a Number
16900 ##### Note
16902 Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept.
16904 ##### Enforcement
16906 * Flag single-operation `concepts` when used outside the definition of other `concepts`.
16907 * Flag uses of `enable_if` that appears to simulate single-operation `concepts`.
16910 ### <a name="Rt-complete"></a>T.21: Require a complete set of operations for a concept
16912 ##### Reason
16914 Ease of comprehension.
16915 Improved interoperability.
16916 Helps implementers and maintainers.
16918 ##### Note
16920 This is a specific variant of the general rule that [a concept must make semantic sense](#Rt-low).
16922 ##### Example, bad (using TS concepts)
16924     template<typename T> concept Subtractable = requires(T a, T, b) { a-b; };
16926 This makes no semantic sense.
16927 You need at least `+` to make `-` meaningful and useful.
16929 Examples of complete sets are
16931 * `Arithmetic`: `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`
16932 * `Comparable`: `<`, `>`, `<=`, `>=`, `==`, `!=`
16934 ##### Note
16936 This rule applies whether we use direct language support for concepts or not.
16937 It is a general design rule that even applies to non-templates:
16939     class Minimal {
16940         // ...
16941     };
16943     bool operator==(const Minimal&, const Minimal&);
16944     bool operator<(const Minimal&, const Minimal&);
16946     Minimal operator+(const Minimal&, const Minimal&);
16947     // no other operators
16949     void f(const Minimal& x, const Minimal& y)
16950     {
16951         if (!(x == y)) { /* ... */ }    // OK
16952         if (x != y) { /* ... */ }       // surprise! error
16954         while (!(x < y)) { /* ... */ }  // OK
16955         while (x >= y) { /* ... */ }    // surprise! error
16957         x = x + y;          // OK
16958         x += y;             // surprise! error
16959     }
16961 This is minimal, but surprising and constraining for users.
16962 It could even be less efficient.
16964 The rule supports the view that a concept should reflect a (mathematically) coherent set of operations.
16966 ##### Example
16968     class Convenient {
16969         // ...
16970     };
16972     bool operator==(const Convenient&, const Convenient&);
16973     bool operator<(const Convenient&, const Convenient&);
16974     // ... and the other comparison operators ...
16976     Minimal operator+(const Convenient&, const Convenient&);
16977     // .. and the other arithmetic operators ...
16979     void f(const Convenient& x, const Convenient& y)
16980     {
16981         if (!(x == y)) { /* ... */ }    // OK
16982         if (x != y) { /* ... */ }       // OK
16984         while (!(x < y)) { /* ... */ }  // OK
16985         while (x >= y) { /* ... */ }    // OK
16987         x = x + y;     // OK
16988         x += y;        // OK
16989     }
16991 It can be a nuisance to define all operators, but not hard.
16992 Ideally, that rule should be language supported by giving you comparison operators by default.
16994 ##### Enforcement
16996 * Flag classes that support "odd" subsets of a set of operators, e.g., `==` but not `!=` or `+` but not `-`.
16997   Yes, `std::string` is "odd", but it's too late to change that.
17000 ### <a name="Rt-axiom"></a>T.22: Specify axioms for concepts
17002 ##### Reason
17004 A meaningful/useful concept has a semantic meaning.
17005 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.
17006 Specifying semantics is a powerful design tool.
17008 ##### Example (using TS concepts)
17010     template<typename T>
17011         // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
17012         // axiom(T a, T b) { a + b == b + a; a - a == 0; a * (b + c) == a * b + a * c; /*...*/ }
17013         concept Number = requires(T a, T b) {
17014             {a + b} -> T;   // the result of a + b is convertible to T
17015             {a - b} -> T;
17016             {a * b} -> T;
17017             {a / b} -> T;
17018         }
17020 ##### Note
17022 This is an axiom in the mathematical sense: something that may be assumed without proof.
17023 In general, axioms are not provable, and when they are the proof is often beyond the capability of a compiler.
17024 An axiom may not be general, but the template writer may assume that it holds for all inputs actually used (similar to a precondition).
17026 ##### Note
17028 In this context axioms are Boolean expressions.
17029 See the [Palo Alto TR](#S-references) for examples.
17030 Currently, C++ does not support axioms (even the ISO Concepts TS), so we have to make do with comments for a longish while.
17031 Once language support is available, the `//` in front of the axiom can be removed
17033 ##### Note
17035 The GSL concepts have well-defined semantics; see the Palo Alto TR and the Ranges TS.
17037 ##### Exception (using TS concepts)
17039 Early versions of a new "concept" still under development will often just define simple sets of constraints without a well-specified semantics.
17040 Finding good semantics can take effort and time.
17041 An incomplete set of constraints can still be very useful:
17043     // balancer for a generic binary tree
17044     template<typename Node> concept bool Balancer = requires(Node* p) {
17045         add_fixup(p);
17046         touch(p);
17047         detach(p);
17048     }
17050 So a `Balancer` must supply at least thee operations on a tree `Node`,
17051 but we are not yet ready to specify detailed semantics because a new kind of balanced tree might require more operations
17052 and the precise general semantics for all nodes is hard to pin down in the early stages of design.
17054 A "concept" that is incomplete or without a well-specified semantics can still be useful.
17055 For example, it allows for some checking during initial experimentation.
17056 However, it should not be assumed to be stable.
17057 Each new use case may require such an incomplete concept to be improved.
17059 ##### Enforcement
17061 * Look for the word "axiom" in concept definition comments
17063 ### <a name="Rt-refine"></a>T.23: Differentiate a refined concept from its more general case by adding new use patterns.
17065 ##### Reason
17067 Otherwise they cannot be distinguished automatically by the compiler.
17069 ##### Example (using TS concepts)
17071     template<typename I>
17072     concept bool Input_iter = requires(I iter) { ++iter; };
17074     template<typename I>
17075     concept bool Fwd_iter = Input_iter<I> && requires(I iter) { iter++; }
17077 The compiler can determine refinement based on the sets of required operations (here, suffix `++`).
17078 This decreases the burden on implementers of these types since
17079 they do not need any special declarations to "hook into the concept".
17080 If two concepts have exactly the same requirements, they are logically equivalent (there is no refinement).
17082 ##### Enforcement
17084 * Flag a concept that has exactly the same requirements as another already-seen concept (neither is more refined).
17085 To disambiguate them, see [T.24](#Rt-tag).
17087 ### <a name="Rt-tag"></a>T.24: Use tag classes or traits to differentiate concepts that differ only in semantics.
17089 ##### Reason
17091 Two concepts requiring the same syntax but having different semantics leads to ambiguity unless the programmer differentiates them.
17093 ##### Example (using TS concepts)
17095     template<typename I>    // iterator providing random access
17096     concept bool RA_iter = ...;
17098     template<typename I>    // iterator providing random access to contiguous data
17099     concept bool Contiguous_iter =
17100         RA_iter<I> && is_contiguous<I>::value;  // using is_contiguous trait
17102 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
17104 Wrapping a tag class into a concept leads to a simpler expression of this idea:
17106     template<typename I> concept Contiguous = is_contiguous<I>::value;
17108     template<typename I>
17109     concept bool Contiguous_iter = RA_iter<I> && Contiguous<I>;
17111 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
17113 ##### Note
17115 Traits can be trait classes or type traits.
17116 These can be user-defined or standard-library ones.
17117 Prefer the standard-library ones.
17119 ##### Enforcement
17121 * The compiler flags ambiguous use of identical concepts.
17122 * Flag the definition of identical concepts.
17124 ### <a name="Rt-not"></a>T.25: Avoid complementary constraints
17126 ##### Reason
17128 Clarity. Maintainability.
17129 Functions with complementary requirements expressed using negation are brittle.
17131 ##### Example (using TS concepts)
17133 Initially, people will try to define functions with complementary requirements:
17135     template<typename T>
17136         requires !C<T>    // bad
17137     void f();
17139     template<typename T>
17140         requires C<T>
17141     void f();
17143 This is better:
17145     template<typename T>   // general template
17146         void f();
17148     template<typename T>   // specialization by concept
17149         requires C<T>
17150     void f();
17152 The compiler will choose the unconstrained template only when `C<T>` is
17153 unsatisfied. If you do not want to (or cannot) define an unconstrained
17154 version of `f()`, then delete it.
17156     template<typename T>
17157     void f() = delete;
17159 The compiler will select the overload and emit an appropriate error.
17161 ##### Note
17163 Complementary constraints are unfortunately common in `enable_if` code:
17165     template<typename T>
17166     enable_if<!C<T>, void>   // bad
17167     f();
17169     template<typename T>
17170     enable_if<C<T>, void>
17171     f();
17174 ##### Note
17176 Complementary requirements on one requirements is sometimes (wrongly) considered manageable.
17177 However, for two or more requirements the number of definitions needs can go up exponentially (2,4,9,16,...):
17179     C1<T> && C2<T>
17180     !C1<T> && C2<T>
17181     C1<T> && !C2<T>
17182     !C1<T> && !C2<T>
17184 Now the opportunities for errors multiply.
17186 ##### Enforcement
17188 * Flag pairs of functions with `C<T>` and `!C<T>` constraints
17190 ### <a name="Rt-use"></a>T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax
17192 ##### Reason
17194 The definition is more readable and corresponds directly to what a user has to write.
17195 Conversions are taken into account. You don't have to remember the names of all the type traits.
17197 ##### Example (using TS concepts)
17199 You might be tempted to define a concept `Equality` like this:
17201     template<typename T> concept Equality = has_equal<T> && has_not_equal<T>;
17203 Obviously, it would be better and easier just to use the standard `EqualityComparable`,
17204 but - just as an example - if you had to define such a concept, prefer:
17206     template<typename T> concept Equality = requires(T a, T b) {
17207         bool == { a == b }
17208         bool == { a != b }
17209         // axiom { !(a == b) == (a != b) }
17210         // axiom { a = b; => a == b }  // => means "implies"
17211     }
17213 as opposed to defining two meaningless concepts `has_equal` and `has_not_equal` just as helpers in the definition of `Equality`.
17214 By "meaningless" we mean that we cannot specify the semantics of `has_equal` in isolation.
17216 ##### Enforcement
17220 ## <a name="SS-temp-interface"></a>Template interfaces
17222 Over the years, programming with templates have suffered from a weak distinction between the interface of a template
17223 and its implementation.
17224 Before concepts, that distinction had no direct language support.
17225 However, the interface to a template is a critical concept - a contract between a user and an implementer - and should be carefully designed.
17227 ### <a name="Rt-fo"></a>T.40: Use function objects to pass operations to algorithms
17229 ##### Reason
17231 Function objects can carry more information through an interface than a "plain" pointer to function.
17232 In general, passing function objects gives better performance than passing pointers to functions.
17234 ##### Example (using TS concepts)
17236     bool greater(double x, double y) { return x > y; }
17237     sort(v, greater);                                    // pointer to function: potentially slow
17238     sort(v, [](double x, double y) { return x > y; });   // function object
17239     sort(v, std::greater<>);                             // function object
17241     bool greater_than_7(double x) { return x > 7; }
17242     auto x = find_if(v, greater_than_7);                 // pointer to function: inflexible
17243     auto y = find_if(v, [](double x) { return x > 7; }); // function object: carries the needed data
17244     auto z = find_if(v, Greater_than<double>(7));        // function object: carries the needed data
17246 You can, of course, generalize those functions using `auto` or (when and where available) concepts. For example:
17248     auto y1 = find_if(v, [](Ordered x) { return x > 7; }); // require an ordered type
17249     auto z1 = find_if(v, [](auto x) { return x > 7; });    // hope that the type has a >
17251 ##### Note
17253 Lambdas generate function objects.
17255 ##### Note
17257 The performance argument depends on compiler and optimizer technology.
17259 ##### Enforcement
17261 * Flag pointer to function template arguments.
17262 * Flag pointers to functions passed as arguments to a template (risk of false positives).
17265 ### <a name="Rt-essential"></a>T.41: Require only essential properties in a template's concepts
17267 ##### Reason
17269 Keep interfaces simple and stable.
17271 ##### Example (using TS concepts)
17273 Consider, a `sort` instrumented with (oversimplified) simple debug support:
17275     void sort(Sortable& s)  // sort sequence s
17276     {
17277         if (debug) cerr << "enter sort( " << s <<  ")\n";
17278         // ...
17279         if (debug) cerr << "exit sort( " << s <<  ")\n";
17280     }
17282 Should this be rewritten to:
17284     template<Sortable S>
17285         requires Streamable<S>
17286     void sort(S& s)  // sort sequence s
17287     {
17288         if (debug) cerr << "enter sort( " << s <<  ")\n";
17289         // ...
17290         if (debug) cerr << "exit sort( " << s <<  ")\n";
17291     }
17293 After all, there is nothing in `Sortable` that requires `iostream` support.
17294 On the other hand, there is nothing in the fundamental idea of sorting that says anything about debugging.
17296 ##### Note
17298 If we require every operation used to be listed among the requirements, the interface becomes unstable:
17299 Every time we change the debug facilities, the usage data gathering, testing support, error reporting, etc.,
17300 the definition of the template would need change and every use of the template would have to be recompiled.
17301 This is cumbersome, and in some environments infeasible.
17303 Conversely, if we use an operation in the implementation that is not guaranteed by concept checking,
17304 we may get a late compile-time error.
17306 By not using concept checking for properties of a template argument that is not considered essential,
17307 we delay checking until instantiation time.
17308 We consider this a worthwhile tradeoff.
17310 Note that using non-local, non-dependent names (such as `debug` and `cerr`) also introduces context dependencies that may lead to "mysterious" errors.
17312 ##### Note
17314 It can be hard to decide which properties of a type are essential and which are not.
17316 ##### Enforcement
17320 ### <a name="Rt-alias"></a>T.42: Use template aliases to simplify notation and hide implementation details
17322 ##### Reason
17324 Improved readability.
17325 Implementation hiding.
17326 Note that template aliases replace many uses of traits to compute a type.
17327 They can also be used to wrap a trait.
17329 ##### Example
17331     template<typename T, size_t N>
17332     class Matrix {
17333         // ...
17334         using Iterator = typename std::vector<T>::iterator;
17335         // ...
17336     };
17338 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>::`.
17340 ##### Example
17342     template<typename T>
17343     void user(T& c)
17344     {
17345         // ...
17346         typename container_traits<T>::value_type x; // bad, verbose
17347         // ...
17348     }
17350     template<typename T>
17351     using Value_type = typename container_traits<T>::value_type;
17354 This saves the user of `Value_type` from having to know the technique used to implement `value_type`s.
17356     template<typename T>
17357     void user2(T& c)
17358     {
17359         // ...
17360         Value_type<T> x;
17361         // ...
17362     }
17364 ##### Note
17366 A simple, common use could be expressed: "Wrap traits!"
17368 ##### Enforcement
17370 * Flag use of `typename` as a disambiguator outside `using` declarations.
17371 * ???
17373 ### <a name="Rt-using"></a>T.43: Prefer `using` over `typedef` for defining aliases
17375 ##### Reason
17377 Improved readability: With `using`, the new name comes first rather than being embedded somewhere in a declaration.
17378 Generality: `using` can be used for template aliases, whereas `typedef`s can't easily be templates.
17379 Uniformity: `using` is syntactically similar to `auto`.
17381 ##### Example
17383     typedef int (*PFI)(int);   // OK, but convoluted
17385     using PFI2 = int (*)(int);   // OK, preferred
17387     template<typename T>
17388     typedef int (*PFT)(T);      // error
17390     template<typename T>
17391     using PFT2 = int (*)(T);   // OK
17393 ##### Enforcement
17395 * Flag uses of `typedef`. This will give a lot of "hits" :-(
17397 ### <a name="Rt-deduce"></a>T.44: Use function templates to deduce class template argument types (where feasible)
17399 ##### Reason
17401 Writing the template argument types explicitly can be tedious and unnecessarily verbose.
17403 ##### Example
17405     tuple<int, string, double> t1 = {1, "Hamlet", 3.14};   // explicit type
17406     auto t2 = make_tuple(1, "Ophelia"s, 3.14);         // better; deduced type
17408 Note the use of the `s` suffix to ensure that the string is a `std::string`, rather than a C-style string.
17410 ##### Note
17412 Since you can trivially write a `make_T` function, so could the compiler. Thus, `make_T` functions may become redundant in the future.
17414 ##### Exception
17416 Sometimes there isn't a good way of getting the template arguments deduced and sometimes, you want to specify the arguments explicitly:
17418     vector<double> v = { 1, 2, 3, 7.9, 15.99 };
17419     list<Record*> lst;
17421 ##### Note
17423 Note that C++17 will make this rule redundant by allowing the template arguments to be deduced directly from constructor arguments:
17424 [Template parameter deduction for constructors (Rev. 3)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r1.html).
17425 For example:
17427     tuple t1 = {1, "Hamlet"s, 3.14}; // deduced: tuple<int, string, double>
17429 ##### Enforcement
17431 Flag uses where an explicitly specialized type exactly matches the types of the arguments used.
17433 ### <a name="Rt-regular"></a>T.46: Require template arguments to be at least `Regular` or `SemiRegular`
17435 ##### Reason
17437  Readability.
17438  Preventing surprises and errors.
17439  Most uses support that anyway.
17441 ##### Example
17443     class X {
17444             // ...
17445     public:
17446         explicit X(int);
17447         X(const X&);            // copy
17448         X operator=(const X&);
17449         X(X&&) noexcept;                 // move
17450         X& operator=(X&&) noexcept;
17451         ~X();
17452         // ... no more constructors ...
17453     };
17455     X x {1};    // fine
17456     X y = x;      // fine
17457     std::vector<X> v(10); // error: no default constructor
17459 ##### Note
17461 Semiregular requires default constructible.
17463 ##### Enforcement
17465 * Flag types that are not at least `SemiRegular`.
17467 ### <a name="Rt-visible"></a>T.47: Avoid highly visible unconstrained templates with common names
17469 ##### Reason
17471  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.
17472  This is particularly annoying/dangerous when ADL is used.
17473  Common names make this problem more likely.
17475 ##### Example
17477     namespace Bad {
17478         struct S { int m; };
17479         template<typename T1, typename T2>
17480         bool operator==(T1, T2) { cout << "Bad\n"; return true; }
17481     }
17483     namespace T0 {
17484         bool operator==(int, Bad::S) { cout << "T0\n"; return true; }  // compare to int
17486         void test()
17487         {
17488             Bad::S bad{ 1 };
17489             vector<int> v(10);
17490             bool b = 1 == bad;
17491             bool b2 = v.size() == bad;
17492         }
17493     }
17495 This prints `T0` and `Bad`.
17497 Now the `==` in `Bad` was designed to cause trouble, but would you have spotted the problem in real code?
17498 The problem is that `v.size()` returns an `unsigned` integer so that a conversion is needed to call the local `==`;
17499 the `==` in `Bad` requires no conversions.
17500 Realistic types, such as the standard-library iterators can be made to exhibit similar anti-social tendencies.
17502 ##### Note
17504 If an unconstrained template is defined in the same namespace as a type,
17505 that unconstrained template can be found by ADL (as happened in the example).
17506 That is, it is highly visible.
17508 ##### Note
17510 This rule should not be necessary, but the committee cannot agree to exclude unconstrained templated from ADL.
17512 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`.
17515 ##### Enforcement
17517 Flag templates defined in a namespace where concrete types are also defined (maybe not feasible until we have concepts).
17520 ### <a name="Rt-concept-def"></a>T.48: If your compiler does not support concepts, fake them with `enable_if`
17522 ##### Reason
17524 Because that's the best we can do without direct concept support.
17525 `enable_if` can be used to conditionally define functions and to select among a set of functions.
17527 ##### Example
17529     template <typename T>
17530     enable_if_t<is_integral_v<T>>
17531     f(T v)
17532     {
17533         // ...
17534     }
17536     // Equivalent to:
17537     template <Integral T>
17538     void f(T v)
17539     {
17540         // ...
17541     }
17543 ##### Note
17545 Beware of [complementary constraints](# T.25).
17546 Faking concept overloading using `enable_if` sometimes forces us to use that error-prone design technique.
17548 ##### Enforcement
17552 ### <a name="Rt-erasure"></a>T.49: Where possible, avoid type-erasure
17554 ##### Reason
17556 Type erasure incurs an extra level of indirection by hiding type information behind a separate compilation boundary.
17558 ##### Example
17560     ???
17562 **Exceptions**: Type erasure is sometimes appropriate, such as for `std::function`.
17564 ##### Enforcement
17569 ##### Note
17572 ## <a name="SS-temp-def"></a>T.def: Template definitions
17574 A template definition (class or function) can contain arbitrary code, so only a comprehensive review of C++ programming techniques would cover this topic.
17575 However, this section focuses on what is specific to template implementation.
17576 In particular, it focuses on a template definition's dependence on its context.
17578 ### <a name="Rt-depend"></a>T.60: Minimize a template's context dependencies
17580 ##### Reason
17582 Eases understanding.
17583 Minimizes errors from unexpected dependencies.
17584 Eases tool creation.
17586 ##### Example
17588     template<typename C>
17589     void sort(C& c)
17590     {
17591         std::sort(begin(c), end(c)); // necessary and useful dependency
17592     }
17594     template<typename Iter>
17595     Iter algo(Iter first, Iter last) {
17596         for (; first != last; ++first) {
17597             auto x = sqrt(*first); // potentially surprising dependency: which sqrt()?
17598             helper(first, x);      // potentially surprising dependency:
17599                                    // helper is chosen based on first and x
17600             TT var = 7;            // potentially surprising dependency: which TT?
17601         }
17602     }
17604 ##### Note
17606 Templates typically appear in header files so their context dependencies are more vulnerable to `#include` order dependencies than functions in `.cpp` files.
17608 ##### Note
17610 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.
17611 For example, an algorithm usually uses other algorithms and invoke operations that does not exclusively operate on arguments.
17612 And don't get us started on macros!
17614 **See also**: [T.69](#Rt-customization)
17616 ##### Enforcement
17618 ??? Tricky
17620 ### <a name="Rt-scary"></a>T.61: Do not over-parameterize members (SCARY)
17622 ##### Reason
17624 A member that does not depend on a template parameter cannot be used except for a specific template argument.
17625 This limits use and typically increases code size.
17627 ##### Example, bad
17629     template<typename T, typename A = std::allocator{}>
17630         // requires Regular<T> && Allocator<A>
17631     class List {
17632     public:
17633         struct Link {   // does not depend on A
17634             T elem;
17635             T* pre;
17636             T* suc;
17637         };
17639         using iterator = Link*;
17641         iterator first() const { return head; }
17643         // ...
17644     private:
17645         Link* head;
17646     };
17648     List<int> lst1;
17649     List<int, My_allocator> lst2;
17651 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.
17652 Typically, the solution is to make what would have been a nested class non-local, with its own minimal set of template parameters.
17654     template<typename T>
17655     struct Link {
17656         T elem;
17657         T* pre;
17658         T* suc;
17659     };
17661     template<typename T, typename A = std::allocator{}>
17662         // requires Regular<T> && Allocator<A>
17663     class List2 {
17664     public:
17665         using iterator = Link<T>*;
17667         iterator first() const { return head; }
17669         // ...
17670     private:
17671         Link* head;
17672     };
17674     List<int> lst1;
17675     List<int, My_allocator> lst2;
17677 Some people found the idea that the `Link` no longer was hidden inside the list scary, so we named the technique
17678 [SCARY](http://www.open-std.org/jtc1/sc22/WG21/docs/papers/2009/n2911.pdf).From that academic paper:
17679 "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."
17681 ##### Enforcement
17683 * Flag member types that do not depend on every template argument
17684 * Flag member functions that do not depend on every template argument
17686 ### <a name="Rt-nondependent"></a>T.62: Place non-dependent class template members in a non-templated base class
17688 ##### Reason
17690  Allow the base class members to be used without specifying template arguments and without template instantiation.
17692 ##### Example
17694     template<typename T>
17695     class Foo {
17696     public:
17697         enum { v1, v2 };
17698         // ...
17699     };
17703     struct Foo_base {
17704         enum { v1, v2 };
17705         // ...
17706     };
17708     template<typename T>
17709     class Foo : public Foo_base {
17710     public:
17711         // ...
17712     };
17714 ##### Note
17716 A more general version of this rule would be
17717 "If a template class member depends on only N template parameters out of M, place it in a base class with only N parameters."
17718 For N == 1, we have a choice of a base class of a class in the surrounding scope as in [T.61](#Rt-scary).
17720 ??? What about constants? class statics?
17722 ##### Enforcement
17724 * Flag ???
17726 ### <a name="Rt-specialization"></a>T.64: Use specialization to provide alternative implementations of class templates
17728 ##### Reason
17730 A template defines a general interface.
17731 Specialization offers a powerful mechanism for providing alternative implementations of that interface.
17733 ##### Example
17735     ??? string specialization (==)
17737     ??? representation specialization ?
17739 ##### Note
17743 ##### Enforcement
17747 ### <a name="Rt-tag-dispatch"></a>T.65: Use tag dispatch to provide alternative implementations of a function
17749 ##### Reason
17751 * A template defines a general interface.
17752 * Tag dispatch allows us to select implementations based on specific properties of an argument type.
17753 * Performance.
17755 ##### Example
17757 This is a simplified version of `std::copy` (ignoring the possibility of non-contiguous sequences)
17759     struct pod_tag {};
17760     struct non_pod_tag {};
17762     template<class T> struct copy_trait { using tag = non_pod_tag; };   // T is not "plain old data"
17764     template<> struct copy_trait<int> { using tag = pod_tag; };         // int is "plain old data"
17766     template<class Iter>
17767     Out copy_helper(Iter first, Iter last, Iter out, pod_tag)
17768     {
17769         // use memmove
17770     }
17772     template<class Iter>
17773     Out copy_helper(Iter first, Iter last, Iter out, non_pod_tag)
17774     {
17775         // use loop calling copy constructors
17776     }
17778     template<class Itert>
17779     Out copy(Iter first, Iter last, Iter out)
17780     {
17781         return copy_helper(first, last, out, typename copy_trait<Iter>::tag{})
17782     }
17784     void use(vector<int>& vi, vector<int>& vi2, vector<string>& vs, vector<string>& vs2)
17785     {
17786         copy(vi.begin(), vi.end(), vi2.begin()); // uses memmove
17787         copy(vs.begin(), vs.end(), vs2.begin()); // uses a loop calling copy constructors
17788     }
17790 This is a general and powerful technique for compile-time algorithm selection.
17792 ##### Note
17794 When `concept`s become widely available such alternatives can be distinguished directly:
17796     template<class Iter>
17797         requires Pod<Value_type<iter>>
17798     Out copy_helper(In, first, In last, Out out)
17799     {
17800         // use memmove
17801     }
17803     template<class Iter>
17804     Out copy_helper(In, first, In last, Out out)
17805     {
17806         // use loop calling copy constructors
17807     }
17809 ##### Enforcement
17814 ### <a name="Rt-specialization2"></a>T.67: Use specialization to provide alternative implementations for irregular types
17816 ##### Reason
17818  ???
17820 ##### Example
17822     ???
17824 ##### Enforcement
17828 ### <a name="Rt-cast"></a>T.68: Use `{}` rather than `()` within templates to avoid ambiguities
17830 ##### Reason
17832  `()` is vulnerable to grammar ambiguities.
17834 ##### Example
17836     template<typename T, typename U>
17837     void f(T t, U u)
17838     {
17839         T v1(x);    // is v1 a function of a variable?
17840         T v2 {x};   // variable
17841         auto x = T(u);  // construction or cast?
17842     }
17844     f(1, "asdf"); // bad: cast from const char* to int
17846 ##### Enforcement
17848 * flag `()` initializers
17849 * flag function-style casts
17852 ### <a name="Rt-customization"></a>T.69: Inside a template, don't make an unqualified nonmember function call unless you intend it to be a customization point
17854 ##### Reason
17856 * Provide only intended flexibility.
17857 * Avoid vulnerability to accidental environmental changes.
17859 ##### Example
17861 There are three major ways to let calling code customize a template.
17863     template<class T>
17864         // Call a member function
17865     void test1(T t)
17866     {
17867         t.f();    // require T to provide f()
17868     }
17870     template<class T>
17871     void test2(T t)
17872         // Call a nonmember function without qualification
17873     {
17874         f(t);  // require f(/*T*/) be available in caller's scope or in T's namespace
17875     }
17877     template<class T>
17878     void test3(T t)
17879         // Invoke a "trait"
17880     {
17881         test_traits<T>::f(t); // require customizing test_traits<>
17882                               // to get non-default functions/types
17883     }
17885 A trait is usually a type alias to compute a type,
17886 a `constexpr` function to compute a value,
17887 or a traditional traits template to be specialized on the user's type.
17889 ##### Note
17891 If you intend to call your own helper function `helper(t)` with a value `t` that depends on a template type parameter,
17892 put it in a `::detail` namespace and qualify the call as `detail::helper(t);`.
17893 An unqualified call becomes a customization point where any function `helper` in the namespace of `t`'s type can be invoked;
17894 this can cause problems like [unintentionally invoking unconstrained function templates](#Rt-unconstrained-adl).
17897 ##### Enforcement
17899 * In a template, flag an unqualified call to a nonmember function that passes a variable of dependent type when there is a nonmember function of the same name in the template's namespace.
17902 ## <a name="SS-temp-hier"></a>T.temp-hier: Template and hierarchy rules:
17904 Templates are the backbone of C++'s support for generic programming and class hierarchies the backbone of its support
17905 for object-oriented programming.
17906 The two language mechanisms can be used effectively in combination, but a few design pitfalls must be avoided.
17908 ### <a name="Rt-hier"></a>T.80: Do not naively templatize a class hierarchy
17910 ##### Reason
17912 Templating a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat.
17914 ##### Example, bad
17916     template<typename T>
17917     struct Container {         // an interface
17918         virtual T* get(int i);
17919         virtual T* first();
17920         virtual T* next();
17921         virtual void sort();
17922     };
17924     template<typename T>
17925     class Vector : public Container<T> {
17926     public:
17927         // ...
17928     };
17930     Vector<int> vi;
17931     Vector<string> vs;
17933 It is probably a dumb 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.
17935 Given this, the compiler cannot know if `vector<int>::sort()` is called, so it must generate code for it.
17936 Similar for `vector<string>::sort()`.
17937 Unless those two functions are called that's code bloat.
17938 Imagine what this would do to a class hierarchy with dozens of member functions and dozens of derived classes with many instantiations.
17940 ##### Note
17942 In many cases you can provide a stable interface by not parameterizing a base;
17943 see ["stable base"](#Rt-abi) and [OO and GP](#Rt-generic-oo)
17945 ##### Enforcement
17947 * Flag virtual functions that depend on a template argument. ??? False positives
17949 ### <a name="Rt-array"></a>T.81: Do not mix hierarchies and arrays
17951 ##### Reason
17953 An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results.
17955 ##### Example
17957 Assume that `Apple` and `Pear` are two kinds of `Fruit`s.
17959     void maul(Fruit* p)
17960     {
17961         *p = Pear{};     // put a Pear into *p
17962         p[1] = Pear{};   // put a Pear into p[1]
17963     }
17965     Apple aa [] = { an_apple, another_apple };   // aa contains Apples (obviously!)
17967     maul(aa);
17968     Apple& a0 = &aa[0];   // a Pear?
17969     Apple& a1 = &aa[1];   // a Pear?
17971 Probably, `aa[0]` will be a `Pear` (without the use of a cast!).
17972 If `sizeof(Apple) != sizeof(Pear)` the access to `aa[1]` will not be aligned to the proper start of an object in the array.
17973 We have a type violation and possibly (probably) a memory corruption.
17974 Never write such code.
17976 Note that `maul()` violates the a [`T*` points to an individual object rule](#Rf-ptr).
17978 **Alternative**: Use a proper (templatized) container:
17980     void maul2(Fruit* p)
17981     {
17982         *p = Pear{};   // put a Pear into *p
17983     }
17985     vector<Apple> va = { an_apple, another_apple };   // va contains Apples (obviously!)
17987     maul2(va);       // error: cannot convert a vector<Apple> to a Fruit*
17988     maul2(&va[0]);   // you asked for it
17990     Apple& a0 = &va[0];   // a Pear?
17992 Note that the assignment in `maul2()` violated the [no-slicing rule](#Res-slice).
17994 ##### Enforcement
17996 * Detect this horror!
17998 ### <a name="Rt-linear"></a>T.82: Linearize a hierarchy when virtual functions are undesirable
18000 ##### Reason
18002  ???
18004 ##### Example
18006     ???
18008 ##### Enforcement
18012 ### <a name="Rt-virtual"></a>T.83: Do not declare a member function template virtual
18014 ##### Reason
18016 C++ does not support that.
18017 If it did, vtbls could not be generated until link time.
18018 And in general, implementations must deal with dynamic linking.
18020 ##### Example, don't
18022     class Shape {
18023         // ...
18024         template<class T>
18025         virtual bool intersect(T* p);   // error: template cannot be virtual
18026     };
18028 ##### Note
18030 We need a rule because people keep asking about this
18032 ##### Alternative
18034 Double dispatch, visitors, calculate which function to call
18036 ##### Enforcement
18038 The compiler handles that.
18040 ### <a name="Rt-abi"></a>T.84: Use a non-template core implementation to provide an ABI-stable interface
18042 ##### Reason
18044 Improve stability of code.
18045 Avoid code bloat.
18047 ##### Example
18049 It could be a base class:
18051     struct Link_base {   // stable
18052         Link_base* suc;
18053         Link_base* pre;
18054     };
18056     template<typename T>   // templated wrapper to add type safety
18057     struct Link : Link_base {
18058         T val;
18059     };
18061     struct List_base {
18062         Link_base* first;   // first element (if any)
18063         int sz;             // number of elements
18064         void add_front(Link_base* p);
18065         // ...
18066     };
18068     template<typename T>
18069     class List : List_base {
18070     public:
18071         void put_front(const T& e) { add_front(new Link<T>{e}); }   // implicit cast to Link_base
18072         T& front() { static_cast<Link<T>*>(first).val; }   // explicit cast back to Link<T>
18073         // ...
18074     };
18076     List<int> li;
18077     List<string> ls;
18079 Now there is only one copy of the operations linking and unlinking elements of a `List`.
18080 The `Link` and `List` classes do nothing but type manipulation.
18082 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.
18084 **Alternative**: Use a [Pimpl](#Ri-pimpl) implementation.
18086 ##### Enforcement
18090 ## <a name="SS-variadic"></a>T.var: Variadic template rules
18094 ### <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
18096 ##### Reason
18098 Variadic templates is the most general mechanism for that, and is both efficient and type-safe. Don't use C varargs.
18100 ##### Example
18102     ??? printf
18104 ##### Enforcement
18106 * Flag uses of `va_arg` in user code.
18108 ### <a name="Rt-variadic-pass"></a>T.101: ??? How to pass arguments to a variadic template ???
18110 ##### Reason
18112  ???
18114 ##### Example
18116     ??? beware of move-only and reference arguments
18118 ##### Enforcement
18122 ### <a name="Rt-variadic-process"></a>T.102: How to process arguments to a variadic template
18124 ##### Reason
18126  ???
18128 ##### Example
18130     ??? forwarding, type checking, references
18132 ##### Enforcement
18136 ### <a name="Rt-variadic-not"></a>T.103: Don't use variadic templates for homogeneous argument lists
18138 ##### Reason
18140 There are more precise ways of specifying a homogeneous sequence, such as an `initializer_list`.
18142 ##### Example
18144     ???
18146 ##### Enforcement
18150 ## <a name="SS-meta"></a>T.meta: Template metaprogramming (TMP)
18152 Templates provide a general mechanism for compile-time programming.
18154 Metaprogramming is programming where at least one input or one result is a type.
18155 Templates offer Turing-complete (modulo memory capacity) duck typing at compile time.
18156 The syntax and techniques needed are pretty horrendous.
18158 ### <a name="Rt-metameta"></a>T.120: Use template metaprogramming only when you really need to
18160 ##### Reason
18162 Template metaprogramming is hard to get right, slows down compilation, and is often very hard to maintain.
18163 However, there are real-world examples where template metaprogramming provides better performance than any alternative short of expert-level assembly code.
18164 Also, there are real-world examples where template metaprogramming expresses the fundamental ideas better than run-time code.
18165 For example, if you really need AST manipulation at compile time (e.g., for optional matrix operation folding) there may be no other way in C++.
18167 ##### Example, bad
18169     ???
18171 ##### Example, bad
18173     enable_if
18175 Instead, use concepts. But see [How to emulate concepts if you don't have language support](#Rt-emulate).
18177 ##### Example
18179     ??? good
18181 **Alternative**: If the result is a value, rather than a type, use a [`constexpr` function](#Rt-fct).
18183 ##### Note
18185 If you feel the need to hide your template metaprogramming in macros, you have probably gone too far.
18187 ### <a name="Rt-emulate"></a>T.121: Use template metaprogramming primarily to emulate concepts
18189 ##### Reason
18191 Until concepts become generally available, we need to emulate them using TMP.
18192 Use cases that require concepts (e.g. overloading based on concepts) are among the most common (and simple) uses of TMP.
18194 ##### Example
18196     template<typename Iter>
18197         /*requires*/ enable_if<random_access_iterator<Iter>, void>
18198     advance(Iter p, int n) { p += n; }
18200     template<typename Iter>
18201         /*requires*/ enable_if<forward_iterator<Iter>, void>
18202     advance(Iter p, int n) { assert(n >= 0); while (n--) ++p;}
18204 ##### Note
18206 Such code is much simpler using concepts:
18208     void advance(RandomAccessIterator p, int n) { p += n; }
18210     void advance(ForwardIterator p, int n) { assert(n >= 0); while (n--) ++p;}
18212 ##### Enforcement
18216 ### <a name="Rt-tmp"></a>T.122: Use templates (usually template aliases) to compute types at compile time
18218 ##### Reason
18220 Template metaprogramming is the only directly supported and half-way principled way of generating types at compile time.
18222 ##### Note
18224 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
18226 ##### Example
18228     ??? big object / small object optimization
18230 ##### Enforcement
18234 ### <a name="Rt-fct"></a>T.123: Use `constexpr` functions to compute values at compile time
18236 ##### Reason
18238 A function is the most obvious and conventional way of expressing the computation of a value.
18239 Often a `constexpr` function implies less compile-time overhead than alternatives.
18241 ##### Note
18243 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
18245 ##### Example
18247     template<typename T>
18248         // requires Number<T>
18249     constexpr T pow(T v, int n)   // power/exponential
18250     {
18251         T res = 1;
18252         while (n--) res *= v;
18253         return res;
18254     }
18256     constexpr auto f7 = pow(pi, 7);
18258 ##### Enforcement
18260 * Flag template metaprograms yielding a value. These should be replaced with `constexpr` functions.
18262 ### <a name="Rt-std-tmp"></a>T.124: Prefer to use standard-library TMP facilities
18264 ##### Reason
18266 Facilities defined in the standard, such as `conditional`, `enable_if`, and `tuple`, are portable and can be assumed to be known.
18268 ##### Example
18270     ???
18272 ##### Enforcement
18276 ### <a name="Rt-lib"></a>T.125: If you need to go beyond the standard-library TMP facilities, use an existing library
18278 ##### Reason
18280 Getting advanced TMP facilities is not easy and using a library makes you part of a (hopefully supportive) community.
18281 Write your own "advanced TMP support" only if you really have to.
18283 ##### Example
18285     ???
18287 ##### Enforcement
18291 ## <a name="SS-temp-other"></a>Other template rules
18293 ### <a name="Rt-name"></a>T.140: Name all operations with potential for reuse
18295 ##### Reason
18297 Documentation, readability, opportunity for reuse.
18299 ##### Example
18301     struct Rec {
18302         string name;
18303         string addr;
18304         int id;         // unique identifier
18305     };
18307     bool same(const Rec& a, const Rec& b)
18308     {
18309         return a.id == b.id;
18310     }
18312     vector<Rec*> find_id(const string& name);    // find all records for "name"
18314     auto x = find_if(vr.begin(), vr.end(),
18315         [&](Rec& r) {
18316             if (r.name.size() != n.size()) return false; // name to compare to is in n
18317             for (int i = 0; i < r.name.size(); ++i)
18318                 if (tolower(r.name[i]) != tolower(n[i])) return false;
18319             return true;
18320         }
18321     );
18323 There is a useful function lurking here (case insensitive string comparison), as there often is when lambda arguments get large.
18325     bool compare_insensitive(const string& a, const string& b)
18326     {
18327         if (a.size() != b.size()) return false;
18328         for (int i = 0; i < a.size(); ++i) if (tolower(a[i]) != tolower(b[i])) return false;
18329         return true;
18330     }
18332     auto x = find_if(vr.begin(), vr.end(),
18333         [&](Rec& r) { compare_insensitive(r.name, n); }
18334     );
18336 Or maybe (if you prefer to avoid the implicit name binding to n):
18338     auto cmp_to_n = [&n](const string& a) { return compare_insensitive(a, n); };
18340     auto x = find_if(vr.begin(), vr.end(),
18341         [](const Rec& r) { return cmp_to_n(r.name); }
18342     );
18344 ##### Note
18346 whether functions, lambdas, or operators.
18348 ##### Exception
18350 * Lambdas logically used only locally, such as an argument to `for_each` and similar control flow algorithms.
18351 * Lambdas as [initializers](#???)
18353 ##### Enforcement
18355 * (hard) flag similar lambdas
18356 * ???
18358 ### <a name="Rt-lambda"></a>T.141: Use an unnamed lambda if you need a simple function object in one place only
18360 ##### Reason
18362 That makes the code concise and gives better locality than alternatives.
18364 ##### Example
18366     auto earlyUsersEnd = std::remove_if(users.begin(), users.end(),
18367                                         [](const User &a) { return a.id > 100; });
18370 ##### Exception
18372 Naming a lambda can be useful for clarity even if it is used only once.
18374 ##### Enforcement
18376 * Look for identical and near identical lambdas (to be replaced with named functions or named lambdas).
18378 ### <a name="Rt-var"></a>T.142?: Use template variables to simplify notation
18380 ##### Reason
18382 Improved readability.
18384 ##### Example
18386     ???
18388 ##### Enforcement
18392 ### <a name="Rt-nongeneric"></a>T.143: Don't write unintentionally nongeneric code
18394 ##### Reason
18396 Generality. Reusability. Don't gratuitously commit to details; use the most general facilities available.
18398 ##### Example
18400 Use `!=` instead of `<` to compare iterators; `!=` works for more objects because it doesn't rely on ordering.
18402     for (auto i = first; i < last; ++i) {   // less generic
18403         // ...
18404     }
18406     for (auto i = first; i != last; ++i) {   // good; more generic
18407         // ...
18408     }
18410 Of course, range-`for` is better still where it does what you want.
18412 ##### Example
18414 Use the least-derived class that has the functionality you need.
18416     class Base {
18417     public:
18418         Bar f();
18419         Bar g();
18420     };
18422     class Derived1 : public Base {
18423     public:
18424         Bar h();
18425     };
18427     class Derived2 : public Base {
18428     public:
18429         Bar j();
18430     };
18432     // bad, unless there is a specific reason for limiting to Derived1 objects only
18433     void my_func(Derived1& param)
18434     {
18435         use(param.f());
18436         use(param.g());
18437     }
18439     // good, uses only Base interface so only commit to that
18440     void my_func(Base& param)
18441     {
18442         use(param.f());
18443         use(param.g());
18444     }
18446 ##### Enforcement
18448 * Flag comparison of iterators using `<` instead of `!=`.
18449 * 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.
18450 * Flag functions that take a pointer or reference to a more-derived type but only use functions declared in a base type.
18452 ### <a name="Rt-specialize-function"></a>T.144: Don't specialize function templates
18454 ##### Reason
18456 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.
18458 ##### Example
18460     ???
18462 **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).
18464 ##### Enforcement
18466 * Flag all specializations of a function template. Overload instead.
18469 ### <a name="Rt-check-class"></a>T.150: Check that a class matches a concept using `static_assert`
18471 ##### Reason
18473 If you intend for a class to match a concept, verifying that early saves users pain.
18475 ##### Example
18477     class X {
18478     public:
18479         X() = delete;
18480         X(const X&) = default;
18481         X(X&&) = default;
18482         X& operator=(const X&) = default;
18483         // ...
18484     };
18486 Somewhere, possibly in an implementation file, let the compiler check the desired properties of `X`:
18488     static_assert(Default_constructible<X>);    // error: X has no default constructor
18489     static_assert(Copyable<X>);                 // error: we forgot to define X's move constructor
18492 ##### Enforcement
18494 Not feasible.
18496 # <a name="S-cpl"></a>CPL: C-style programming
18498 C and C++ are closely related languages.
18499 They both originate in "Classic C" from 1978 and have evolved in ISO committees since then.
18500 Many attempts have been made to keep them compatible, but neither is a subset of the other.
18502 C rule summary:
18504 * [CPL.1: Prefer C++ to C](#Rcpl-C)
18505 * [CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++](#Rcpl-subset)
18506 * [CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces](#Rcpl-interface)
18508 ### <a name="Rcpl-C"></a>CPL.1: Prefer C++ to C
18510 ##### Reason
18512 C++ provides better type checking and more notational support.
18513 It provides better support for high-level programming and often generates faster code.
18515 ##### Example
18517     char ch = 7;
18518     void* pv = &ch;
18519     int* pi = pv;   // not C++
18520     *pi = 999;      // overwrite sizeof(int) bytes near &ch
18522 The rules for implicit casting to and from `void*` in C are subtle and unenforced.
18523 In particular, this example violates a rule against converting to a type with stricter alignment.
18525 ##### Enforcement
18527 Use a C++ compiler.
18529 ### <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++
18531 ##### Reason
18533 That subset can be compiled with both C and C++ compilers, and when compiled as C++ is better type checked than "pure C."
18535 ##### Example
18537     int* p1 = malloc(10 * sizeof(int));                      // not C++
18538     int* p2 = static_cast<int*>(malloc(10 * sizeof(int)));   // not C, C-style C++
18539     int* p3 = new int[10];                                   // not C
18540     int* p4 = (int*) malloc(10 * sizeof(int));               // both C and C++
18542 ##### Enforcement
18544 * Flag if using a build mode that compiles code as C.
18546   * The C++ compiler will enforce that the code is valid C++ unless you use C extension options.
18548 ### <a name="Rcpl-interface"></a>CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces
18550 ##### Reason
18552 C++ is more expressive than C and offers better support for many types of programming.
18554 ##### Example
18556 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.
18557 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.
18559 ##### Example
18561 You can call C from C++:
18563     // in C:
18564     double sqrt(double);
18566     // in C++:
18567     extern "C" double sqrt(double);
18569     sqrt(2);
18571 ##### Example
18573 You can call C++ from C:
18575     // in C:
18576     X call_f(struct Y*, int);
18578     // in C++:
18579     extern "C" X call_f(Y* p, int i)
18580     {
18581         return p->f(i);   // possibly a virtual function call
18582     }
18584 ##### Enforcement
18586 None needed
18588 # <a name="S-source"></a>SF: Source files
18590 Distinguish between declarations (used as interfaces) and definitions (used as implementations).
18591 Use header files to represent interfaces and to emphasize logical structure.
18593 Source file rule summary:
18595 * [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)
18596 * [SF.2: A `.h` file may not contain object definitions or non-inline function definitions](#Rs-inline)
18597 * [SF.3: Use `.h` files for all declarations used in multiple source files](#Rs-declaration-header)
18598 * [SF.4: Include `.h` files before other declarations in a file](#Rs-include-order)
18599 * [SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface](#Rs-consistency)
18600 * [SF.6: Use `using namespace` directives for transition, for foundation libraries (such as `std`), or within a local scope (only)](#Rs-using)
18601 * [SF.7: Don't write `using namespace` at global scope in a header file](#Rs-using-directive)
18602 * [SF.8: Use `#include` guards for all `.h` files](#Rs-guards)
18603 * [SF.9: Avoid cyclic dependencies among source files](#Rs-cycles)
18604 * [SF.10: Avoid dependencies on implicitly `#include`d names](#Rs-implicit)
18605 * [SF.11: Header files should be self-contained](#Rs-contained)
18607 * [SF.20: Use `namespace`s to express logical structure](#Rs-namespace)
18608 * [SF.21: Don't use an unnamed (anonymous) namespace in a header](#Rs-unnamed)
18609 * [SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities](#Rs-unnamed2)
18611 ### <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
18613 ##### Reason
18615 It's a longstanding convention.
18616 But consistency is more important, so if your project uses something else, follow that.
18618 ##### Note
18620 This convention reflects a common use pattern:
18621 Headers are more often shared with C to compile as both C++ and C, which typically uses `.h`,
18622 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.
18623 On the other hand, implementation files are rarely shared with C and so should typically be distinguished from `.c` files,
18624 so it's normally best to name all C++ implementation files something else (such as `.cpp`).
18626 The specific names `.h` and `.cpp` are not required (just recommended as a default) and other names are in widespread use.
18627 Examples are `.hh`, `.C`, and `.cxx`. Use such names equivalently.
18628 In this document, we refer to `.h` and `.cpp` as a shorthand for header and implementation files,
18629 even though the actual extension may be different.
18631 Your IDE (if you use one) may have strong opinions about suffixes.
18633 ##### Example
18635     // foo.h:
18636     extern int a;   // a declaration
18637     extern void foo();
18639     // foo.cpp:
18640     int a;   // a definition
18641     void foo() { ++a; }
18643 `foo.h` provides the interface to `foo.cpp`. Global variables are best avoided.
18645 ##### Example, bad
18647     // foo.h:
18648     int a;   // a definition
18649     void foo() { ++a; }
18651 `#include <foo.h>` twice in a program and you get a linker error for two one-definition-rule violations.
18653 ##### Enforcement
18655 * Flag non-conventional file names.
18656 * Check that `.h` and `.cpp` (and equivalents) follow the rules below.
18658 ### <a name="Rs-inline"></a>SF.2: A `.h` file may not contain object definitions or non-inline function definitions
18660 ##### Reason
18662 Including entities subject to the one-definition rule leads to linkage errors.
18664 ##### Example
18666     // file.h:
18667     namespace Foo {
18668         int x = 7;
18669         int xx() { return x+x; }
18670     }
18672     // file1.cpp:
18673     #include <file.h>
18674     // ... more ...
18676      // file2.cpp:
18677     #include <file.h>
18678     // ... more ...
18680 Linking `file1.cpp` and `file2.cpp` will give two linker errors.
18682 **Alternative formulation**: A `.h` file must contain only:
18684 * `#include`s of other `.h` files (possibly with include guards)
18685 * templates
18686 * class definitions
18687 * function declarations
18688 * `extern` declarations
18689 * `inline` function definitions
18690 * `constexpr` definitions
18691 * `const` definitions
18692 * `using` alias definitions
18693 * ???
18695 ##### Enforcement
18697 Check the positive list above.
18699 ### <a name="Rs-declaration-header"></a>SF.3: Use `.h` files for all declarations used in multiple source files
18701 ##### Reason
18703 Maintainability. Readability.
18705 ##### Example, bad
18707     // bar.cpp:
18708     void bar() { cout << "bar\n"; }
18710     // foo.cpp:
18711     extern void bar();
18712     void foo() { bar(); }
18714 A maintainer of `bar` cannot find all declarations of `bar` if its type needs changing.
18715 The user of `bar` cannot know if the interface used is complete and correct. At best, error messages come (late) from the linker.
18717 ##### Enforcement
18719 * Flag declarations of entities in other source files not placed in a `.h`.
18721 ### <a name="Rs-include-order"></a>SF.4: Include `.h` files before other declarations in a file
18723 ##### Reason
18725 Minimize context dependencies and increase readability.
18727 ##### Example
18729     #include <vector>
18730     #include <algorithm>
18731     #include <string>
18733     // ... my code here ...
18735 ##### Example, bad
18737     #include <vector>
18739     // ... my code here ...
18741     #include <algorithm>
18742     #include <string>
18744 ##### Note
18746 This applies to both `.h` and `.cpp` files.
18748 ##### Note
18750 There is an argument for insulating code from declarations and macros in header files by `#including` headers *after* the code we want to protect
18751 (as in the example labeled "bad").
18752 However
18754 * that only works for one file (at one level): Use that technique in a header included with other headers and the vulnerability reappears.
18755 * a namespace (an "implementation namespace") can protect against many context dependencies.
18756 * full protection and flexibility require modules.
18758 **See also**:
18760 * [Working Draft, Extensions to C++ for Modules](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4592.pdf)
18761 * [Modules, Componentization, and Transition](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0141r0.pdf)
18763 ##### Enforcement
18765 Easy.
18767 ### <a name="Rs-consistency"></a>SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface
18769 ##### Reason
18771 This enables the compiler to do an early consistency check.
18773 ##### Example, bad
18775     // foo.h:
18776     void foo(int);
18777     int bar(long);
18778     int foobar(int);
18780     // foo.cpp:
18781     void foo(int) { /* ... */ }
18782     int bar(double) { /* ... */ }
18783     double foobar(int);
18785 The errors will not be caught until link time for a program calling `bar` or `foobar`.
18787 ##### Example
18789     // foo.h:
18790     void foo(int);
18791     int bar(long);
18792     int foobar(int);
18794     // foo.cpp:
18795     #include <foo.h>
18797     void foo(int) { /* ... */ }
18798     int bar(double) { /* ... */ }
18799     double foobar(int);   // error: wrong return type
18801 The return-type error for `foobar` is now caught immediately when `foo.cpp` is compiled.
18802 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.
18804 ##### Enforcement
18808 ### <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)
18810 ##### Reason
18812  `using namespace` can lead to name clashes, so it should be used sparingly.
18813  However, it is not always possible to qualify every name from a namespace in user code (e.g., during transition)
18814  and sometimes a namespace is so fundamental and prevalent in a code base, that consistent qualification would be verbose and distracting.
18816 ##### Example
18818     #include <string>
18819     #include <vector>
18820     #include <iostream>
18821     #include <memory>
18822     #include <algorithm>
18824     using namespace std;
18826     // ...
18828 Here (obviously), the standard library is used pervasively and apparently no other library is used, so requiring `std::` everywhere
18829 could be distracting.
18831 ##### Example
18833 The use of `using namespace std;` leaves the programmer open to a name clash with a name from the standard library
18835     #include <cmath>
18836     using namespace std;
18838     int g(int x)
18839     {
18840         int sqrt = 7;
18841         // ...
18842         return sqrt(x); // error
18843     }
18845 However, this is not particularly likely to lead to a resolution that is not an error and
18846 people who use `using namespace std` are supposed to know about `std` and about this risk.
18848 ##### Note
18850 A `.cpp` file is a form of local scope.
18851 There is little difference in the opportunities for name clashes in an N-line `.cpp` containing a `using namespace X`,
18852 an N-line function containing a `using namespace X`,
18853 and M functions each containing a `using namespace X`with N lines of code in total.
18855 ##### Note
18857 [Don't write `using namespace` in a header file](#Rs-using-directive).
18859 ##### Enforcement
18861 Flag multiple `using namespace` directives for different namespaces in a single source file.
18863 ### <a name="Rs-using-directive"></a>SF.7: Don't write `using namespace` at global scope in a header file
18865 ##### Reason
18867 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 may have different meaning when included in different orders.
18869 ##### Example
18871     // bad.h
18872     #include <iostream>
18873     using namespace std; // bad
18875     // user.cpp
18876     #include "bad.h"
18878     bool copy(/*... some parameters ...*/);    // some function that happens to be named copy
18880     int main() {
18881         copy(/*...*/);    // now overloads local ::copy and std::copy, could be ambiguous
18882     }
18884 ##### Enforcement
18886 Flag `using namespace` at global scope in a header file.
18888 ### <a name="Rs-guards"></a>SF.8: Use `#include` guards for all `.h` files
18890 ##### Reason
18892 To avoid files being `#include`d several times.
18894 In order to avoid include guard collisions, do not just name the guard after the filename.
18895 Be sure to also include a key and good differentiator, such as the name of library or component
18896 the header file is part of.
18898 ##### Example
18900     // file foobar.h:
18901     #ifndef LIBRARY_FOOBAR_H
18902     #define LIBRARY_FOOBAR_H
18903     // ... declarations ...
18904     #endif // LIBRARY_FOOBAR_H
18906 ##### Enforcement
18908 Flag `.h` files without `#include` guards.
18910 ##### Note
18912 Some implementations offer vendor extensions like `#pragma once` as alternative to include guards.
18913 It is not standard and it is not portable.  It injects the hosting machine's filesystem semantics
18914 into your program, in addition to locking you down to a vendor.
18915 Our recommendation is to write in ISO C++: See [rule P.2](#Rp-Cplusplus).
18917 ### <a name="Rs-cycles"></a>SF.9: Avoid cyclic dependencies among source files
18919 ##### Reason
18921 Cycles complicates comprehension and slows down compilation.
18922 Complicates conversion to use language-supported modules (when they become available).
18924 ##### Note
18926 Eliminate cycles; don't just break them with `#include` guards.
18928 ##### Example, bad
18930     // file1.h:
18931     #include "file2.h"
18933     // file2.h:
18934     #include "file3.h"
18936     // file3.h:
18937     #include "file1.h"
18939 ##### Enforcement
18941 Flag all cycles.
18944 ### <a name="Rs-implicit"></a>SF.10: Avoid dependencies on implicitly `#include`d names
18946 ##### Reason
18948 Avoid surprises.
18949 Avoid having to change `#include`s if an `#include`d header changes.
18950 Avoid accidentally becoming dependent on implementation details and logically separate entities included in a header.
18952 ##### Example
18954     #include <iostream>
18955     using namespace std;
18957     void use()                  // bad
18958     {
18959         string s;
18960         cin >> s;               // fine
18961         getline(cin, s);        // error: getline() not defined
18962         if (s == "surprise") {  // error == not defined
18963             // ...
18964         }
18965     }
18967 `<iostream>` exposes the definition of `std::string` ("why?" makes for a fun trivia question),
18968 but it is not required to do so by transitively including the entire `<string>` header,
18969 resulting in the popular beginner question "why doesn't `getline(cin,s);` work?"
18970 or even an occasional "`string`s cannot be compared with `==`).
18972 The solution is to explicitly `#include <string>`:
18974     #include <iostream>
18975     #include <string>
18976     using namespace std;
18978     void use()
18979     {
18980         string s;
18981         cin >> s;               // fine
18982         getline(cin, s);        // fine
18983         if (s == "surprise") {  // fine
18984             // ...
18985         }
18986     }
18988 ##### Note
18990 Some headers exist exactly to collect a set of consistent declarations from a variety of headers.
18991 For example:
18993     // basic_std_lib.h:
18995     #include <vector>
18996     #include <string>
18997     #include <map>
18998     #include <iostream>
18999     #include <random>
19000     #include <vector>
19002 a user can now get that set of declarations with a single `#include`"
19004     #include "basic_std_lib.h"
19006 This rule against implicit inclusion is not meant to prevent such deliberate aggregation.
19008 ##### Enforcement
19010 Enforcement would require some knowledge about what in a header is meant to be "exported" to users and what is there to enable implementation.
19011 No really good solution is possible until we have modules.
19013 ### <a name="Rs-contained"></a>SF.11: Header files should be self-contained
19015 ##### Reason
19017 Usability, headers should be simple to use and work when included on their own.
19018 Headers should encapsulate the functionality they provide.
19019 Avoid clients of a header having to manage that header's dependencies.
19021 ##### Example
19023     #include "helpers.h"
19024     // helpers.h depends on std::string and includes <string>
19026 ##### Note
19028 Failing to follow this results in difficult to diagnose errors for clients of a header.
19030 ##### Enforcement
19032 A test should verify that the header file itself compiles or that a cpp file which only includes the header file compiles.
19034 ### <a name="Rs-namespace"></a>SF.20: Use `namespace`s to express logical structure
19036 ##### Reason
19038  ???
19040 ##### Example
19042     ???
19044 ##### Enforcement
19048 ### <a name="Rs-unnamed"></a>SF.21: Don't use an unnamed (anonymous) namespace in a header
19050 ##### Reason
19052 It is almost always a bug to mention an unnamed namespace in a header file.
19054 ##### Example
19056     ???
19058 ##### Enforcement
19060 * Flag any use of an anonymous namespace in a header file.
19062 ### <a name="Rs-unnamed2"></a>SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities
19064 ##### Reason
19066 Nothing external can depend on an entity in a nested unnamed namespace.
19067 Consider putting every definition in an implementation source file in an unnamed namespace unless that is defining an "external/exported" entity.
19069 ##### Example
19071 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.
19073     ???
19075 ##### Enforcement
19077 * ???
19079 # <a name="S-stdlib"></a>SL: The Standard Library
19081 Using only the bare language, every task is tedious (in any language).
19082 Using a suitable library any task can be reasonably simple.
19084 The standard library has steadily grown over the years.
19085 Its description in the standard is now larger than that of the language features.
19086 So, it is likely that this library section of the guidelines will eventually grow in size to equal or exceed all the rest.
19088 << ??? We need another level of rule numbering ??? >>
19090 C++ Standard Library component summary:
19092 * [SL.con: Containers](#SS-con)
19093 * [SL.str: String](#SS-string)
19094 * [SL.io: Iostream](#SS-io)
19095 * [SL.regex: Regex](#SS-regex)
19096 * [SL.chrono: Time](#SS-chrono)
19097 * [SL.C: The C Standard Library](#SS-clib)
19099 Standard-library rule summary:
19101 * [SL.1: Use libraries wherever possible](#Rsl-lib)
19102 * [SL.2: Prefer the standard library to other libraries](#Rsl-sl)
19103 * [SL.3: Do not add non-standard entities to namespace `std`](#sl-std)
19104 * [SL.4: Use the standard library in a type-safe manner](#sl-safe)
19105 * ???
19107 ### <a name="Rsl-lib"></a>SL.1:  Use libraries wherever possible
19109 ##### Reason
19111 Save time. Don't re-invent the wheel.
19112 Don't replicate the work of others.
19113 Benefit from other people's work when they make improvements.
19114 Help other people when you make improvements.
19116 ### <a name="Rsl-sl"></a>SL.2: Prefer the standard library to other libraries
19118 ##### Reason
19120 More people know the standard library.
19121 It is more likely to be stable, well-maintained, and widely available than your own code or most other libraries.
19124 ### <a name="sl-std"></a>SL.3: Do not add non-standard entities to namespace `std`
19126 ##### Reason
19128 Adding to `std` may change the meaning of otherwise standards conforming code.
19129 Additions to `std` may clash with future versions of the standard.
19131 ##### Example
19133     ???
19135 ##### Enforcement
19137 Possible, but messy and likely to cause problems with platforms.
19139 ### <a name="sl-safe"></a>SL.4: Use the standard library in a type-safe manner
19141 ##### Reason
19143 Because, obviously, breaking this rule can lead to undefined behavior, memory corruption, and all kinds of other bad errors.
19145 ##### Note
19147 This is a semi-philosophical meta-rule, which needs many supporting concrete rules.
19148 We need it as an umbrella for the more specific rules.
19150 Summary of more specific rules:
19152 * [SL.4: Use the standard library in a type-safe manner](#sl-safe)
19155 ## <a name="SS-con"></a>SL.con: Containers
19159 Container rule summary:
19161 * [SL.con.1: Prefer using STL `array` or `vector` instead of a C array](#Rsl-arrays)
19162 * [SL.con.2: Prefer using STL `vector` by default unless you have a reason to use a different container](#Rsl-vector)
19163 * [SL.con.3: Avoid bounds errors](#Rsl-bounds)
19164 *  ???
19166 ### <a name="Rsl-arrays"></a>SL.con.1: Prefer using STL `array` or `vector` instead of a C array
19168 ##### Reason
19170 C arrays are less safe, and have no advantages over `array` and `vector`.
19171 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.
19172 Also, like a built-in array, a stack-allocated `std::array` keeps its elements on the stack.
19173 For a variable-length array, use `std::vector`, which additionally can change its size and handles memory allocation.
19175 ##### Example
19177     int v[SIZE];                        // BAD
19179     std::array<int, SIZE> w;             // ok
19181 ##### Example
19183     int* v = new int[initial_size];     // BAD, owning raw pointer
19184     delete[] v;                         // BAD, manual delete
19186     std::vector<int> w(initial_size);   // ok
19188 ##### Note
19190 Use `gsl::span` for non-owning references into a container.
19192 ##### Note
19194 Comparing the performance of a fixed-sized array allocated on the stack against a `vector` with its elements on the free store is bogus.
19195 You could just as well compare a `std::array` on the stack against the result of a `malloc()` accessed through a pointer.
19196 For most code, even the difference between stack allocation and free-store allocation doesn't matter, but the convenience and safety of `vector` does.
19197 People working with code for which that difference matters are quite capable of choosing between `array` and `vector`.
19199 ##### Enforcement
19201 * 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`.
19203 ### <a name="Rsl-vector"></a>SL.con.2: Prefer using STL `vector` by default unless you have a reason to use a different container
19205 ##### Reason
19207 `vector` and `array` are the only standard containers that offer the following advantages:
19209 * the fastest general-purpose access (random access, including being vectorization-friendly);
19210 * the fastest default access pattern (begin-to-end or end-to-begin is prefetcher-friendly);
19211 * the lowest space overhead (contiguous layout has zero per-element overhead, which is cache-friendly).
19213 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`.
19215 Even when other containers seem more suited, such a `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.
19217 ##### Note
19219 `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.
19221 ##### Exceptions
19223 If you have a good reason to use another container, use that instead. For example:
19225 * If `vector` suits your needs but you don't need the container to be variable size, use `array` instead.
19227 * 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.
19229 ##### Note
19231 To initialize a vector with a number of elements, use `()`-initialization.
19232 To initialize a vector with a list of elements, use `{}`-initialization.
19234     vector<int> v1(20);  // v1 has 20 elements with the value 0 (vector<int>{})
19235     vector<int> v2 {20}; // v2 has 1 element with the value 20
19237 [Prefer the {}-initializer syntax](#Res-list).
19239 ##### Enforcement
19241 * 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.
19243 ### <a name="Rsl-bounds"></a>SL.con.3: Avoid bounds errors
19245 ##### Reason
19247 Read or write beyond an allocated range of elements typically leads to bad errors, wrong results, crashes, and security violations.
19249 ##### Note
19251 The standard-library functions that apply to ranges of elements all have (or could have) bounds-safe overloads that take `span`.
19252 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()`.
19254 Ideally, the in-bounds guarantee should be statically enforced.
19255 For example:
19257 * a range-`for` cannot loop beyond the range of the container to which it is applied
19258 * a `v.begin(),v.end()` is easily determined to be bounds safe
19260 Such loops are as fast as any unchecked/unsafe equivalent.
19262 Often a simple pre-check can eliminate the need for checking of individual indices.
19263 For example
19265 * for `v.begin(),v.begin()+i` the `i` can easily be checked against `v.size()`
19267 Such loops can be much faster than individually checked element accesses.
19269 ##### Example, bad
19271     void f()
19272     {
19273         array<int, 10> a, b;
19274         memset(a.data(), 0, 10);         // BAD, and contains a length error (length = 10 * sizeof(int))
19275         memcmp(a.data(), b.data(), 10);  // BAD, and contains a length error (length = 10 * sizeof(int))
19276     }
19278 Also, `std::array<>::fill()` or `std::fill()` or even an empty initializer are better candidate than `memset()`.
19280 ##### Example, good
19282     void f()
19283     {
19284         array<int, 10> a, b, c{};       // c is initialized to zero
19285         a.fill(0);
19286         fill(b.begin(), b.end(), 0);    // std::fill()
19287         fill(b, 0);                     // std::fill() + Ranges TS
19289         if ( a == b ) {
19290           // ...
19291         }
19292     }
19294 ##### Example
19296 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.
19298     void f(std::vector<int>& v, std::array<int, 12> a, int i)
19299     {
19300         v[0] = a[0];        // BAD
19301         v.at(0) = a[0];     // OK (alternative 1)
19302         at(v, 0) = a[0];    // OK (alternative 2)
19304         v.at(0) = a[i];     // BAD
19305         v.at(0) = a.at(i);  // OK (alternative 1)
19306         v.at(0) = at(a, i); // OK (alternative 2)
19307     }
19309 ##### Enforcement
19311 * Issue a diagnostic for any call to a standard-library function that is not bounds-checked.
19312 ??? insert link to a list of banned functions
19314 This rule is part of the [bounds profile](#SS-bounds).
19316 **TODO Notes**:
19318 * Impact on the standard library will require close coordination with WG21, if only to ensure compatibility even if never standardized.
19319 * We are considering specifying bounds-safe overloads for stdlib (especially C stdlib) functions like `memcmp` and shipping them in the GSL.
19320 * 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).
19324 ## <a name="SS-string"></a>SL.str: String
19326 Text manipulation is a huge topic.
19327 `std::string` doesn't cover all of it.
19328 This section primarily tries to clarify `std::string`'s relation to `char*`, `zstring`, `string_view`, and `gsl::string_span`.
19329 The important issue of non-ASCII character sets and encodings (e.g., `wchar_t`, Unicode, and UTF-8) will be covered elsewhere.
19331 **See also**: [regular expressions](#SS-regex)
19333 Here, we use "sequence of characters" or "string" to refer to a sequence of characters meant to be read as text (somehow, eventually).
19334 We don't consider
19336 String summary:
19338 * [SL.str.1: Use `std::string` to own character sequences](#Rstr-string)
19339 * [SL.str.2: Use `std::string_view` or `gsl::string_span` to refer to character sequences](#Rstr-view)
19340 * [SL.str.3: Use `zstring` or `czstring` to refer to a C-style, zero-terminated, sequence of characters](#Rstr-zstring)
19341 * [SL.str.4: Use `char*` to refer to a single character](#Rstr-char*)
19342 * [SL.str.5: Use `std::byte` to refer to byte values that do not necessarily represent characters](#Rstr-byte)
19344 * [SL.str.10: Use `std::string` when you need to perform locale-sensitive string operations](#Rstr-locale)
19345 * [SL.str.11: Use `gsl::string_span` rather than `std::string_view` when you need to mutate a string](#Rstr-span)
19346 * [SL.str.12: Use the `s` suffix for string literals meant to be standard-library `string`s](#Rstr-s)
19348 **See also**:
19350 * [F.24 span](#Rf-range)
19351 * [F.25 zstring](#Rf-zstring)
19354 ### <a name="Rstr-string"></a>SL.str.1: Use `std::string` to own character sequences
19356 ##### Reason
19358 `string` correctly handles allocation, ownership, copying, gradual expansion, and offers a variety of useful operations.
19360 ##### Example
19362     vector<string> read_until(const string& terminator)
19363     {
19364         vector<string> res;
19365         for (string s; cin >> s && s != terminator; ) // read a word
19366             res.push_back(s);
19367         return res;
19368     }
19370 Note how `>>` and `!=` are provided for `string` (as examples of useful operations) and there are no explicit
19371 allocations, deallocations, or range checks (`string` takes care of those).
19373 In C++17, we might use `string_view` as the argument, rather than `const string*` to allow more flexibility to callers:
19375     vector<string> read_until(string_view terminator)   // C++17
19376     {
19377         vector<string> res;
19378         for (string s; cin >> s && s != terminator; ) // read a word
19379             res.push_back(s);
19380         return res;
19381     }
19383 The `gsl::string_span` is a current alternative offering most of the benefits of `std::string_view` for simple examples:
19385     vector<string> read_until(string_span terminator)
19386     {
19387         vector<string> res;
19388         for (string s; cin >> s && s != terminator; ) // read a word
19389             res.push_back(s);
19390         return res;
19391     }
19393 ##### Example, bad
19395 Don't use C-style strings for operations that require non-trivial memory management
19397     char* cat(const char* s1, const char* s2)   // beware!
19398         // return s1 + '.' + s2
19399     {
19400         int l1 = strlen(s1);
19401         int l2 = strlen(s2);
19402         char* p = (char*) malloc(l1 + l2 + 2);
19403         strcpy(p, s1, l1);
19404         p[l1] = '.';
19405         strcpy(p + l1 + 1, s2, l2);
19406         p[l1 + l2 + 1] = 0;
19407         return p;
19408     }
19410 Did we get that right?
19411 Will the caller remember to `free()` the returned pointer?
19412 Will this code pass a security review?
19414 ##### Note
19416 Do not assume that `string` is slower than lower-level techniques without measurement and remember than not all code is performance critical.
19417 [Don't optimize prematurely](#Rper-Knuth)
19419 ##### Enforcement
19423 ### <a name="Rstr-view"></a>SL.str.2: Use `std::string_view` or `gsl::string_span` to refer to character sequences
19425 ##### Reason
19427 `std::string_view` or `gsl::string_span` provides simple and (potentially) safe access to character sequences independently of how
19428 those sequences are allocated and stored.
19430 ##### Example
19432     vector<string> read_until(string_span terminator);
19434     void user(zstring p, const string& s, string_span ss)
19435     {
19436         auto v1 = read_until(p);
19437         auto v2 = read_until(s);
19438         auto v3 = read_until(ss);
19439         // ...
19440     }
19442 ##### Note
19444 `std::string_view` (C++17) is read-only.
19446 ##### Enforcement
19450 ### <a name="Rstr-zstring"></a>SL.str.3: Use `zstring` or `czstring` to refer to a C-style, zero-terminated, sequence of characters
19452 ##### Reason
19454 Readability.
19455 Statement of intent.
19456 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.
19457 Distinguishing these alternatives prevents misunderstandings and bugs.
19459 ##### Example
19461     void f1(const char* s); // s is probably a string
19463 All we know is that it is supposed to be the nullptr or point to at least one character
19465     void f1(zstring s);     // s is a C-style string or the nullptr
19466     void f1(czstring s);    // s is a C-style string constant or the nullptr
19467     void f1(std::byte* s);  // s is a pointer to a byte (C++17)
19469 ##### Note
19471 Don't convert a C-style string to `string` unless there is a reason to.
19473 ##### Note
19475 Like any other "plain pointer", a `zstring` should not represent ownership.
19477 ##### Note
19479 There are billions of lines of C++ "out there", most use `char*` and `const char*` without documenting intent.
19480 They are used in a wide variety of ways, including to represent ownership and as generic pointers to memory (instead of `void*`).
19481 It is hard to separate these uses, so this guideline is hard to follow.
19482 This is one of the major sources of bugs in C and C++ programs, so it is worthwhile to follow this guideline wherever feasible..
19484 ##### Enforcement
19486 * Flag uses of `[]` on a `char*`
19487 * Flag uses of `delete` on a `char*`
19488 * Flag uses of `free()` on a `char*`
19490 ### <a name="Rstr-char*"></a>SL.str.4: Use `char*` to refer to a single character
19492 ##### Reason
19494 The variety of uses of `char*` in current code is a major source of errors.
19496 ##### Example, bad
19498     char arr[] = {'a', 'b', 'c'};
19500     void print(const char* p)
19501     {
19502         cout << p << '\n';
19503     }
19505     void use()
19506     {
19507         print(arr);   // run-time error; potentially very bad
19508     }
19510 The array `arr` is not a C-style string because it is not zero-terminated.
19512 ##### Alternative
19514 See [`zstring`](#Rstr-zstring), [`string`](#Rstr-string), and [`string_span`](#Rstr-view).
19516 ##### Enforcement
19518 * Flag uses of `[]` on a `char*`
19520 ### <a name="Rstr-byte"></a>SL.str.5: Use `std::byte` to refer to byte values that do not necessarily represent characters
19522 ##### Reason
19524 Use of `char*` to represent a pointer to something that is not necessarily a character causes confusion
19525 and disables valuable optimizations.
19527 ##### Example
19529     ???
19531 ##### Note
19533 C++17
19535 ##### Enforcement
19540 ### <a name="Rstr-locale"></a>SL.str.10: Use `std::string` when you need to perform locale-sensitive string operations
19542 ##### Reason
19544 `std::string` supports standard-library [`locale` facilities](#Rstr-locale)
19546 ##### Example
19548     ???
19550 ##### Note
19554 ##### Enforcement
19558 ### <a name="Rstr-span"></a>SL.str.11: Use `gsl::string_span` rather than `std::string_view` when you need to mutate a string
19560 ##### Reason
19562 `std::string_view` is read-only.
19564 ##### Example
19568 ##### Note
19572 ##### Enforcement
19574 The compiler will flag attempts to write to a `string_view`.
19576 ### <a name="Rstr-s"></a>SL.str.12: Use the `s` suffix for string literals meant to be standard-library `string`s
19578 ##### Reason
19580 Direct expression of an idea minimizes mistakes.
19582 ##### Example
19584     auto pp1 = make_pair("Tokyo", 9.00);         // {C-style string,double} intended?
19585     pair<string, double> pp2 = {"Tokyo", 9.00};  // a bit verbose
19586     auto pp3 = make_pair("Tokyo"s, 9.00);        // {std::string,double}    // C++14
19587     pair pp4 = {"Tokyo"s, 9.00};                 // {std::string,double}    // C++17
19591 ##### Enforcement
19596 ## <a name="SS-io"></a>SL.io: Iostream
19598 `iostream`s is a type safe, extensible, formatted and unformatted I/O library for streaming I/O.
19599 It supports multiple (and user extensible) buffering strategies and multiple locales.
19600 It can be used for conventional I/O, reading and writing to memory (string streams),
19601 and user-defines extensions, such as streaming across networks (asio: not yet standardized).
19603 Iostream rule summary:
19605 * [SL.io.1: Use character-level input only when you have to](#Rio-low)
19606 * [SL.io.2: When reading, always consider ill-formed input](#Rio-validate)
19607 * [SL.io.3: Prefer iostreams for I/O](#Rio-streams)
19608 * [SL.io.10: Unless you use `printf`-family functions call `ios_base::sync_with_stdio(false)`](#Rio-sync)
19609 * [SL.io.50: Avoid `endl`](#Rio-endl)
19610 * [???](#???)
19612 ### <a name="Rio-low"></a>SL.io.1: Use character-level input only when you have to
19614 ##### Reason
19616 Unless you genuinely just deal with individual characters, using character-level input leads to the user code performing potentially error-prone
19617 and potentially inefficient composition of tokens out of characters.
19619 ##### Example
19621     char c;
19622     char buf[128];
19623     int i = 0;
19624     while (cin.get(c) && !isspace(c) && i < 128)
19625         buf[i++] = c;
19626     if (i == 128) {
19627         // ... handle too long string ....
19628     }
19630 Better (much simpler and probably faster):
19632     string s;
19633     s.reserve(128);
19634     cin >> s;
19636 and the `reserve(128)` is probably not worthwhile.
19638 ##### Enforcement
19643 ### <a name="Rio-validate"></a>SL.io.2: When reading, always consider ill-formed input
19645 ##### Reason
19647 Errors are typically best handled as soon as possible.
19648 If input isn't validated, every function must be written to cope with bad data (and that is not practical).
19650 ##### Example
19652     ???
19654 ##### Enforcement
19658 ### <a name="Rio-streams"></a>SL.io.3: Prefer `iostream`s for I/O
19660 ##### Reason
19662 `iostream`s are safe, flexible, and extensible.
19664 ##### Example
19666     // write a complex number:
19667     complex<double> z{ 3, 4 };
19668     cout << z << '\n';
19670 `complex` is a user-defined type and its I/O is defined without modifying the `iostream` library.
19672 ##### Example
19674     // read a file of complex numbers:
19675     for (complex<double> z; cin >> z; )
19676         v.push_back(z);
19678 ##### Exception
19680 ??? performance ???
19682 ##### Discussion: `iostream`s vs. the `printf()` family
19684 It is often (and often correctly) pointed out that the `printf()` family has two advantages compared to `iostream`s:
19685 flexibility of formatting and performance.
19686 This has to be weighed against `iostream`s advantages of extensibility to handle user-defined types, resilient against security violations,
19687 implicit memory management, and `locale` handling.
19689 If you need I/O performance, you can almost always do better than `printf()`.
19691 `gets()` `scanf()` using `s`, and `printf()` using `%s` are security hazards (vulnerable to buffer overflow and generally error-prone).
19692 In C11, they are replaced by `gets_s()`, `scanf_s()`, and `printf_s()` as safer alternatives, but they are still not type safe.
19694 ##### Enforcement
19696 Optionally flag `<cstdio>` and `<stdio.h>`.
19698 ### <a name="Rio-sync"></a>SL.io.10: Unless you use `printf`-family functions call `ios_base::sync_with_stdio(false)`
19700 ##### Reason
19702 Synchronizing `iostreams` with `printf-style` I/O can be costly.
19703 `cin` and `cout` are by default synchronized with `printf`.
19705 ##### Example
19707     int main()
19708     {
19709         ios_base::sync_with_stdio(false);
19710         // ... use iostreams ...
19711     }
19713 ##### Enforcement
19717 ### <a name="Rio-endl"></a>SL.io.50: Avoid `endl`
19719 ##### Reason
19721 The `endl` manipulator is mostly equivalent to `'\n'` and `"\n"`;
19722 as most commonly used it simply slows down output by doing redundant `flush()`s.
19723 This slowdown can be significant compared to `printf`-style output.
19725 ##### Example
19727     cout << "Hello, World!" << endl;    // two output operations and a flush
19728     cout << "Hello, World!\n";          // one output operation and no flush
19730 ##### Note
19732 For `cin`/`cout` (and equivalent) interaction, there is no reason to flush; that's done automatically.
19733 For writing to a file, there is rarely a need to `flush`.
19735 ##### Note
19737 Apart from the (occasionally important) issue of performance,
19738 the choice between `'\n'` and `endl` is almost completely aesthetic.
19740 ## <a name="SS-regex"></a>SL.regex: Regex
19742 `<regex>` is the standard C++ regular expression library.
19743 It supports a variety of regular expression pattern conventions.
19745 ## <a name="SS-chrono"></a>SL.chrono: Time
19747 `<chrono>` (defined in namespace `std::chrono`) provides the notions of `time_point` and `duration` together with functions for
19748 outputting time in various units.
19749 It provides clocks for registering `time_points`.
19751 ## <a name="SS-clib"></a>SL.C: The C Standard Library
19755 C Standard Library rule summary:
19757 * [S.C.1: Don't use setjmp/longjmp](#Rclib-jmp)
19758 * [???](#???)
19759 * [???](#???)
19761 ### <a name="Rclib-jmp"></a>SL.C.1: Don't use setjmp/longjmp
19763 ##### Reason
19765 a `longjmp` ignores destructors, thus invalidating all resource-management strategies relying on RAII
19767 ##### Enforcement
19769 Flag all occurrences of `longjmp`and `setjmp`
19773 # <a name="S-A"></a>A: Architectural ideas
19775 This section contains ideas about higher-level architectural ideas and libraries.
19777 Architectural rule summary:
19779 * [A.1: Separate stable code from less stable code](#Ra-stable)
19780 * [A.2: Express potentially reusable parts as a library](#Ra-lib)
19781 * [A.4: There should be no cycles among libraries](#Ra-dag)
19782 * [???](#???)
19783 * [???](#???)
19784 * [???](#???)
19785 * [???](#???)
19786 * [???](#???)
19787 * [???](#???)
19789 ### <a name="Ra-stable"></a>A.1: Separate stable code from less stable code
19791 Isolating less stable code facilitates its unit testing, interface improvement, refactoring, and eventual deprecation.
19793 ### <a name="Ra-lib"></a>A.2: Express potentially reusable parts as a library
19795 ##### Reason
19797 ##### Note
19799 A library is a collection of declarations and definitions maintained, documented, and shipped together.
19800 A library could be a set of headers (a "header-only library") or a set of headers plus a set of object files.
19801 You can statically or dynamically link a library into a program, or you can `#include` a header-only library.
19804 ### <a name="Ra-dag"></a>A.4: There should be no cycles among libraries
19806 ##### Reason
19808 * A cycle complicates the build process.
19809 * Cycles are hard to understand and may introduce indeterminism (unspecified behavior).
19811 ##### Note
19813 A library can contain cyclic references in the definition of its components.
19814 For example:
19816     ???
19818 However, a library should not depend on another that depends on it.
19821 # <a name="S-not"></a>NR: Non-Rules and myths
19823 This section contains rules and guidelines that are popular somewhere, but that we deliberately don't recommend.
19824 We know full well that there have been times and places where these rules made sense, and we have used them ourselves at times.
19825 However, in the context of the styles of programming we recommend and support with the guidelines, these "non-rules" would do harm.
19827 Even today, there can be contexts where the rules make sense.
19828 For example, lack of suitable tool support can make exceptions unsuitable in hard-real-time systems,
19829 but please don't blindly trust "common wisdom" (e.g., unsupported statements about "efficiency");
19830 such "wisdom" may be based on decades-old information or experienced from languages with very different properties than C++
19831 (e.g., C or Java).
19833 The positive arguments for alternatives to these non-rules are listed in the rules offered as "Alternatives".
19835 Non-rule summary:
19837 * [NR.1: Don't: All declarations should be at the top of a function](#Rnr-top)
19838 * [NR.2: Don't: Have only a single `return`-statement in a function](#Rnr-single-return)
19839 * [NR.3: Don't: Don't use exceptions](#Rnr-no-exceptions)
19840 * [NR.4: Don't: Place each class declaration in its own source file](#Rnr-lots-of-files)
19841 * [NR.5: Don't: Don't do substantive work in a constructor; instead use two-phase initialization](#Rnr-two-phase-init)
19842 * [NR.6: Don't: Place all cleanup actions at the end of a function and `goto exit`](#Rnr-goto-exit)
19843 * [NR.7: Don't: Make all data members `protected`](#Rnr-protected-data)
19844 * ???
19846 ### <a name="Rnr-top"></a>NR.1: Don't: All declarations should be at the top of a function
19848 ##### Reason (not to follow this rule)
19850 This rule is a legacy of old programming languages that didn't allow initialization of variables and constants after a statement.
19851 This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
19853 ##### Example, bad
19855     int use(int x)
19856     {
19857         int i;
19858         char c;
19859         double d;
19861         // ... some stuff ...
19863         if (x < i) {
19864             // ...
19865             i = f(x, d);
19866         }
19867         if (i < x) {
19868             // ...
19869             i = g(x, c);
19870         }
19871         return i;
19872     }
19874 The larger the distance between the uninitialized variable and its use, the larger the chance of a bug.
19875 Fortunately, compilers catch many "used before set" errors.
19876 Unfortunately, compilers cannot catch all such errors and unfortunately, the bugs aren't always as simple to spot as in this small example.
19879 ##### Alternative
19881 * [Always initialize an object](#Res-always)
19882 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
19884 ### <a name="Rnr-single-return"></a>NR.2: Don't: Have only a single `return`-statement in a function
19886 ##### Reason (not to follow this rule)
19888 The single-return rule can lead to unnecessarily convoluted code and the introduction of extra state variables.
19889 In particular, the single-return rule makes it harder to concentrate error checking at the top of a function.
19891 ##### Example
19893     template<class T>
19894     //  requires Number<T>
19895     string sign(T x)
19896     {
19897         if (x < 0)
19898             return "negative";
19899         else if (x > 0)
19900             return "positive";
19901         return "zero";
19902     }
19904 to use a single return only we would have to do something like
19906     template<class T>
19907     //  requires Number<T>
19908     string sign(T x)        // bad
19909     {
19910         string res;
19911         if (x < 0)
19912             res = "negative";
19913         else if (x > 0)
19914             res = "positive";
19915         else
19916             res = "zero";
19917         return res;
19918     }
19920 This is both longer and likely to be less efficient.
19921 The larger and more complicated the function is, the more painful the workarounds get.
19922 Of course many simple functions will naturally have just one `return` because of their simpler inherent logic.
19924 ##### Example
19926     int index(const char* p)
19927     {
19928         if (!p) return -1;  // error indicator: alternatively "throw nullptr_error{}"
19929         // ... do a lookup to find the index for p
19930         return i;
19931     }
19933 If we applied the rule, we'd get something like
19935     int index2(const char* p)
19936     {
19937         int i;
19938         if (!p)
19939             i = -1;  // error indicator
19940         else {
19941             // ... do a lookup to find the index for p
19942         }
19943         return i;
19944     }
19946 Note that we (deliberately) violated the rule against uninitialized variables because this style commonly leads to that.
19947 Also, this style is a temptation to use the [goto exit](#Rnr-goto-exit) non-rule.
19949 ##### Alternative
19951 * Keep functions short and simple
19952 * Feel free to use multiple `return` statements (and to throw exceptions).
19954 ### <a name="Rnr-no-exceptions"></a>NR.3: Don't: Don't use exceptions
19956 ##### Reason (not to follow this rule)
19958 There seem to be three main reasons given for this non-rule:
19960 * exceptions are inefficient
19961 * exceptions lead to leaks and errors
19962 * exception performance is not predictable
19964 There is no way we can settle this issue to the satisfaction of everybody.
19965 After all, the discussions about exceptions have been going on for 40+ years.
19966 Some languages cannot be used without exceptions, but others do not support them.
19967 This leads to strong traditions for the use and non-use of exceptions, and to heated debates.
19969 However, we can briefly outline why we consider exceptions the best alternative for general-purpose programming
19970 and in the context of these guidelines.
19971 Simple arguments for and against are often inconclusive.
19972 There are specialized applications where exceptions indeed can be inappropriate
19973 (e.g., hard-real-time systems without support for reliable estimates of the cost of handling an exception).
19975 Consider the major objections to exceptions in turn
19977 * Exceptions are inefficient:
19978 Compared to what?
19979 When comparing make sure that the same set of errors are handled and that they are handled equivalently.
19980 In particular, do not compare a program that immediately terminate on seeing an error with a program
19981 that carefully cleans up resources before logging an error.
19982 Yes, some systems have poor exception handling implementations; sometimes, such implementations force us to use
19983 other error-handling approaches, but that's not a fundamental problem with exceptions.
19984 When using an efficiency argument - in any context - be careful that you have good data that actually provides
19985 insight into the problem under discussion.
19986 * Exceptions lead to leaks and errors.
19987 They do not.
19988 If your program is a rat's nest of pointers without an overall strategy for resource management,
19989 you have a problem whatever you do.
19990 If your system consists of a million lines of such code,
19991 you probably will not be able to use exceptions,
19992 but that's a problem with excessive and undisciplined pointer use, rather than with exceptions.
19993 In our opinion, you need RAII to make exception-based error handling simple and safe -- simpler and safer than alternatives.
19994 * Exception performance is not predictable.
19995 If you are in a hard-real-time system where you must guarantee completion of a task in a given time,
19996 you need tools to back up such guarantees.
19997 As far as we know such tools are not available (at least not to most programmers).
19999 Many, possibly most, problems with exceptions stem from historical needs to interact with messy old code.
20001 The fundamental arguments for the use of exceptions are
20003 * They clearly differentiate between erroneous return and ordinary return
20004 * They cannot be forgotten or ignored
20005 * They can be used systematically
20007 Remember
20009 * Exceptions are for reporting errors (in C++; other languages can have different uses for exceptions).
20010 * Exceptions are not for errors that can be handled locally.
20011 * Don't try to catch every exception in every function (that's tedious, clumsy, and leads to slow code).
20012 * Exceptions are not for errors that require instant termination of a module/system after a non-recoverable error.
20014 ##### Example
20016     ???
20018 ##### Alternative
20020 * [RAII](#Re-raii)
20021 * Contracts/assertions: Use GSL's `Expects` and `Ensures` (until we get language support for contracts)
20023 ### <a name="Rnr-lots-of-files"></a>NR.4: Don't: Place each class declaration in its own source file
20025 ##### Reason (not to follow this rule)
20027 The resulting number of files are hard to manage and can slow down compilation.
20028 Individual classes are rarely a good logical unit of maintenance and distribution.
20030 ##### Example
20032     ???
20034 ##### Alternative
20036 * Use namespaces containing logically cohesive sets of classes and functions.
20038 ### <a name="Rnr-two-phase-init"></a>NR.5: Don't: Don't do substantive work in a constructor; instead use two-phase initialization
20040 ##### Reason (not to follow this rule)
20042 Following this rule leads to weaker invariants,
20043 more complicated code (having to deal with semi-constructed objects),
20044 and errors (when we didn't deal correctly with semi-constructed objects consistently).
20046 ##### Example, bad
20048     class Picture
20049     {
20050         int mx;
20051         int my;
20052         char * data;
20053     public:
20054         Picture(int x, int y)
20055         {
20056             mx = x,
20057             my = y;
20058             data = nullptr;
20059         }
20060     
20061         ~Picture()
20062         {
20063             Cleanup();
20064         }
20065     
20066         bool Init()
20067         {
20068             // invariant checks
20069             if (mx <= 0 || my <= 0) {
20070                 return false;
20071             }
20072             if (data) {
20073                 return false;
20074             }
20075             data = (char*) malloc(x*y*sizeof(int));
20076             return data != nullptr;
20077         }
20078     
20079         void Cleanup()
20080         {
20081             if (data) free(data);
20082             data = nullptr;
20083         }
20084     };
20085     
20086     Picture picture(100, 0); // not ready-to-use picture here
20087     // this will fail..
20088     if (!picture.Init()) {
20089         puts("Error, invalid picture");
20090     }
20091     // now have a invalid picture object instance.
20093 ##### Example, good
20095     class Picture
20096     {
20097         size_t mx;
20098         size_t my;
20099         vector<char> data;
20100     
20101         static size_t check_size(size_t s)
20102         {
20103             // invariant check
20104             Expects(s > 0);
20105             return s;
20106         }
20107     
20108     public:
20109         // even more better would be a class for a 2D Size as one single parameter
20110         Picture(size_t x, size_t y)
20111             : mx(check_size(x))
20112             , my(check_size(y))
20113             // now we know x and y have a valid size
20114             , data(mx * my * sizeof(int)) // will throw std::bad_alloc on error
20115         {
20116             // picture is ready-to-use
20117         }
20118         // compiler generated dtor does the job. (also see C.21)
20119     };
20120     
20121     Picture picture1(100, 100);
20122     // picture is ready-to-use here...
20123     
20124     // not a valid size for y,
20125     // default contract violation behavior will call std::terminate then
20126     Picture picture2(100, 0);
20127     // not reach here...
20129 ##### Alternative
20131 * Always establish a class invariant in a constructor.
20132 * Don't define an object before it is needed.
20134 ### <a name="Rnr-goto-exit"></a>NR.6: Don't: Place all cleanup actions at the end of a function and `goto exit`
20136 ##### Reason (not to follow this rule)
20138 `goto` is error-prone.
20139 This technique is a pre-exception technique for RAII-like resource and error handling.
20141 ##### Example, bad
20143     void do_something(int n)
20144     {
20145         if (n < 100) goto exit;
20146         // ...
20147         int* p = (int*) malloc(n);
20148         // ...
20149         if (some_error) goto_exit;
20150         // ...
20151     exit:
20152         free(p);
20153     }
20155 and spot the bug.
20157 ##### Alternative
20159 * Use exceptions and [RAII](#Re-raii)
20160 * for non-RAII resources, use [`finally`](#Re-finally).
20162 ### <a name="Rnr-protected-data"></a>NR.7: Don't: Make all data members `protected`
20164 ##### Reason (not to follow this rule)
20166 `protected` data is a source of errors.
20167 `protected` data can be manipulated from an unbounded amount of code in various places.
20168 `protected` data is the class hierarchy equivalent to global data.
20170 ##### Example
20172     ???
20174 ##### Alternative
20176 * [Make member data `public` or (preferably) `private`](#Rh-protected)
20179 # <a name="S-references"></a>RF: References
20181 Many coding standards, rules, and guidelines have been written for C++, and especially for specialized uses of C++.
20182 Many
20184 * focus on lower-level issues, such as the spelling of identifiers
20185 * are written by C++ novices
20186 * see "stopping programmers from doing unusual things" as their primary aim
20187 * aim at portability across many compilers (some 10 years old)
20188 * are written to preserve decades old code bases
20189 * aim at a single application domain
20190 * are downright counterproductive
20191 * are ignored (must be ignored by programmers to get their work done well)
20193 A bad coding standard is worse than no coding standard.
20194 However an appropriate set of guidelines are much better than no standards: "Form is liberating."
20196 Why can't we just have a language that allows all we want and disallows all we don't want ("a perfect language")?
20197 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.
20198 Also, your needs change over time and a general-purpose language is needed to allow you to adapt.
20199 A language that is ideal for today would be overly restrictive tomorrow.
20201 Coding guidelines adapt the use of a language to specific needs.
20202 Thus, there cannot be a single coding style for everybody.
20203 We expect different organizations to provide additions, typically with more restrictions and firmer style rules.
20205 Reference sections:
20207 * [RF.rules: Coding rules](#SS-rules)
20208 * [RF.books: Books with coding guidelines](#SS-books)
20209 * [RF.C++: C++ Programming (C++11/C++14/C++17)](#SS-Cplusplus)
20210 * [RF.web: Websites](#SS-web)
20211 * [RS.video: Videos about "modern C++"](#SS-vid)
20212 * [RF.man: Manuals](#SS-man)
20213 * [RF.core: Core Guidelines materials](#SS-core)
20215 ## <a name="SS-rules"></a>RF.rules: Coding rules
20217 * [Boost Library Requirements and Guidelines](http://www.boost.org/development/requirements.html).
20218   ???.
20219 * [Bloomberg: BDE C++ Coding](https://github.com/bloomberg/bde/wiki/CodingStandards.pdf).
20220   Has a strong emphasis on code organization and layout.
20221 * Facebook: ???
20222 * [GCC Coding Conventions](https://gcc.gnu.org/codingconventions.html).
20223   C++03 and (reasonably) a bit backwards looking.
20224 * [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html).
20225   Geared toward C++03 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.
20226 * [JSF++: JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS](http://www.stroustrup.com/JSF-AV-rules.pdf).
20227   Document Number 2RDU00001 Rev C. December 2005.
20228   For flight control software.
20229   For hard-real-time.
20230   This means that it is necessarily very restrictive ("if the program fails somebody dies").
20231   For example, no free store allocation or deallocation may occur after the plane takes off (no memory overflow and no fragmentation allowed).
20232   No exception may be used (because there was no available tool for guaranteeing that an exception would be handled within a fixed short time).
20233   Libraries used have to have been approved for mission critical applications.
20234   Any similarities to this set of guidelines are unsurprising because Bjarne Stroustrup was an author of JSF++.
20235   Recommended, but note its very specific focus.
20236 * [Mozilla Portability Guide](https://developer.mozilla.org/en-US/docs/Mozilla/C%2B%2B_Portability_Guide).
20237   As the name indicates, this aims for portability across many (old) compilers.
20238   As such, it is restrictive.
20239 * [Geosoft.no: C++ Programming Style Guidelines](http://geosoft.no/development/cppstyle.html).
20240   ???.
20241 * [Possibility.com: C++ Coding Standard](http://www.possibility.com/Cpp/CppCodingStandard.html).
20242   ???.
20243 * [SEI CERT: Secure C++ Coding Standard](https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=637).
20244   A very nicely done set of rules (with examples and rationales) done for security-sensitive code.
20245   Many of their rules apply generally.
20246 * [High Integrity C++ Coding Standard](http://www.codingstandard.com/).
20247 * [llvm](http://llvm.org/docs/CodingStandards.html).
20248   Somewhat brief, pre-C++11, and (not unreasonably) adjusted to its domain.
20249 * ???
20251 ## <a name="SS-books"></a>RF.books: Books with coding guidelines
20253 * [Meyers96](#Meyers96) Scott Meyers: *More Effective C++*. Addison-Wesley 1996.
20254 * [Meyers97](#Meyers97) Scott Meyers: *Effective C++, Second Edition*. Addison-Wesley 1997.
20255 * [Meyers01](#Meyers01) Scott Meyers: *Effective STL*. Addison-Wesley 2001.
20256 * [Meyers05](#Meyers05) Scott Meyers: *Effective C++, Third Edition*. Addison-Wesley 2005.
20257 * [Meyers15](#Meyers15) Scott Meyers: *Effective Modern C++*. O'Reilly 2015.
20258 * [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.
20259 * [Stroustrup05](#Stroustrup05) Bjarne Stroustrup: [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
20260   LCSD05. October 2005.
20261 * [Stroustrup14](#Stroustrup05) Stroustrup: [A Tour of C++](http://www.stroustrup.com/Tour.html).
20262   Addison Wesley 2014.
20263   Each chapter ends with an advice section consisting of a set of recommendations.
20264 * [Stroustrup13](#Stroustrup13) Stroustrup: [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html).
20265   Addison Wesley 2013.
20266   Each chapter ends with an advice section consisting of a set of recommendations.
20267 * Stroustrup: [Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
20268   for [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
20269   Mostly low-level naming and layout rules.
20270   Primarily a teaching tool.
20272 ## <a name="SS-Cplusplus"></a>RF.C++: C++ Programming (C++11/C++14)
20274 * [TC++PL4](http://www.stroustrup.com/4th.html):
20275 A thorough description of the C++ language and standard libraries for experienced programmers.
20276 * [Tour++](http://www.stroustrup.com/Tour.html):
20277 An overview of the C++ language and standard libraries for experienced programmers.
20278 * [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html):
20279 A textbook for beginners and relative novices.
20281 ## <a name="SS-web"></a>RF.web: Websites
20283 * [isocpp.org](https://isocpp.org)
20284 * [Bjarne Stroustrup's home pages](http://www.stroustrup.com)
20285 * [WG21](http://www.open-std.org/jtc1/sc22/wg21/)
20286 * [Boost](http://www.boost.org)<a name="Boost"></a>
20287 * [Adobe open source](http://www.adobe.com/open-source.html)
20288 * [Poco libraries](http://pocoproject.org/)
20289 * Sutter's Mill?
20290 * ???
20292 ## <a name="SS-vid"></a>RS.video: Videos about "modern C++"
20294 * Bjarne Stroustrup: [C++11 Style](http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style). 2012.
20295 * 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
20296 * All the talks from [CppCon '14](https://isocpp.org/blog/2014/11/cppcon-videos-c9)
20297 * Bjarne Stroustrup: [The essence of C++](https://www.youtube.com/watch?v=86xWVb4XIyE) at the University of Edinburgh. 2014.
20298 * Bjarne Stroustrup: [The Evolution of C++ Past, Present and Future](https://www.youtube.com/watch?v=_wzc7a3McOs). CppCon 2016 keynote.
20299 * Bjarne Stroustrup: [Make Simple Tasks Simple!](https://www.youtube.com/watch?v=nesCaocNjtQ). CppCon 2014 keynote.
20300 * Bjarne Stroustrup: [Writing Good C++14](https://www.youtube.com/watch?v=1OEu9C51K2A). CppCon 2015 keynote about the Core Guidelines.
20301 * Herb Sutter: [Writing Good C++14... By Default](https://www.youtube.com/watch?v=hEx5DNLWGgA). CppCon 2015 keynote about the Core Guidelines.
20302 * CppCon 15
20303 * ??? C++ Next
20304 * ??? Meting C++
20305 * ??? more ???
20307 ## <a name="SS-man"></a>RF.man: Manuals
20309 * ISO C++ Standard C++11.
20310 * ISO C++ Standard C++14.
20311 * [ISO C++ Standard C++17](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4606.pdf). Committee Draft.
20312 * [Palo Alto "Concepts" TR](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3351.pdf).
20313 * [ISO C++ Concepts TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
20314 * [WG21 Ranges report](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf). Draft.
20317 ## <a name="SS-core"></a>RF.core: Core Guidelines materials
20319 This section contains materials that has been useful for presenting the core guidelines and the ideas behind them:
20321 * [Our documents directory](https://github.com/isocpp/CppCoreGuidelines/tree/master/docs)
20322 * 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.
20323 * Sergey Zubkov: [a Core Guidelines talk](https://www.youtube.com/watch?v=DyLwdl_6vmU)
20324 and here are the [slides](http://2017.cppconf.ru/talks/sergey-zubkov). In Russian. 2017.
20325 * Neil MacIntosh: [The Guideline Support Library: One Year Later](https://www.youtube.com/watch?v=_GhNnCuaEjo). CppCon 2016.
20326 * Bjarne Stroustrup: [Writing Good C++14](https://www.youtube.com/watch?v=1OEu9C51K2A). CppCon 2015 keynote.
20327 * Herb Sutter: [Writing Good C++14... By Default](https://www.youtube.com/watch?v=hEx5DNLWGgA). CppCon 2015 keynote.
20328 * Peter Sommerlad: [C++ Core Guidelines - Modernize your C++ Code Base](https://www.youtube.com/watch?v=fQ926v4ZzAM). ACCU 2017.
20329 * Bjarne Stroustrup: [No Littering!](https://www.youtube.com/watch?v=01zI9kV4h8c). Bay Area ACCU 2016.
20330 It gives some idea of the ambition level for the Core Guidelines.
20332 Note that slides for CppCon presentations are available (links with the posted videos).
20334 Contributions to this list would be most welcome.
20336 ## <a name="SS-ack"></a>Acknowledgements
20338 Thanks to the many people who contributed rules, suggestions, supporting information, references, etc.:
20340 * Peter Juhl
20341 * Neil MacIntosh
20342 * Axel Naumann
20343 * Andrew Pardoe
20344 * Gabriel Dos Reis
20345 * Zhuang, Jiangang (Jeff)
20346 * Sergey Zubkov
20348 and see the contributor list on the github.
20350 # <a name="S-profile"></a>Pro: Profiles
20352 Ideally, we would follow all of the guidelines.
20353 That would give the cleanest, most regular, least error-prone, and often the fastest code.
20354 Unfortunately, that is usually impossible because we have to fit our code into large code bases and use existing libraries.
20355 Often, such code has been written over decades and does not follow these guidelines.
20356 We must aim for [gradual adoption](#S-modernizing).
20358 Whatever strategy for gradual adoption we adopt, we need to be able to apply sets of related guidelines to address some set
20359 of problems first and leave the rest until later.
20360 A similar idea of "related guidelines" becomes important when some, but not all, guidelines are considered relevant to a code base
20361 or if a set of specialized guidelines is to be applied for a specialized application area.
20362 We call such a set of related guidelines a "profile".
20363 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"
20364 or "static type safety."
20365 Each profile is designed to eliminate a class of errors.
20366 Enforcement of "random" rules in isolation is more likely to be disruptive to a code base than delivering a definite improvement.
20368 A "profile" is a set of deterministic and portably enforceable subset rules (i.e., restrictions) that are designed to achieve a specific guarantee.
20369 "Deterministic" means they require only local analysis and could be implemented in a compiler (though they don't need to be).
20370 "Portably enforceable" means they are like language rules, so programmers can count on different enforcement tools giving the same answer for the same code.
20372 Code written to be warning-free using such a language profile is considered to conform to the profile.
20373 Conforming code is considered to be safe by construction with regard to the safety properties targeted by that profile.
20374 Conforming code will not be the root cause of errors for that property,
20375 although such errors may be introduced into a program by other code, libraries or the external environment.
20376 A profile may also introduce additional library types to ease conformance and encourage correct code.
20378 Profiles summary:
20380 * [Pro.type: Type safety](#SS-type)
20381 * [Pro.bounds: Bounds safety](#SS-bounds)
20382 * [Pro.lifetime: Lifetime safety](#SS-lifetime)
20384 In the future, we expect to define many more profiles and add more checks to existing profiles.
20385 Candidates include:
20387 * narrowing arithmetic promotions/conversions (likely part of a separate safe-arithmetic profile)
20388 * arithmetic cast from negative floating point to unsigned integral type (ditto)
20389 * selected undefined behavior: Start with Gabriel Dos Reis's UB list developed for the WG21 study group
20390 * selected unspecified behavior: Addressing portability concerns.
20391 * `const` violations: Mostly done by compilers already, but we can catch inappropriate casting and underuse of `const`.
20393 Enabling a profile is implementation defined; typically, it is set in the analysis tool used.
20395 To suppress enforcement of a profile check, place a `suppress` annotation on a language contract. For example:
20397     [[suppress(bounds)]] char* raw_find(char* p, int n, char x)    // find x in p[0]..p[n - 1]
20398     {
20399         // ...
20400     }
20402 Now `raw_find()` can scramble memory to its heart's content.
20403 Obviously, suppression should be very rare.
20405 ## <a name="SS-type"></a>Pro.safety: Type-safety profile
20407 This profile makes it easier to construct code that uses types correctly and avoids inadvertent type punning.
20408 It does so by focusing on removing the primary sources of type violations, including unsafe uses of casts and unions.
20410 For the purposes of this section,
20411 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.
20412 Memory accessed as a type `T` should not be valid memory that actually contains an object of an unrelated type `U`.
20413 Note that the safety is intended to be complete when combined also with [Bounds safety](#SS-bounds) and [Lifetime safety](#SS-lifetime).
20415 An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic.
20417 Type safety profile summary:
20419 * <a name="Pro-type-avoidcasts"></a>Type.1: [Avoid casts](#Res-casts):
20420 <a name="Pro-type-reinterpretcast">a. </a>Don't use `reinterpret_cast`; A strict version of [Avoid casts](#Res-casts) and [prefer named casts](#Res-casts-named).
20421 <a name="Pro-type-arithmeticcast">b. </a>Don't use `static_cast` for arithmetic types; A strict version of [Avoid casts](#Res-casts) and [prefer named casts](#Res-casts-named).
20422 <a name="Pro-type-identitycast">c. </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).
20423 <a name="Pro-type-implicitpointercast">d. </a>Don't cast between pointer types when the conversion could be implicit; A strict version of [Avoid casts](#Res-casts).
20424 * <a name="Pro-type-downcast"></a>Type.2: Don't use `static_cast` to downcast:
20425 [Use `dynamic_cast` instead](#Rh-dynamic_cast).
20426 * <a name="Pro-type-constcast"></a>Type.3: Don't use `const_cast` to cast away `const` (i.e., at all):
20427 [Don't cast away const](#Res-casts-const).
20428 * <a name="Pro-type-cstylecast"></a>Type.4: Don't use C-style `(T)expression` or functional `T(expression)` casts:
20429 Prefer [construction](#Res-construct) or [named casts](#Res-cast-named).
20430 * <a name="Pro-type-init"></a>Type.5: Don't use a variable before it has been initialized:
20431 [always initialize](#Res-always).
20432 * <a name="Pro-type-memberinit"></a>Type.6: Always initialize a member variable:
20433 [always initialize](#Res-always),
20434 possibly using [default constructors](#Rc-default0) or
20435 [default member initializers](#Rc-in-class-initializers).
20436 * <a name="Pro-type-unon"></a>Type.7: Avoid naked union:
20437 [Use `variant` instead](#Ru-naked).
20438 * <a name="Pro-type-varargs"></a>Type.8: Avoid varargs:
20439 [Don't use `va_arg` arguments](#F-varargs).
20441 ##### Impact
20443 With the type-safety profile you can trust that every operation is applied to a valid object.
20444 Exception may be thrown to indicate errors that cannot be detected statically (at compile time).
20445 Note that this type-safety can be complete only if we also have [Bounds safety](#SS-bounds) and [Lifetime safety](#SS-lifetime).
20446 Without those guarantees, a region of memory could be accessed independent of which object, objects, or parts of objects are stored in it.
20449 ## <a name="SS-bounds"></a>Pro.bounds: Bounds safety profile
20451 This profile makes it easier to construct code that operates within the bounds of allocated blocks of memory.
20452 It does so by focusing on removing the primary sources of bounds violations: pointer arithmetic and array indexing.
20453 One of the core features of this profile is to restrict pointers to only refer to single objects, not arrays.
20455 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.
20456 Bounds safety is intended to be complete only when combined with [Type safety](#SS-type) and [Lifetime safety](#SS-lifetime),
20457 which cover other unsafe operations that allow bounds violations.
20459 Bounds safety profile summary:
20461 * <a name="Pro-bounds-arithmetic"></a>Bounds.1: Don't use pointer arithmetic. Use `span` instead:
20462 [Pass pointers to single objects (only)](#Ri-array) and [Keep pointer arithmetic simple](#Res-ptr).
20463 * <a name="Pro-bounds-arrayindex"></a>Bounds.2: Only index into arrays using constant expressions:
20464 [Pass pointers to single objects (only)](#Ri-array) and [Keep pointer arithmetic simple](#Res-ptr).
20465 * <a name="Pro-bounds-decay"></a>Bounds.3: No array-to-pointer decay:
20466 [Pass pointers to single objects (only)](#Ri-array) and [Keep pointer arithmetic simple](#Res-ptr).
20467 * <a name="Pro-bounds-stdlib"></a>Bounds.4: Don't use standard-library functions and types that are not bounds-checked:
20468 [Use the standard library in a type-safe manner](#Rsl-bounds).
20470 ##### Impact
20472 Bounds safety implies that access to an object - notably arrays - does not access beyond the object's memory allocation.
20473 This eliminates a large class of insidious and hard-to-find errors, including the (in)famous "buffer overflow" errors.
20474 This closes security loopholes as well as a prominent source of memory corruption (when writing out of bounds).
20475 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)
20476 and "mysterious values."
20479 ## <a name="SS-lifetime"></a>Pro.lifetime: Lifetime safety profile
20481 Accessing through a pointer that doesn't point to anything is a major source of errors,
20482 and very hard to avoid in many traditional C or C++ styles of programming.
20483 For example, a pointer may be uninitialized, the `nullptr`, point beyond the range of an array, or to a deleted object.
20485 [See the current design specification here.](https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/Lifetime.pdf)
20487 Lifetime safety profile summary:
20489 * <a name="Pro-lifetime-invalid-deref"></a>Lifetime.1: Don't dereference a possibly invalid pointer:
20490 [detect or avoid](#Res-deref).
20492 ##### Impact
20494 Once completely enforced through a combination of style rules, static analysis, and library support, this profile
20496 * eliminates one of the major sources of nasty errors in C++
20497 * eliminates a major source of potential security violations
20498 * improves performance by eliminating redundant "paranoia" checks
20499 * increases confidence in correctness of code
20500 * avoids undefined behavior by enforcing a key C++ language rule
20503 # <a name="S-gsl"></a>GSL: Guidelines support library
20505 The GSL is a small library of facilities designed to support this set of guidelines.
20506 Without these facilities, the guidelines would have to be far more restrictive on language details.
20508 The Core Guidelines support library is defined in namespace `gsl` and the names may 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.
20510 The GSL is header only, and can be found at [GSL: Guidelines support library](https://github.com/Microsoft/GSL).
20511 The support library facilities are designed to be extremely lightweight (zero-overhead) so that they impose no overhead compared to using conventional alternatives.
20512 Where desirable, they can be "instrumented" with additional functionality (e.g., checks) for tasks such as debugging.
20514 These Guidelines assume a `variant` type, but this is not currently in GSL.
20515 Eventually, use [the one voted into C++17](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0088r3.html).
20517 Summary of GSL components:
20519 * [GSL.view: Views](#SS-views)
20520 * [GSL.owner](#SS-ownership)
20521 * [GSL.assert: Assertions](#SS-assertions)
20522 * [GSL.util: Utilities](#SS-utilities)
20523 * [GSL.concept: Concepts](#SS-gsl-concepts)
20525 We plan for a "ISO C++ standard style" semi-formal specification of the GSL.
20527 We rely on the ISO C++ Standard Library and hope for parts of the GSL to be absorbed into the standard library.
20529 ## <a name="SS-views"></a>GSL.view: Views
20531 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.
20533 These "views" are never owners.
20535 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.
20537 The names are mostly ISO standard-library style (lower case and underscore):
20539 * `T*`      // The `T*` is not an owner, may be null; assumed to be pointing to a single element.
20540 * `T&`      // The `T&` is not an owner and can never be a "null reference"; references are always bound to objects.
20542 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.
20543 Owners should be converted to resource handles (e.g., `unique_ptr` or `vector<T>`) or marked `owner<T*>`.
20545 * `owner<T*>`   // a `T*` that owns the object pointed/referred to; may be `nullptr`.
20547 `owner` is used to mark owning pointers in code that cannot be upgraded to use proper resource handles.
20548 Reasons for that include:
20550 * Cost of conversion.
20551 * The pointer is used with an ABI.
20552 * The pointer is part of the implementation of a resource handle.
20554 An `owner<T>` differs from a resource handle for a `T` by still requiring an explicit `delete`.
20556 An `owner<T>` is assumed to refer to an object on the free store (heap).
20558 If something is not supposed to be `nullptr`, say so:
20560 * `not_null<T>`   // `T` is usually a pointer type (e.g., `not_null<int*>` and `not_null<owner<Foo*>>`) that may not be `nullptr`.
20561   `T` can be any type for which `==nullptr` is meaningful.
20563 * `span<T>`       // `[p:p+n)`, constructor from `{p, q}` and `{p, n}`; `T` is the pointer type
20564 * `span_p<T>`     // `{p, predicate}` `[p:q)` where `q` is the first element for which `predicate(*p)` is true
20565 * `string_span`   // `span<char>`
20566 * `cstring_span`  // `span<const char>`
20568 A `span<T>` refers to zero or more mutable `T`s unless `T` is a `const` type.
20570 "Pointer arithmetic" is best done within `span`s.
20571 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`.
20573 * `zstring`    // a `char*` supposed to be a C-style string; that is, a zero-terminated sequence of `char` or `nullptr`
20574 * `czstring`   // a `const char*` supposed to be a C-style string; that is, a zero-terminated sequence of `const` `char` or `nullptr`
20576 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.
20577 A sequence of characters that is not assumed to be zero-terminated should be a `char*`, rather than a `zstring`.
20578 French accent optional.
20580 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?
20582 ## <a name="SS-ownership"></a>GSL.owner: Ownership pointers
20584 * `unique_ptr<T>`     // unique ownership: `std::unique_ptr<T>`
20585 * `shared_ptr<T>`     // shared ownership: `std::shared_ptr<T>` (a counted pointer)
20586 * `stack_array<T>`    // A stack-allocated array. The number of elements are determined at construction and fixed thereafter. The elements are mutable unless `T` is a `const` type.
20587 * `dyn_array<T>`      // ??? needed ??? A heap-allocated array. The number of elements are determined at construction and fixed thereafter.
20588   The elements are mutable unless `T` is a `const` type. Basically a `span` that allocates and owns its elements.
20590 ## <a name="SS-assertions"></a>GSL.assert: Assertions
20592 * `Expects`     // precondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
20593                 // `Expects(p)` terminates the program unless `p == true`
20594                 // `Expect` in under control of some options (enforcement, error message, alternatives to terminate)
20595 * `Ensures`     // postcondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
20597 These assertions are currently macros (yuck!) and must appear in function definitions (only)
20598 pending standard committee decisions on contracts and assertion syntax.
20599 See [the contract proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf); using the attribute syntax,
20600 for example, `Expects(p)` will become `[[expects: p]]`.
20602 ## <a name="SS-utilities"></a>GSL.util: Utilities
20604 * `finally`        // `finally(f)` makes a `final_action{f}` with a destructor that invokes `f`
20605 * `narrow_cast`    // `narrow_cast<T>(x)` is `static_cast<T>(x)`
20606 * `narrow`         // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
20607 * `[[implicit]]`   // "Marker" to put on single-argument constructors to explicitly make them non-explicit.
20608 * `move_owner`     // `p = move_owner(q)` means `p = q` but ???
20609 * `joining_thread` // a RAII style version of `std::thread` that joins.
20610 * `index`          // a type to use for all container and array indexing (currently an alias for `ptrdiff_t`)
20612 ## <a name="SS-gsl-concepts"></a>GSL.concept: Concepts
20614 These concepts (type predicates) are borrowed from
20615 Andrew Sutton's Origin library,
20616 the Range proposal,
20617 and the ISO WG21 Palo Alto TR.
20618 They are likely to be very similar to what will become part of the ISO C++ standard.
20619 The notation is that of the ISO WG21 [Concepts TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
20620 Most of the concepts below are defined in [the Ranges TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf).
20622 * `Range`
20623 * `String`   // ???
20624 * `Number`   // ???
20625 * `Sortable`
20626 * `EqualityComparable`   // ???Must we suffer CaMelcAse???
20627 * `Convertible`
20628 * `Common`
20629 * `Boolean`
20630 * `Integral`
20631 * `SignedIntegral`
20632 * `SemiRegular` // ??? Copyable?
20633 * `Regular`
20634 * `TotallyOrdered`
20635 * `Function`
20636 * `RegularFunction`
20637 * `Predicate`
20638 * `Relation`
20639 * ...
20641 ### <a name="SS-gsl-smartptrconcepts"></a>GSL.ptr: Smart pointer concepts
20643 * `Pointer`  // A type with `*`, `->`, `==`, and default construction (default construction is assumed to set the singular "null" value)
20644 * `Unique_ptr`  // A type that matches `Pointer`, is movable, and is not copyable
20645 * `Shared_ptr`   // A type that matches `Pointer`, and is copyable
20647 # <a name="S-naming"></a>NL: Naming and layout rules
20649 Consistent naming and layout are helpful.
20650 If for no other reason because it minimizes "my style is better than your style" arguments.
20651 However, there are many, many, different styles around and people are passionate about them (pro and con).
20652 Also, most real-world projects includes code from many sources, so standardizing on a single style for all code is often impossible.
20653 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.
20654 IDEs and tools can help (as well as hinder).
20656 Naming and layout rules:
20658 * [NL.1: Don't say in comments what can be clearly stated in code](#Rl-comments)
20659 * [NL.2: State intent in comments](#Rl-comments-intent)
20660 * [NL.3: Keep comments crisp](#Rl-comments-crisp)
20661 * [NL.4: Maintain a consistent indentation style](#Rl-indent)
20662 * [NL.5: Avoid encoding type information in names](#Rl-name-type)
20663 * [NL.7: Make the length of a name roughly proportional to the length of its scope](#Rl-name-length)
20664 * [NL.8: Use a consistent naming style](#Rl-name)
20665 * [NL.9: Use `ALL_CAPS` for macro names only](#Rl-all-caps)
20666 * [NL.10: Prefer `underscore_style` names](#Rl-camel)
20667 * [NL.11: Make literals readable](#Rl-literals)
20668 * [NL.15: Use spaces sparingly](#Rl-space)
20669 * [NL.16: Use a conventional class member declaration order](#Rl-order)
20670 * [NL.17: Use K&R-derived layout](#Rl-knr)
20671 * [NL.18: Use C++-style declarator layout](#Rl-ptr)
20672 * [NL.19: Avoid names that are easily misread](#Rl-misread)
20673 * [NL.20: Don't place two statements on the same line](#Rl-stmt)
20674 * [NL.21: Declare one name (only) per declaration](#Rl-dcl)
20675 * [NL.25: Don't use `void` as an argument type](#Rl-void)
20676 * [NL.26: Use conventional `const` notation](#Rl-const)
20678 Most of these rules are aesthetic and programmers hold strong opinions.
20679 IDEs also tend to have defaults and a range of alternatives.
20680 These rules are suggested defaults to follow unless you have reasons not to.
20682 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.
20683 We are not "legislating" (see the previous paragraph).
20684 However, we have had many requests for a set of naming and layout conventions to use when there are no external constraints.
20686 More specific and detailed rules are easier to enforce.
20688 These rules bear a strong resemblance to the recommendations in the [PPP Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
20689 written in support of Stroustrup's [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
20691 ### <a name="Rl-comments"></a>NL.1: Don't say in comments what can be clearly stated in code
20693 ##### Reason
20695 Compilers do not read comments.
20696 Comments are less precise than code.
20697 Comments are not updated as consistently as code.
20699 ##### Example, bad
20701     auto x = m * v1 + vv;   // multiply m with v1 and add the result to vv
20703 ##### Enforcement
20705 Build an AI program that interprets colloquial English text and see if what is said could be better expressed in C++.
20707 ### <a name="Rl-comments-intent"></a>NL.2: State intent in comments
20709 ##### Reason
20711 Code says what is done, not what is supposed to be done. Often intent can be stated more clearly and concisely than the implementation.
20713 ##### Example
20715     void stable_sort(Sortable& c)
20716         // sort c in the order determined by <, keep equal elements (as defined by ==) in
20717         // their original relative order
20718     {
20719         // ... quite a few lines of non-trivial code ...
20720     }
20722 ##### Note
20724 If the comment and the code disagree, both are likely to be wrong.
20726 ### <a name="Rl-comments-crisp"></a>NL.3: Keep comments crisp
20728 ##### Reason
20730 Verbosity slows down understanding and makes the code harder to read by spreading it around in the source file.
20732 ##### Note
20734 Use intelligible English.
20735 I may be fluent in Danish, but most programmers are not; the maintainers of my code may not be.
20736 Avoid SMS lingo and watch your grammar, punctuation, and capitalization.
20737 Aim for professionalism, not "cool."
20739 ##### Enforcement
20741 not possible.
20743 ### <a name="Rl-indent"></a>NL.4: Maintain a consistent indentation style
20745 ##### Reason
20747 Readability. Avoidance of "silly mistakes."
20749 ##### Example, bad
20751     int i;
20752     for (i = 0; i < max; ++i); // bug waiting to happen
20753     if (i == j)
20754         return i;
20756 ##### Note
20758 Always indenting the statement after `if (...)`, `for (...)`, and `while (...)` is usually a good idea:
20760     if (i < 0) error("negative argument");
20762     if (i < 0)
20763         error("negative argument");
20765 ##### Enforcement
20767 Use a tool.
20769 ### <a name="Rl-name-type"></a>NL.5: Avoid encoding type information in names
20771 ##### Rationale
20773 If names reflect types rather than functionality, it becomes hard to change the types used to provide that functionality.
20774 Also, if the type of a variable is changed, code using it will have to be modified.
20775 Minimize unintentional conversions.
20777 ##### Example, bad
20779     void print_int(int i);
20780     void print_string(const char*);
20782     print_int(1);          // repetitive, manual type matching
20783     print_string("xyzzy"); // repetitive, manual type matching
20785 ##### Example, good
20787     void print(int i);
20788     void print(string_view);    // also works on any string-like sequence
20790     print(1);              // clear, automatic type matching
20791     print("xyzzy");        // clear, automatic type matching
20793 ##### Note
20795 Names with types encoded are either verbose or cryptic.
20797     printS  // print a std::string
20798     prints  // print a C-style string
20799     printi  // print an int
20801 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).
20803 ##### Note
20805 Some styles use very general (not type-specific) prefixes to denote the general use of a variable.
20807     auto p = new User();
20808     auto p = make_unique<User>();
20809     // note: "p" is not being used to say "raw pointer to type User,"
20810     //       just generally to say "this is an indirection"
20812     auto cntHits = calc_total_of_hits(/*...*/);
20813     // note: "cnt" is not being used to encode a type,
20814     //       just generally to say "this is a count of something"
20816 This is not harmful and does not fall under this guideline because it does not encode type information.
20818 ##### Note
20820 Some styles distinguish members from local variable, and/or from global variable.
20822     struct S {
20823         int m_;
20824         S(int m) :m_{abs(m)} { }
20825     };
20827 This is not harmful and does not fall under this guideline because it does not encode type information.
20829 ##### Note
20831 Like C++, some styles distinguish types from non-types.
20832 For example, by capitalizing type names, but not the names of functions and variables.
20834     typename<typename T>
20835     class HashTable {   // maps string to T
20836         // ...
20837     };
20839     HashTable<int> index;
20841 This is not harmful and does not fall under this guideline because it does not encode type information.
20843 ### <a name="Rl-name-length"></a>NL.7: Make the length of a name roughly proportional to the length of its scope
20845 **Rationale**: The larger the scope the greater the chance of confusion and of an unintended name clash.
20847 ##### Example
20849     double sqrt(double x);   // return the square root of x; x must be non-negative
20851     int length(const char* p);  // return the number of characters in a zero-terminated C-style string
20853     int length_of_string(const char zero_terminated_array_of_char[])    // bad: verbose
20855     int g;      // bad: global variable with a cryptic name
20857     int open;   // bad: global variable with a short, popular name
20859 The use of `p` for pointer and `x` for a floating-point variable is conventional and non-confusing in a restricted scope.
20861 ##### Enforcement
20865 ### <a name="Rl-name"></a>NL.8: Use a consistent naming style
20867 **Rationale**: Consistence in naming and naming style increases readability.
20869 ##### Note
20871 There are many styles and when you use multiple libraries, you can't follow all their different conventions.
20872 Choose a "house style", but leave "imported" libraries with their original style.
20874 ##### Example
20876 ISO Standard, use lower case only and digits, separate words with underscores:
20878 * `int`
20879 * `vector`
20880 * `my_map`
20882 Avoid double underscores `__`.
20884 ##### Example
20886 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
20887 ISO Standard, but with upper case used for your own types and concepts:
20889 * `int`
20890 * `vector`
20891 * `My_map`
20893 ##### Example
20895 CamelCase: capitalize each word in a multi-word identifier:
20897 * `int`
20898 * `vector`
20899 * `MyMap`
20900 * `myMap`
20902 Some conventions capitalize the first letter, some don't.
20904 ##### Note
20906 Try to be consistent in your use of acronyms and lengths of identifiers:
20908     int mtbf {12};
20909     int mean_time_between_failures {12}; // make up your mind
20911 ##### Enforcement
20913 Would be possible except for the use of libraries with varying conventions.
20915 ### <a name="Rl-all-caps"></a>NL.9: Use `ALL_CAPS` for macro names only
20917 ##### Reason
20919 To avoid confusing macros with names that obey scope and type rules.
20921 ##### Example
20923     void f()
20924     {
20925         const int SIZE{1000};  // Bad, use 'size' instead
20926         int v[SIZE];
20927     }
20929 ##### Note
20931 This rule applies to non-macro symbolic constants:
20933     enum bad { BAD, WORSE, HORRIBLE }; // BAD
20935 ##### Enforcement
20937 * Flag macros with lower-case letters
20938 * Flag `ALL_CAPS` non-macro names
20940 ### <a name="Rl-camel"></a>NL.10: Prefer `underscore_style` names
20942 ##### Reason
20944 The use of underscores to separate parts of a name is the original C and C++ style and used in the C++ Standard Library.
20946 ##### Note
20948 This rule is a default to use only if you have a choice.
20949 Often, you don't have a choice and must follow an established style for [consistency](#Rl-name).
20950 The need for consistency beats personal taste.
20952 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
20953 This rule was added after many requests for guidance.
20955 ##### Example
20957 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
20958 ISO Standard, but with upper case used for your own types and concepts:
20960 * `int`
20961 * `vector`
20962 * `My_map`
20964 ##### Enforcement
20966 Impossible.
20968 ### <a name="Rl-space"></a>NL.15: Use spaces sparingly
20970 ##### Reason
20972 Too much space makes the text larger and distracts.
20974 ##### Example, bad
20976     #include < map >
20978     int main(int argc, char * argv [ ])
20979     {
20980         // ...
20981     }
20983 ##### Example
20985     #include <map>
20987     int main(int argc, char* argv[])
20988     {
20989         // ...
20990     }
20992 ##### Note
20994 Some IDEs have their own opinions and add distracting space.
20996 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
20997 This rule was added after many requests for guidance.
20999 ##### Note
21001 We value well-placed whitespace as a significant help for readability. Just don't overdo it.
21003 ### <a name="Rl-literals"></a>NL.11: Make literals readable
21005 ##### Reason
21007 Readability.
21009 ##### Example
21011 Use digit separators to avoid long strings of digits
21013     auto c = 299'792'458; // m/s2
21014     auto q2 = 0b0000'1111'0000'0000;
21015     auto ss_number = 123'456'7890;
21017 ##### Example
21019 Use literal suffixes where clarification is needed
21021     auto hello = "Hello!"s; // a std::string
21022     auto world = "world";   // a C-style string
21023     auto interval = 100ms;  // using <chrono>
21025 ##### Note
21027 Literals should not be sprinkled all over the code as ["magic constants"](#Res-magic),
21028 but it is still a good idea to make them readable where they are defined.
21029 It is easy to make a typo in a long string of integers.
21031 ##### Enforcement
21033 Flag long digit sequences. The trouble is to define "long"; maybe 7.
21035 ### <a name="Rl-order"></a>NL.16: Use a conventional class member declaration order
21037 ##### Reason
21039 A conventional order of members improves readability.
21041 When declaring a class use the following order
21043 * types: classes, enums, and aliases (`using`)
21044 * constructors, assignments, destructor
21045 * functions
21046 * data
21048 Use the `public` before `protected` before `private` order.
21050 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21051 This rule was added after many requests for guidance.
21053 ##### Example
21055     class X {
21056     public:
21057         // interface
21058     protected:
21059         // unchecked function for use by derived class implementations
21060     private:
21061         // implementation details
21062     };
21064 ##### Example
21066 Sometimes, the default order of members conflicts with a desire to separate the public interface from implementation details.
21067 In such cases, private types and functions can be placed with private data.
21069     class X {
21070     public:
21071         // interface
21072     protected:
21073         // unchecked function for use by derived class implementations
21074     private:
21075         // implementation details (types, functions, and data)
21076     };
21078 ##### Example, bad
21080 Avoid multiple blocks of declarations of one access (e.g., `public`) dispersed among blocks of declarations with different access (e.g. `private`).
21082     class X {   // bad
21083     public:
21084         void f();
21085     public:
21086         int g();
21087         // ...
21088     };
21090 The use of macros to declare groups of members often leads to violation of any ordering rules.
21091 However, macros obscures what is being expressed anyway.
21093 ##### Enforcement
21095 Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule.
21097 ### <a name="Rl-knr"></a>NL.17: Use K&R-derived layout
21099 ##### Reason
21101 This is the original C and C++ layout. It preserves vertical space well. It distinguishes different language constructs (such as functions and classes) well.
21103 ##### Note
21105 In the context of C++, this style is often called "Stroustrup".
21107 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21108 This rule was added after many requests for guidance.
21110 ##### Example
21112     struct Cable {
21113         int x;
21114         // ...
21115     };
21117     double foo(int x)
21118     {
21119         if (0 < x) {
21120             // ...
21121         }
21123         switch (x) {
21124         case 0:
21125             // ...
21126             break;
21127         case amazing:
21128             // ...
21129             break;
21130         default:
21131             // ...
21132             break;
21133         }
21135         if (0 < x)
21136             ++x;
21138         if (x < 0)
21139             something();
21140         else
21141             something_else();
21143         return some_value;
21144     }
21146 Note the space between `if` and `(`
21148 ##### Note
21150 Use separate lines for each statement, the branches of an `if`, and the body of a `for`.
21152 ##### Note
21154 The `{` for a `class` and a `struct` is *not* on a separate line, but the `{` for a function is.
21156 ##### Note
21158 Capitalize the names of your user-defined types to distinguish them from standards-library types.
21160 ##### Note
21162 Do not capitalize function names.
21164 ##### Enforcement
21166 If you want enforcement, use an IDE to reformat.
21168 ### <a name="Rl-ptr"></a>NL.18: Use C++-style declarator layout
21170 ##### Reason
21172 The C-style layout emphasizes use in expressions and grammar, whereas the C++-style emphasizes types.
21173 The use in expressions argument doesn't hold for references.
21175 ##### Example
21177     T& operator[](size_t);   // OK
21178     T &operator[](size_t);   // just strange
21179     T & operator[](size_t);   // undecided
21181 ##### Note
21183 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21184 This rule was added after many requests for guidance.
21186 ##### Enforcement
21188 Impossible in the face of history.
21191 ### <a name="Rl-misread"></a>NL.19: Avoid names that are easily misread
21193 ##### Reason
21195 Readability.
21196 Not everyone has screens and printers that make it easy to distinguish all characters.
21197 We easily confuse similarly spelled and slightly misspelled words.
21199 ##### Example
21201     int oO01lL = 6; // bad
21203     int splunk = 7;
21204     int splonk = 8; // bad: splunk and splonk are easily confused
21206 ##### Enforcement
21210 ### <a name="Rl-stmt"></a>NL.20: Don't place two statements on the same line
21212 ##### Reason
21214 Readability.
21215 It is really easy to overlook a statement when there is more on a line.
21217 ##### Example
21219     int x = 7; char* p = 29;    // don't
21220     int x = 7; f(x);  ++x;      // don't
21222 ##### Enforcement
21224 Easy.
21226 ### <a name="Rl-dcl"></a>NL.21: Declare one name (only) per declaration
21228 ##### Reason
21230 Readability.
21231 Minimizing confusion with the declarator syntax.
21233 ##### Note
21235 For details, see [ES.10](#Res-name-one).
21238 ### <a name="Rl-void"></a>NL.25: Don't use `void` as an argument type
21240 ##### Reason
21242 It's verbose and only needed where C compatibility matters.
21244 ##### Example
21246     void f(void);   // bad
21248     void g();       // better
21250 ##### Note
21252 Even Dennis Ritchie deemed `void f(void)` an abomination.
21253 You can make an argument for that abomination in C when function prototypes were rare so that banning:
21255     int f();
21256     f(1, 2, "weird but valid C89");   // hope that f() is defined int f(a, b, c) char* c; { /* ... */ }
21258 would have caused major problems, but not in the 21st century and in C++.
21260 ### <a name="Rl-const"></a>NL.26: Use conventional `const` notation
21262 ##### Reason
21264 Conventional notation is more familiar to more programmers.
21265 Consistency in large code bases.
21267 ##### Example
21269     const int x = 7;    // OK
21270     int const y = 9;    // bad
21272     const int *const p = nullptr;   // OK, constant pointer to constant int
21273     int const *const p = nullptr;   // bad, constant pointer to constant int
21275 ##### Note
21277 We are well aware that you could claim the "bad" examples more logical than the ones marked "OK",
21278 but they also confuse more people, especially novices relying on teaching material using the far more common, conventional OK style.
21280 As ever, remember that the aim of these naming and layout rules is consistency and that aesthetics vary immensely.
21282 This is a recommendation for [when you have no constraints or better ideas](#S-naming).
21283 This rule was added after many requests for guidance.
21285 ##### Enforcement
21287 Flag `const` used as a suffix for a type.
21289 # <a name="S-faq"></a>FAQ: Answers to frequently asked questions
21291 This section covers answers to frequently asked questions about these guidelines.
21293 ### <a name="Faq-aims"></a>FAQ.1: What do these guidelines aim to achieve?
21295 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 (as of this writing, C++14). 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.
21297 ### <a name="Faq-announced"></a>FAQ.2: When and where was this work first announced?
21299 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).
21301 ### <a name="Faq-maintainers"></a>FAQ.3: Who are the authors and maintainers of these guidelines?
21303 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!"
21305 ### <a name="Faq-contribute"></a>FAQ.4: How can I contribute?
21307 See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help!
21309 ### <a name="Faq-maintainer"></a>FAQ.5: How can I become an editor/maintainer?
21311 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!
21313 ### <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?
21315 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.
21317 ### <a name="Faq-isocpp"></a>FAQ.7: If these guidelines are not approved by the committee, why are they under `github.com/isocpp`?
21319 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.
21321 ### <a name="Faq-cpp98"></a>FAQ.8: Will there be a C++98 version of these Guidelines? a C++11 version?
21323 No. These guidelines are about how to best use Standard C++14 (and, if you have an implementation available, the Concepts Technical Specification) and write code assuming you have a modern conforming compiler.
21325 ### <a name="Faq-language-extensions"></a>FAQ.9: Do these guidelines propose new language features?
21327 No. These guidelines are about how to best use Standard C++14 + the Concepts Technical Specification, and they limit themselves to recommending only those features.
21329 ### <a name="Faq-markdown"></a>FAQ.10: What version of Markdown do these guidelines use?
21331 These coding standards are written using [CommonMark](http://commonmark.org), and `<a>` HTML anchors.
21333 We are considering the following extensions from [GitHub Flavored Markdown (GFM)](https://help.github.com/articles/github-flavored-markdown/):
21335 * fenced code blocks (consistently using indented vs. fenced is under discussion)
21336 * tables (none yet but we'll likely need them, and this is a GFM extension)
21338 Avoid other HTML tags and other extensions.
21340 Note: We are not yet consistent with this style.
21342 ### <a name="Faq-gsl"></a>FAQ.50: What is the GSL (guidelines support library)?
21344 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.
21346 ### <a name="Faq-msgsl"></a>FAQ.51: Is [github.com/Microsoft/GSL](https://github.com/Microsoft/GSL) the GSL?
21348 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.
21350 ### <a name="Faq-gsl-implementation"></a>FAQ.52: Why not supply an actual GSL implementation in/with these guidelines?
21352 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.
21354 ### <a name="Faq-boost"></a>FAQ.53: Why weren't the GSL types proposed through Boost?
21356 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.
21358 ### <a name="Faq-gsl-iso"></a>FAQ.54: Has the GSL (guidelines support library) been approved by the ISO C++ standards committee?
21360 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.
21362 ### <a name="Faq-gsl-string-view"></a>FAQ.55: If you're using the standard types where available, why is the GSL `string_span` 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`?
21364 The consensus on the taxonomy of views for the C++ Standard Library was that "view" means "read-only", and "span" means "read/write". The read-only `string_view` was the first such component to complete the standardization process, while `span` and `string_span` are currently being considered for standardization.
21366 ### <a name="Faq-gsl-owner"></a>FAQ.56: Is `owner` the same as the proposed `observer_ptr`?
21368 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.
21370 ### <a name="Faq-gsl-stack-array"></a>FAQ.57: Is `stack_array` the same as the standard `array`?
21372 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.
21374 ### <a name="Faq-gsl-dyn-array"></a>FAQ.58: Is `dyn_array` the same as `vector` or the proposed `dynarray`?
21376 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.
21378 ### <a name="Faq-gsl-expects"></a>FAQ.59: Is `Expects` the same as `assert`?
21380 No. It is a placeholder for language support for contract preconditions.
21382 ### <a name="Faq-gsl-ensures"></a>FAQ.60: Is `Ensures` the same as `assert`?
21384 No. It is a placeholder for language support for contract postconditions.
21386 # <a name="S-libraries"></a>Appendix A: Libraries
21388 This section lists recommended libraries, and explicitly recommends a few.
21390 ??? Suitable for the general guide? I think not ???
21392 # <a name="S-modernizing"></a>Appendix B: Modernizing code
21394 Ideally, we follow all rules in all code.
21395 Realistically, we have to deal with a lot of old code:
21397 * application code written before the guidelines were formulated or known
21398 * libraries written to older/different standards
21399 * code written under "unusual" constraints
21400 * code that we just haven't gotten around to modernizing
21402 If we have a million lines of new code, the idea of "just changing it all at once" is typically unrealistic.
21403 Thus, we need a way of gradually modernizing a code base.
21405 Upgrading older code to modern style can be a daunting task.
21406 Often, the old code is both a mess (hard to understand) and working correctly (for the current range of uses).
21407 Typically, the original programmer is not around and the test cases incomplete.
21408 The fact that the code is a mess dramatically increases the effort needed to make any change and the risk of introducing errors.
21409 Often, messy old code runs unnecessarily slowly because it requires outdated compilers and cannot take advantage of modern hardware.
21410 In many cases, automated "modernizer"-style tool support would be required for major upgrade efforts.
21412 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.
21413 Making code "look pretty" or "follow modern style" are not by themselves reasons for change.
21414 There are risks implied by every change and costs (including the cost of lost opportunities) implied by having an outdated code base.
21415 The cost reductions must outweigh the risks.
21417 But how?
21419 There is no one approach to modernizing code.
21420 How best to do it depends on the code, the pressure for updates, the backgrounds of the developers, and the available tool.
21421 Here are some (very general) ideas:
21423 * The ideal is "just upgrade everything." That gives the most benefits for the shortest total time.
21424   In most circumstances, it is also impossible.
21425 * 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.
21426 * 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.
21427 * We could start by focusing on the interfaces, e.g., make sure that no resources are lost and no pointer is misused.
21428   This would be a set of changes across the whole code base, but would most likely have huge benefits.
21429   Afterwards, code hidden behind those interfaces can be gradually modernized without affecting other code.
21431 Whichever way you choose, please note that the most advantages come with the highest conformance to the guidelines.
21432 The guidelines are not a random set of unrelated rules where you can randomly pick and choose with an expectation of success.
21434 We would dearly love to hear about experience and about tools used.
21435 Modernization can be much faster, simpler, and safer when supported with analysis tools and even code transformation tools.
21437 # <a name="S-discussion"></a>Appendix C: Discussion
21439 This section contains follow-up material on rules and sets of rules.
21440 In particular, here we present further rationale, longer examples, and discussions of alternatives.
21442 ### <a name="Sd-order"></a>Discussion: Define and initialize member variables in the order of member declaration
21444 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.
21446     class Employee {
21447         string email, first, last;
21448     public:
21449         Employee(const char* firstName, const char* lastName);
21450         // ...
21451     };
21453     Employee::Employee(const char* firstName, const char* lastName)
21454       : first(firstName),
21455         last(lastName),
21456         // BAD: first and last not yet constructed
21457         email(first + "." + last + "@acme.com")
21458     {}
21460 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.
21462 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.
21464 **References**:
21466 [\[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
21468 ### <a name="Sd-init"></a>Discussion: Use of `=`, `{}`, and `()` as initializers
21472 ### <a name="Sd-factory"></a>Discussion: Use a factory function if you need "virtual behavior" during initialization
21474 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:
21476 * *Pass the buck:* Just document that user code must call the post-initialization function right after constructing an object.
21477 * *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.
21478 * *Use virtual base class semantics:* Language rules dictate that the constructor most-derived class decides which base constructor will be invoked; you can use that to your advantage. (See [\[Taligent94\]](#Taligent94).)
21479 * *Use a factory function:* This way, you can easily force a mandatory invocation of a post-constructor function.
21481 Here is an example of the last option:
21483     class B {
21484     public:
21485         B() { /* ... */ f(); /* ... */ }   // BAD: see Item 49.1
21487         virtual void f() = 0;
21489         // ...
21490     };
21492     class B {
21493     protected:
21494         B() { /* ... */ }
21495         virtual void post_initialize()    // called right after construction
21496             { /* ... */ f(); /* ... */ }   // GOOD: virtual dispatch is safe
21497     public:
21498         virtual void f() = 0;
21500         template<class T>
21501         static shared_ptr<T> create()    // interface for creating objects
21502         {
21503             auto p = make_shared<T>();
21504             p->post_initialize();
21505             return p;
21506         }
21507     };
21510     class D : public B {                 // some derived class
21511     public:
21512         void f() override { /* ...  */ };
21514     protected:
21515         D() {}
21517         template<class T>
21518         friend shared_ptr<T> B::Create();
21519     };
21521     shared_ptr<D> p = D::Create<D>();    // creating a D object
21523 This design requires the following discipline:
21525 * Derived classes such as `D` must not expose a public constructor. Otherwise, `D`'s users could create `D` objects that don't invoke `PostInitialize`.
21526 * Allocation is limited to `operator new`. `B` can, however, override `new` (see Items 45 and 46).
21527 * `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.
21529 If the requirements above are met, the design guarantees that `PostInitialize` has been called for any fully constructed `B`-derived object. `PostInitialize` doesn't need to be virtual; it can, however, invoke virtual functions freely.
21531 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).
21533 **References**: [\[Alexandrescu01\]](#Alexandrescu01) §3, [\[Boost\]](#Boost), [\[Dewhurst03\]](#Dewhurst03) §75, [\[Meyers97\]](#Meyers97) §46, [\[Stroustrup00\]](#Stroustrup00) §15.4.3, [\[Taligent94\]](#Taligent94)
21535 ### <a name="Sd-dtor"></a>Discussion: Make base class destructors public and virtual, or protected and nonvirtual
21537 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 nonvirtual since it doesn't need to behave virtually.
21539 ##### Example
21541 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>`:
21543     class Base {
21544     public:
21545         ~Base();                   // BAD, not virtual
21546         virtual ~Base();           // GOOD
21547         // ...
21548     };
21550     class Derived : public Base { /* ... */ };
21552     {
21553         unique_ptr<Base> pb = make_unique<Derived>();
21554         // ...
21555     } // ~pb invokes correct destructor only when ~Base is virtual
21557 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 nonvirtual:
21559     class My_policy {
21560     public:
21561         virtual ~My_policy();      // BAD, public and virtual
21562     protected:
21563         ~My_policy();              // GOOD
21564         // ...
21565     };
21567     template<class Policy>
21568     class customizable : Policy { /* ... */ }; // note: private inheritance
21570 ##### Note
21572 This simple guideline illustrates a subtle issue and reflects modern uses of inheritance and object-oriented design principles.
21574 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 nonvirtual (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.
21576 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:
21578 * Whether it should behave virtually or not.
21579 * Whether it should be publicly available to all callers using a pointer to `Base` or else be a hidden internal implementation detail.
21581 As described in Item 39, for a normal member function, the choice is between allowing it to be called via a pointer to `Base` nonvirtually (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.
21583 Destruction can be viewed as just another operation, albeit with special semantics that make nonvirtual 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; "nonvirtually" is not an option. Hence, a base class destructor is virtual if it can be called (i.e., is public), and nonvirtual otherwise.
21585 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.)
21587 Corollary: When writing a base class, always write a destructor explicitly, because the implicitly generated one is public and nonvirtual. 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.
21589 ##### Exception
21591 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.
21593 Consider also this rare case:
21595 * `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.
21596 * 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.
21598 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.
21600 In this rare case, you could make the destructor public and nonvirtual but clearly document that further-derived objects must not be used polymorphically as `B`'s. This is what was done with `std::unary_function`.
21602 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 nonvirtual destructor.
21604 **References**: [\[C++CS\]](#CplusplusCS) 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
21606 ### <a name="Sd-noexcept"></a>Discussion: Usage of noexcept
21610 ### <a name="Sd-never-fail"></a>Discussion: Destructors, deallocation, and swap must never fail
21612 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 may throw an exception are flatly forbidden from use with the C++ Standard Library. Most destructors are now implicitly `noexcept` by default.
21614 ##### Example
21616     class Nefarious {
21617     public:
21618         Nefarious()  { /* code that could throw */ }   // ok
21619         ~Nefarious() { /* code that could throw */ }   // BAD, should not throw
21620         // ...
21621     };
21623 1. `Nefarious` objects are hard to use safely even as local variables:
21626         void test(string& s)
21627         {
21628             Nefarious n;          // trouble brewing
21629             string copy = s;      // copy the string
21630         } // destroy copy and then n
21632     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.
21634 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 poor behavior:
21637         class Innocent_bystander {
21638             Nefarious member;     // oops, poisons the enclosing class's destructor
21639             // ...
21640         };
21642         void test(string& s)
21643         {
21644             Innocent_bystander i; // more trouble brewing
21645             string copy2 = s;      // copy the string
21646         } // destroy copy and then i
21648     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`.
21650 3. You can't reliably create global or static `Nefarious` objects either:
21653         static Nefarious n;       // oops, any destructor exception can't be caught
21655 4. You can't reliably create arrays of `Nefarious`:
21658         void test()
21659         {
21660             std::array<Nefarious, 10> arr; // this line can std::terminate(!)
21661         }
21663     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.
21665 5. You can't use `Nefarious` objects in standard containers:
21668         std::vector<Nefarious> vec(10);   // this line can std::terminate()
21670     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.
21672 ##### Note
21674 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.
21676 Consider the following advice and requirements found in the C++ Standard:
21678 > 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)
21680 > 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)
21682 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.
21683 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`:
21685     T& T::operator=(const T& other) {
21686         auto temp = other;
21687         swap(temp);
21688         return *this;
21689     }
21691 (See also Item 56. ???)
21693 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).
21695 When using exceptions as your error handling mechanism, always document this behavior by declaring these functions `noexcept`. (See Item 75.)
21697 **References**: [\[C++CS\]](#CplusplusCS) 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
21699 ## <a name="Sd-consistent"></a>Define Copy, move, and destroy consistently
21701 ##### Reason
21703  ???
21705 ##### Note
21707 If you define a copy constructor, you must also define a copy assignment operator.
21709 ##### Note
21711 If you define a move constructor, you must also define a move assignment operator.
21713 ##### Example
21715     class X {
21716         // ...
21717     public:
21718         X(const X&) { /* stuff */ }
21720         // BAD: failed to also define a copy assignment operator
21722         X(x&&) noexcept { /* stuff */ }
21724         // BAD: failed to also define a move assignment operator
21725     };
21727     X x1;
21728     X x2 = x1; // ok
21729     x2 = x1;   // pitfall: either fails to compile, or does something suspicious
21731 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.
21733     class X {
21734         HANDLE hnd;
21735         // ...
21736     public:
21737         ~X() { /* custom stuff, such as closing hnd */ }
21738         // suspicious: no mention of copying or moving -- what happens to hnd?
21739     };
21741     X x1;
21742     X x2 = x1; // pitfall: either fails to compile, or does something suspicious
21743     x2 = x1;   // pitfall: either fails to compile, or does something suspicious
21745 If you define copying, and any base or member has a type that defines a move operation, you should also define a move operation.
21747     class X {
21748         string s; // defines more efficient move operations
21749         // ... other data members ...
21750     public:
21751         X(const X&) { /* stuff */ }
21752         X& operator=(const X&) { /* stuff */ }
21754         // BAD: failed to also define a move construction and move assignment
21755         // (why wasn't the custom "stuff" repeated here?)
21756     };
21758     X test()
21759     {
21760         X local;
21761         // ...
21762         return local;  // pitfall: will be inefficient and/or do the wrong thing
21763     }
21765 If you define any of the copy constructor, copy assignment operator, or destructor, you probably should define the others.
21767 ##### Note
21769 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:
21771 * 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.)
21772 * 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.
21773 * 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.
21775 In many cases, holding properly encapsulated resources using RAII "owning" objects can eliminate the need to write these operations yourself. (See Item 13.)
21777 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.
21779 **Exceptions**: When any of the special functions are declared only to make them nonpublic or virtual, but without special semantics, it doesn't imply that the others are needed.
21780 In rare cases, classes that have members of strange types (such as reference members) are an exception because they have peculiar copy semantics.
21781 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.)
21783 **References**: [\[C++CS\]](#CplusplusCS) Item 52; [\[Cline99\]](#Cline99) §30.01-14, [\[Koenig97\]](#Koenig97) §4, [\[Stroustrup00\]](#Stroustrup00) §5.5, §10.4, [\[SuttHysl04b\]](#SuttHysl04b)
21785 Resource management rule summary:
21787 * [Provide strong resource safety; that is, never leak anything that you think of as a resource](#Cr-safety)
21788 * [Never throw while holding a resource not owned by a handle](#Cr-never)
21789 * [A "raw" pointer or reference is never a resource handle](#Cr-raw)
21790 * [Never let a pointer outlive the object it points to](#Cr-outlive)
21791 * [Use templates to express containers (and other resource handles)](#Cr-templates)
21792 * [Return containers by value (relying on move or copy elision for efficiency)](#Cr-value-return)
21793 * [If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations](#Cr-handle)
21794 * [If a class is a container, give it an initializer-list constructor](#Cr-list)
21796 ### <a name="Cr-safety"></a>Discussion: Provide strong resource safety; that is, never leak anything that you think of as a resource
21798 ##### Reason
21800 Prevent leaks. Leaks can lead to performance degradation, mysterious error, system crashes, and security violations.
21802 **Alternative formulation**: Have every resource represented as an object of some class managing its lifetime.
21804 ##### Example
21806     template<class T>
21807     class Vector {
21808     // ...
21809     private:
21810         T* elem;   // sz elements on the free store, owned by the class object
21811         int sz;
21812     };
21814 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.).
21816 ##### Example
21818     ??? "odd" non-memory resource ???
21820 ##### Enforcement
21822 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.
21824 ### <a name="Cr-never"></a>Discussion: Never throw while holding a resource not owned by a handle
21826 ##### Reason
21828 That would be a leak.
21830 ##### Example
21832     void f(int i)
21833     {
21834         FILE* f = fopen("a file", "r");
21835         ifstream is { "another file" };
21836         // ...
21837         if (i == 0) return;
21838         // ...
21839         fclose(f);
21840     }
21842 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:
21844     void f(int i)
21845     {
21846         unique_ptr<FILE, int(*)(FILE*)> f(fopen("a file", "r"), fclose);
21847         // ...
21848         if (i == 0) return;
21849         // ...
21850     }
21852 Better:
21854     void f(int i)
21855     {
21856         ifstream input {"a file"};
21857         // ...
21858         if (i == 0) return;
21859         // ...
21860     }
21862 ##### Enforcement
21864 A checker must consider all "naked pointers" suspicious.
21865 A checker probably must rely on a human-provided list of resources.
21866 For starters, we know about the standard-library containers, `string`, and smart pointers.
21867 The use of `span` and `string_span` should help a lot (they are not resource handles).
21869 ### <a name="Cr-raw"></a>Discussion: A "raw" pointer or reference is never a resource handle
21871 ##### Reason
21873 To be able to distinguish owners from views.
21875 ##### Note
21877 This is independent of how you "spell" pointer: `T*`, `T&`, `Ptr<T>` and `Range<T>` are not owners.
21879 ### <a name="Cr-outlive"></a>Discussion: Never let a pointer outlive the object it points to
21881 ##### Reason
21883 To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system.
21885 ##### Example
21887     string* bad()   // really bad
21888     {
21889         vector<string> v = { "This", "will", "cause", "trouble", "!" };
21890         // leaking a pointer into a destroyed member of a destroyed object (v)
21891         return &v[0];
21892     }
21894     void use()
21895     {
21896         string* p = bad();
21897         vector<int> xx = {7, 8, 9};
21898         // undefined behavior: x may not be the string "This"
21899         string x = *p;
21900         // undefined behavior: we don't know what (if anything) is allocated a location p
21901         *p = "Evil!";
21902     }
21904 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`) may have been reallocated by the time `*p` is executed. There may be no `string` to read and a write through `p` could easily corrupt objects of unrelated types.
21906 ##### Enforcement
21908 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.
21910 ### <a name="Cr-templates"></a>Discussion: Use templates to express containers (and other resource handles)
21912 ##### Reason
21914 To provide statically type-safe manipulation of elements.
21916 ##### Example
21918     template<typename T> class Vector {
21919         // ...
21920         T* elem;   // point to sz elements of type T
21921         int sz;
21922     };
21924 ### <a name="Cr-value-return"></a>Discussion: Return containers by value (relying on move or copy elision for efficiency)
21926 ##### Reason
21928 To simplify code and eliminate a need for explicit memory management. To bring an object into a surrounding scope, thereby extending its lifetime.
21930 **See also**: [F.20, the general item about "out" output values](#Rf-out)
21932 ##### Example
21934     vector<int> get_large_vector()
21935     {
21936         return ...;
21937     }
21939     auto v = get_large_vector(); //  return by value is ok, most modern compilers will do copy elision
21941 ##### Exception
21943 See the Exceptions in [F.20](#Rf-out).
21945 ##### Enforcement
21947 Check for pointers and references returned from functions and see if they are assigned to resource handles (e.g., to a `unique_ptr`).
21949 ### <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
21951 ##### Reason
21953 To provide complete control of the lifetime of the resource. To provide a coherent set of operations on the resource.
21955 ##### Example
21957     ??? Messing with pointers
21959 ##### Note
21961 If all members are resource handles, rely on the default special operations where possible.
21963     template<typename T> struct Named {
21964         string name;
21965         T value;
21966     };
21968 Now `Named` has a default constructor, a destructor, and efficient copy and move operations, provided `T` has.
21970 ##### Enforcement
21972 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.
21974 ### <a name="Cr-list"></a>Discussion: If a class is a container, give it an initializer-list constructor
21976 ##### Reason
21978 It is common to need an initial set of elements.
21980 ##### Example
21982     template<typename T> class Vector {
21983     public:
21984         Vector(std::initializer_list<T>);
21985         // ...
21986     };
21988     Vector<string> vs { "Nygaard", "Ritchie" };
21990 ##### Enforcement
21992 When is a class a container? ???
21994 # <a name="S-tools"></a>Appendix D: Supporting tools
21996 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
21997 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.
21999 ### <a name="St-clangtidy"></a>Tools: [Clang-tidy](http://clang.llvm.org/extra/clang-tidy/checks/list.html)
22001 Clang-tidy has a set of rules that specifically enforce the C++ Core Guidelines. These rules are named in the pattern `cppcoreguidelines-*`.
22003 ### <a name="St-cppcorecheck"></a>Tools: [CppCoreCheck](https://docs.microsoft.com/en-us/visualstudio/code-quality/using-the-cpp-core-guidelines-checkers)
22005 The Microsoft compiler's C++ code analysis contains a set of rules specifically aimed at enforcement of the C++ Core Guidelines.
22007 # <a name="S-glossary"></a>Glossary
22009 A relatively informal definition of terms used in the guidelines
22010 (based off the glossary in [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html))
22012 More information on many topics about C++ can be found on the [Standard C++ Foundation](https://isocpp.org)'s site.
22014 * *ABI*: Application Binary Interface, a specification for a specific hardware platform combined with the operating system. Contrast with API.
22015 * *abstract class*: a class that cannot be directly used to create objects; often used to define an interface to derived classes.
22016   A class is made abstract by having a pure virtual function or only protected constructors.
22017 * *abstraction*: a description of something that selectively and deliberately ignores (hides) details (e.g., implementation details); selective ignorance.
22018 * *address*: a value that allows us to find an object in a computer's memory.
22019 * *algorithm*: a procedure or formula for solving a problem; a finite series of computational steps to produce a result.
22020 * *alias*: an alternative way of referring to an object; often a name, pointer, or reference.
22021 * *API*: Application Programming Interface, a set of functions that form the communication between various software components. Contrast with ABI.
22022 * *application*: a program or a collection of programs that is considered an entity by its users.
22023 * *approximation*: something (e.g., a value or a design) that is close to the perfect or ideal (value or design).
22024   Often an approximation is a result of trade-offs among ideals.
22025 * *argument*: a value passed to a function or a template, in which it is accessed through a parameter.
22026 * *array*: a homogeneous sequence of elements, usually numbered, e.g., `[0:max)`.
22027 * *assertion*: a statement inserted into a program to state (assert) that something must always be true at this point in the program.
22028 * *base class*: a class used as the base of a class hierarchy. Typically a base class has one or more virtual functions.
22029 * *bit*: the basic unit of information in a computer. A bit can have the value 0 or the value 1.
22030 * *bug*: an error in a program.
22031 * *byte*: the basic unit of addressing in most computers. Typically, a byte holds 8 bits.
22032 * *class*: a user-defined type that may contain data members, function members, and member types.
22033 * *code*: a program or a part of a program; ambiguously used for both source code and object code.
22034 * *compiler*: a program that turns source code into object code.
22035 * *complexity*: a hard-to-precisely-define notion or measure of the difficulty of constructing a solution to a problem or of the solution itself.
22036   Sometimes complexity is used to (simply) mean an estimate of the number of operations needed to execute an algorithm.
22037 * *computation*: the execution of some code, usually taking some input and producing some output.
22038 * *concept*: (1) a notion, and idea; (2) a set of requirements, usually for a template argument.
22039 * *concrete class*: class for which objects can be created using usual construction syntax (e.g., on the stack) and the resulting object behaves much like an `int` as it comes to copying, comparison, and such
22040 (as opposed to a base class in a hierarchy).
22041 * *constant*: a value that cannot be changed (in a given scope); not mutable.
22042 * *constructor*: an operation that initializes ("constructs") an object.
22043   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).
22044 * *container*: an object that holds elements (other objects).
22045 * *copy*: an operation that makes two object have values that compare equal. See also move.
22046 * *correctness*: a program or a piece of a program is correct if it meets its specification.
22047   Unfortunately, a specification can be incomplete or inconsistent, or can fail to meet users' reasonable expectations.
22048   Thus, to produce acceptable code, we sometimes have to do more than just follow the formal specification.
22049 * *cost*: the expense (e.g., in programmer time, run time, or space) of producing a program or of executing it.
22050   Ideally, cost should be a function of complexity.
22051 * *customization point*: ???
22052 * *data*: values used in a computation.
22053 * *debugging*: the act of searching for and removing errors from a program; usually far less systematic than testing.
22054 * *declaration*: the specification of a name with its type in a program.
22055 * *definition*: a declaration of an entity that supplies all information necessary to complete a program using the entity.
22056   Simplified definition: a declaration that allocates memory.
22057 * *derived class*: a class derived from one or more base classes.
22058 * *design*: an overall description of how a piece of software should operate to meet its specification.
22059 * *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.
22060 * *encapsulation*: protecting something meant to be private (e.g., implementation details) from unauthorized access.
22061 * *error*: a mismatch between reasonable expectations of program behavior (often expressed as a requirement or a users' guide) and what a program actually does.
22062 * *executable*: a program ready to be run (executed) on a computer.
22063 * *feature creep*: a tendency to add excess functionality to a program "just in case."
22064 * *file*: a container of permanent information in a computer.
22065 * *floating-point number*: a computer's approximation of a real number, such as 7.93 and 10.78e-3.
22066 * *function*: a named unit of code that can be invoked (called) from different parts of a program; a logical unit of computation.
22067 * *generic programming*: a style of programming focused on the design and efficient implementation of algorithms.
22068   A generic algorithm will work for all argument types that meet its requirements. In C++, generic programming typically uses templates.
22069 * *global variable*: technically, a named object in namespace scope.
22070 * *handle*: a class that allows access to another through a member pointer or reference. See also resource, copy, move.
22071 * *header*: a file containing declarations used to share interfaces between parts of a program.
22072 * *hiding*: the act of preventing a piece of information from being directly seen or accessed.
22073   For example, a name from a nested (inner) scope can prevent that same name from an outer (enclosing) scope from being directly used.
22074 * *ideal*: the perfect version of something we are striving for. Usually we have to make trade-offs and settle for an approximation.
22075 * *implementation*: (1) the act of writing and testing code; (2) the code that implements a program.
22076 * *infinite loop*: a loop where the termination condition never becomes true. See iteration.
22077 * *infinite recursion*: a recursion that doesn't end until the machine runs out of memory to hold the calls.
22078   In reality, such recursion is never infinite but is terminated by some hardware error.
22079 * *information hiding*: the act of separating interface and implementation, thus hiding implementation details not meant for the user's attention and providing an abstraction.
22080 * *initialize*: giving an object its first (initial) value.
22081 * *input*: values used by a computation (e.g., function arguments and characters typed on a keyboard).
22082 * *integer*: a whole number, such as 42 and -99.
22083 * *interface*: a declaration or a set of declarations specifying how a piece of code (such as a function or a class) can be called.
22084 * *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.
22085 * *iteration*: the act of repeatedly executing a piece of code; see recursion.
22086 * *iterator*: an object that identifies an element of a sequence.
22087 * *ISO*: International Organization for Standardization. The C++ language is an ISO standard, ISO/IEC 14882. More information at [iso.org](http://iso.org).
22088 * *library*: a collection of types, functions, classes, etc. implementing a set of facilities (abstractions) meant to be potentially used as part of more that one program.
22089 * *lifetime*: the time from the initialization of an object until it becomes unusable (goes out of scope, is deleted, or the program terminates).
22090 * *linker*: a program that combines object code files and libraries into an executable program.
22091 * *literal*: a notation that directly specifies a value, such as 12 specifying the integer value "twelve."
22092 * *loop*: a piece of code executed repeatedly; in C++, typically a for-statement or a `while`-statement.
22093 * *move*: an operation that transfers a value from one object to another leaving behind a value representing "empty." See also copy.
22094 * *mutable*: changeable; the opposite of immutable, constant, and invariable.
22095 * *object*: (1) an initialized region of memory of a known type which holds a value of that type; (2) a region of memory.
22096 * *object code*: output from a compiler intended as input for a linker (for the linker to produce executable code).
22097 * *object file*: a file containing object code.
22098 * *object-oriented programming*: (OOP) a style of programming focused on the design and use of classes and class hierarchies.
22099 * *operation*: something that can perform some action, such as a function and an operator.
22100 * *output*: values produced by a computation (e.g., a function result or lines of characters written on a screen).
22101 * *overflow*: producing a value that cannot be stored in its intended target.
22102 * *overload*: defining two functions or operators with the same name but different argument (operand) types.
22103 * *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.
22104 * *owner*: an object responsible for releasing a resource.
22105 * *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.
22106 * *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.
22107 * *pointer*: (1) a value used to identify a typed object in memory; (2) a variable holding such a value.
22108 * *post-condition*: a condition that must hold upon exit from a piece of code, such as a function or a loop.
22109 * *pre-condition*: a condition that must hold upon entry into a piece of code, such as a function or a loop.
22110 * *program*: code (possibly with associated data) that is sufficiently complete to be executed by a computer.
22111 * *programming*: the art of expressing solutions to problems as code.
22112 * *programming language*: a language for expressing programs.
22113 * *pseudo code*: a description of a computation written in an informal notation rather than a programming language.
22114 * *pure virtual function*: a virtual function that must be overridden in a derived class.
22115 * *RAII*: ("Resource Acquisition Is Initialization") a basic technique for resource management based on scopes.
22116 * *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.
22117 * *recursion*: the act of a function calling itself; see also iteration.
22118 * *reference*: (1) a value describing the location of a typed value in memory; (2) a variable holding such a value.
22119 * *regular expression*: a notation for patterns in character strings.
22120 * *regular*: a type that behaves similarly to built-in types like `int` and can be compared with `==`.
22121 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*.
22122 * *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.
22123 * *resource*: something that is acquired and must later be released, such as a file handle, a lock, or memory. See also handle, owner.
22124 * *rounding*: conversion of a value to the mathematically nearest value of a less precise type.
22125 * *RTTI*: Run-Time Type Information. ???
22126 * *scope*: the region of program text (source code) in which a name can be referred to.
22127 * *semiregular*: a type that behaves roughly like an built-in type like `int`, but possibly without a `==` operator. See also *regular type*.
22128 * *sequence*: elements that can be visited in a linear order.
22129 * *software*: a collection of pieces of code and associated data; often used interchangeably with program.
22130 * *source code*: code as produced by a programmer and (in principle) readable by other programmers.
22131 * *source file*: a file containing source code.
22132 * *specification*: a description of what a piece of code should do.
22133 * *standard*: an officially agreed upon definition of something, such as a programming language.
22134 * *state*: a set of values.
22135 * *STL*: the containers, iterators, and algorithms part of the standard library.
22136 * *string*: a sequence of characters.
22137 * *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.
22138 * *subtype*: derived type; a type that has all the properties of a type and possibly more.
22139 * *supertype*: base type; a type that has a subset of the properties of a type.
22140 * *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.
22141 * *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.
22142 * *template*: a class or a function parameterized by one or more types or (compile-time) values; the basic C++ language construct supporting generic programming.
22143 * *testing*: a systematic search for errors in a program.
22144 * *trade-off*: the result of balancing several design and implementation criteria.
22145 * *truncation*: loss of information in a conversion from a type into another that cannot exactly represent the value to be converted.
22146 * *type*: something that defines a set of possible values and a set of operations for an object.
22147 * *uninitialized*: the (undefined) state of an object before it is initialized.
22148 * *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.
22149 * *use case*: a specific (typically simple) use of a program meant to test its functionality and demonstrate its purpose.
22150 * *value*: a set of bits in memory interpreted according to a type.
22151 * *variable*: a named object of a given type; contains a value unless uninitialized.
22152 * *virtual function*: a member function that can be overridden in a derived class.
22153 * *word*: a basic unit of memory in a computer, often the unit used to hold an integer.
22155 # <a name="S-unclassified"></a>To-do: Unclassified proto-rules
22157 This is our to-do list.
22158 Eventually, the entries will become rules or parts of rules.
22159 Alternatively, we will decide that no change is needed and delete the entry.
22161 * No long-distance friendship
22162 * Should physical design (what's in a file) and large-scale design (libraries, groups of libraries) be addressed?
22163 * Namespaces
22164 * Avoid using directives in the global scope (except for std, and other "fundamental" namespaces (e.g. experimental))
22165 * 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?
22166 * Should there be inline namespaces (à la `std::literals::*_literals`)?
22167 * Avoid implicit conversions
22168 * 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
22169 * Always initialize variables, use initialization lists for member variables.
22170 * 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. :)
22171 * Use `const`-ness wherever possible: member functions, variables and (yippee) `const_iterators`
22172 * Use `auto`
22173 * `(size)` vs. `{initializers}` vs. `{Extent{size}}`
22174 * Don't overabstract
22175 * Never pass a pointer down the call stack
22176 * falling through a function bottom
22177 * 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?
22178 * 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?
22179 * Speaking of lambdas, what would weigh in on the decision between lambdas and (local?) classes in algorithm calls and other callback scenarios?
22180 * 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?
22181 * What to do with leaks out of temporaries? : `p = (s1 + s2).c_str();`
22182 * pointer/iterator invalidation leading to dangling pointers:
22184         void bad()
22185         {
22186             int* p = new int[700];
22187             int* q = &p[7];
22188             delete p;
22190             vector<int> v(700);
22191             int* q2 = &v[7];
22192             v.resize(900);
22194             // ... use q and q2 ...
22195         }
22197 * LSP
22198 * private inheritance vs/and membership
22199 * avoid static class members variables (race conditions, almost-global variables)
22201 * Use RAII lock guards (`lock_guard`, `unique_lock`, `shared_lock`), never call `mutex.lock` and `mutex.unlock` directly (RAII)
22202 * Prefer non-recursive locks (often used to work around bad reasoning, overhead)
22203 * 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`?
22204 * If two or more mutexes must be acquired at the same time, use `std::lock` (or another deadlock avoidance algorithm?)
22205 * 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.
22206 * 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)
22207 * 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)
22208 * 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)
22210 * rules for arithmetic
22212 # Bibliography
22214 * <a name="Abrahams01"></a>
22215   \[Abrahams01]:  D. Abrahams. [Exception-Safety in Generic Components](http://www.boost.org/community/exception_safety.html).
22216 * <a name="Alexandrescu01"></a>
22217   \[Alexandrescu01]:  A. Alexandrescu. Modern C++ Design (Addison-Wesley, 2001).
22218 * <a name="Cplusplus03"></a>
22219   \[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).
22220 * <a name="CplusplusCS"></a>
22221   \[C++CS]:           ???
22222 * <a name="Cargill92"></a>
22223   \[Cargill92]:       T. Cargill. C++ Programming Style (Addison-Wesley, 1992).
22224 * <a name="Cline99"></a>
22225   \[Cline99]:         M. Cline, G. Lomow, and M. Girou. C++ FAQs (2ndEdition) (Addison-Wesley, 1999).
22226 * <a name="Dewhurst03"></a>
22227   \[Dewhurst03]:      S. Dewhurst. C++ Gotchas (Addison-Wesley, 2003).
22228 * <a name="Henricson97"></a>
22229   \[Henricson97]:     M. Henricson and E. Nyquist. Industrial Strength C++ (Prentice Hall, 1997).
22230 * <a name="Koenig97"></a>
22231   \[Koenig97]:        A. Koenig and B. Moo. Ruminations on C++ (Addison-Wesley, 1997).
22232 * <a name="Lakos96"></a>
22233   \[Lakos96]:         J. Lakos. Large-Scale C++ Software Design (Addison-Wesley, 1996).
22234 * <a name="Meyers96"></a>
22235   \[Meyers96]:        S. Meyers. More Effective C++ (Addison-Wesley, 1996).
22236 * <a name="Meyers97"></a>
22237   \[Meyers97]:        S. Meyers. Effective C++ (2nd Edition) (Addison-Wesley, 1997).
22238 * <a name="Meyers15"></a>
22239   \[Meyers15]:        S. Meyers. Effective Modern C++ (O'Reilly, 2015).
22240 * <a name="Murray93"></a>
22241   \[Murray93]:        R. Murray. C++ Strategies and Tactics (Addison-Wesley, 1993).
22242 * <a name="Stroustrup94"></a>
22243   \[Stroustrup94]:    B. Stroustrup. The Design and Evolution of C++ (Addison-Wesley, 1994).
22244 * <a name="Stroustrup00"></a>
22245   \[Stroustrup00]:    B. Stroustrup. The C++ Programming Language (Special 3rdEdition) (Addison-Wesley, 2000).
22246 * <a name="Stroustrup05"></a>
22247   \[Stroustrup05]:    B. Stroustrup. [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
22248 * <a name="Stroustrup13"></a>
22249   \[Stroustrup13]:    B. Stroustrup. [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html). Addison Wesley 2013.
22250 * <a name="Stroustrup14"></a>
22251   \[Stroustrup14]:    B. Stroustrup. [A Tour of C++](http://www.stroustrup.com/Tour.html).
22252   Addison Wesley 2014.
22253 * <a name="Stroustrup15"></a>
22254   \[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).
22255 * <a name="SuttHysl04b"></a>
22256   \[SuttHysl04b]:     H. Sutter and J. Hyslop. "Collecting Shared Objects" (C/C++ Users Journal, 22(8), August 2004).
22257 * <a name="SuttAlex05"></a>
22258   \[SuttAlex05]:      H. Sutter and  A. Alexandrescu. C++ Coding Standards. Addison-Wesley 2005.
22259 * <a name="Sutter00"></a>
22260   \[Sutter00]:        H. Sutter. Exceptional C++ (Addison-Wesley, 2000).
22261 * <a name="Sutter02"></a>
22262   \[Sutter02]:        H. Sutter. More Exceptional C++ (Addison-Wesley, 2002).
22263 * <a name="Sutter04"></a>
22264   \[Sutter04]:        H. Sutter. Exceptional C++ Style (Addison-Wesley, 2004).
22265 * <a name="Taligent94"></a>
22266   \[Taligent94]: Taligent's Guide to Designing Programs (Addison-Wesley, 1994).