Per our discussion, C.42 enforcement belongs to C.41
[CppCoreGuidelines.git] / CppCoreGuidelines.md
blob0ce6e3fa3b62524aafb71fb269ab277c1970f4f0
1 # <a name="main"></a>C++ Core Guidelines
3 November 21, 2016
5 Editors:
7 * [Bjarne Stroustrup](http://www.stroustrup.com)
8 * [Herb Sutter](http://herbsutter.com/)
10 This document is a very early draft. It is inkorrekt, incompleat, and pµÃoorly formatted.
11 Had it been an open source (code) project, this would have been release 0.7.
12 Copying, use, modification, and creation of derivative works from this project is licensed under an MIT-style license.
13 Contributing to this project requires agreeing to a Contributor License. See the accompanying [LICENSE](LICENSE) file for details.
14 We make this project available to "friendly users" to use, copy, modify, and derive from, hoping for constructive input.
16 Comments and suggestions for improvements are most welcome.
17 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
18 When commenting, please note [the introduction](#S-introduction) that outlines our aims and general approach.
19 The list of contributors is [here](#SS-ack).
21 Problems:
23 * The sets of rules have not been thoroughly checked for completeness, consistency, or enforceability.
24 * Triple question marks (???) mark known missing information
25 * Update reference sections; many pre-C++11 sources are too old.
26 * For a more-or-less up-to-date to-do list see: [To-do: Unclassified proto-rules](#S-unclassified)
28 You can [read an explanation of the scope and structure of this Guide](#S-abstract) or just jump straight in:
30 * [In: Introduction](#S-introduction)
31 * [P: Philosophy](#S-philosophy)
32 * [I: Interfaces](#S-interfaces)
33 * [F: Functions](#S-functions)
34 * [C: Classes and class hierarchies](#S-class)
35 * [Enum: Enumerations](#S-enum)
36 * [R: Resource management](#S-resource)
37 * [ES: Expressions and statements](#S-expr)
38 * [Per: Performance](#S-performance)
39 * [CP: Concurrency](#S-concurrency)
40 * [E: Error handling](#S-errors)
41 * [Con: Constants and immutability](#S-const)
42 * [T: Templates and generic programming](#S-templates)
43 * [CPL: C-style programming](#S-cpl)
44 * [SF: Source files](#S-source)
45 * [SL: The Standard library](#S-stdlib)
47 Supporting sections:
49 * [A: Architectural Ideas](#S-A)
50 * [N: Non-Rules and myths](#S-not)
51 * [RF: References](#S-references)
52 * [Pro: Profiles](#S-profile)
53 * [GSL: Guideline support library](#S-gsl)
54 * [NL: Naming and layout](#S-naming)
55 * [FAQ: Answers to frequently asked questions](#S-faq)
56 * [Appendix A: Libraries](#S-libraries)
57 * [Appendix B: Modernizing code](#S-modernizing)
58 * [Appendix C: Discussion](#S-discussion)
59 * [Glossary](#S-glossary)
60 * [To-do: Unclassified proto-rules](#S-unclassified)
62 or look at a specific language feature
64 * [assignment](#S-???)
65 * [`class`](#S-class)
66 * [constructor](#SS-ctor)
67 * [derived `class`](#SS-hier)
68 * [destructor](#SS-dtor)
69 * [exception](#S-errors)
70 * [`for`](#S-???)
71 * [`inline`](#S-class)
72 * [initialization](#S-???)
73 * [lambda expression](#SS-lambdas)
74 * [operator](#S-???)
75 * [`public`, `private`, and `protected`](#S-???)
76 * [`static_assert`](#S-???)
77 * [`struct`](#S-class)
78 * [`template`](#S-???)
79 * [`unsigned`](#S-???)
80 * [`virtual`](#SS-hier)
82 Definitions of terms used to express and discuss the rules, that are not language-technical, but refer to design and programming techniques
84 * error
85 * exception
86 * failure
87 * invariant
88 * leak
89 * precondition
90 * postcondition
91 * resource
92 * exception guarantee
94 # <a name="S-abstract"></a>Abstract
96 This document is a set of guidelines for using C++ well.
97 The aim of this document is to help people to use modern C++ effectively.
98 By "modern C++" we mean C++11 and C++14 (and soon C++17).
99 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?
101 The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management, and concurrency.
102 Such rules affect application architecture and library design.
103 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.
104 And it will run fast -- you can afford to do things right.
106 We are less concerned with low-level issues, such as naming conventions and indentation style.
107 However, no topic that can help a programmer is out of bounds.
109 Our initial set of rules emphasizes safety (of various forms) and simplicity.
110 They may very well be too strict.
111 We expect to have to introduce more exceptions to better accommodate real-world needs.
112 We also need more rules.
114 You will find some of the rules contrary to your expectations or even contrary to your experience.
115 If we haven't suggested you change your coding style in any way, we have failed!
116 Please try to verify or disprove rules!
117 In particular, we'd really like to have some of our rules backed up with measurements or better examples.
119 You will find some of the rules obvious or even trivial.
120 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.
122 Many of the rules are designed to be supported by an analysis tool.
123 Violations of rules will be flagged with references (or links) to the relevant rule.
124 We do not expect you to memorize all the rules before trying to write code.
125 One way of thinking about these guidelines is as a specification for tools that happens to be readable by humans.
127 The rules are meant for gradual introduction into a code base.
128 We plan to build tools for that and hope others will too.
130 Comments and suggestions for improvements are most welcome.
131 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
133 # <a name="S-introduction"></a>In: Introduction
135 This is a set of core guidelines for modern C++, C++14, taking likely future enhancements and ISO Technical Specifications (TSs) into account.
136 The aim is to help C++ programmers to write simpler, more efficient, more maintainable code.
138 Introduction summary:
140 * [In.target: Target readership](#SS-readers)
141 * [In.aims: Aims](#SS-aims)
142 * [In.not: Non-aims](#SS-non)
143 * [In.force: Enforcement](#SS-force)
144 * [In.struct: The structure of this document](#SS-struct)
145 * [In.sec: Major sections](#SS-sec)
147 ## <a name="SS-readers"></a>In.target: Target readership
149 All C++ programmers. This includes [programmers who might consider C](#S-cpl).
151 ## <a name="SS-aims"></a>In.aims: Aims
153 The purpose of this document is to help developers to adopt modern C++ (C++11, C++14, and soon C++17) and to achieve a more uniform style across code bases.
155 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.
156 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").
157 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.
158 Remember:
160 ### <a name="R0"></a>In.0: Don't panic!
162 Take the time to understand the implications of a guideline rule on your program.
164 These guidelines are designed according to the "subset of superset" principle ([Stroustrup05](#Stroustrup05)).
165 They do not simply define a subset of C++ to be used (for reliability, safety, performance, or whatever).
166 Instead, they strongly recommend the use of a few simple "extensions" ([library components](#S-gsl))
167 that make the use of the most error-prone features of C++ redundant, so that they can be banned (in our set of rules).
169 The rules emphasize static type safety and resource safety.
170 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).
171 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.
173 Many of the rules are prescriptive.
174 We are uncomfortable with rules that simply state "don't do that!" without offering an alternative.
175 One consequence of that is that some rules can be supported only by heuristics, rather than precise and mechanically verifiable checks.
176 Other rules articulate general principles. For these more general rules, more detailed and specific rules provide partial checking.
178 These guidelines address the core of C++ and its use.
179 We expect that most large organizations, specific application areas, and even large projects will need further rules, possibly further restrictions, and further library support.
180 For example, hard real-time programmers typically can't use free store (dynamic memory) freely and will be restricted in their choice of libraries.
181 We encourage the development of such more specific rules as addenda to these core guidelines.
182 Build your ideal small foundation library and use that, rather than lowering your level of programming to glorified assembly code.
184 The rules are designed to allow [gradual adoption](#S-modernizing).
186 Some rules aim to increase various forms of safety while others aim to reduce the likelihood of accidents, many do both.
187 The guidelines aimed at preventing accidents often ban perfectly legal C++.
188 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.
190 ## <a name="SS-non"></a>In.not: Non-aims
192 The rules are not intended to be minimal or orthogonal.
193 In particular, general rules can be simple, but unenforceable.
194 Also, it is often hard to understand the implications of a general rule.
195 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.
196 We provide rules aimed at helping novices as well as rules supporting expert use.
197 Some rules can be completely enforced, but others are based on heuristics.
199 These rules are not meant to be read serially, like a book.
200 You can browse through them using the links.
201 However, their main intended use is to be targets for tools.
202 That is, a tool looks for violations and the tool returns links to violated rules.
203 The rules then provide reasons, examples of potential consequences of the violation, and suggested remedies.
205 These guidelines are not intended to be a substitute for a tutorial treatment of C++.
206 If you need a tutorial for some given level of experience, see [the references](#S-references).
208 This is not a guide on how to convert old C++ code to more modern code.
209 It is meant to articulate ideas for new code in a concrete fashion.
210 However, see [the modernization section](#S-modernizing) for some possible approaches to modernizing/rejuvenating/upgrading.
211 Importantly, the rules support gradual adoption: It is typically infeasible to convert all of a large code base at once.
213 These guidelines are not meant to be complete or exact in every language-technical detail.
214 For the final word on language definition issues, including every exception to general rules and every feature, see the ISO C++ standard.
216 The rules are not intended to force you to write in an impoverished subset of C++.
217 They are *emphatically* not meant to define a, say, Java-like subset of C++.
218 They are not meant to define a single "one true C++" language.
219 We value expressiveness and uncompromised performance.
221 The rules are not value-neutral.
222 They are meant to make code simpler and more correct/safer than most existing C++ code, without loss of performance.
223 They are meant to inhibit perfectly valid C++ code that correlates with errors, spurious complexity, and poor performance.
225 The rules are not perfect.
226 A rule can do harm by prohibiting something that is useful in a given situation.
227 A rule can do harm by failing to prohibit something that enables a serious error in a given situation.
228 A rule can do a lot of harm by being vague, ambiguous, unenforceable, or by enabling every solution to a problem.
229 It is impossible to completely meet the "do no harm" criteria.
230 Instead, our aim is the less ambitious: "Do the most good for most programmers";
231 if you cannot live with a rule, object to it, ignore it, but don't water it down until it becomes meaningless.
232 Also, suggest an improvement.
234 ## <a name="SS-force"></a>In.force: Enforcement
236 Rules with no enforcement are unmanageable for large code bases.
237 Enforcement of all rules is possible only for a small weak set of rules or for a specific user community.
239 * But we want lots of rules, and we want rules that everybody can use.
240 * But different people have different needs.
241 * But people don't like to read lots of rules.
242 * But people can't remember many rules.
244 So, we need subsetting to meet a variety of needs.
246 * But arbitrary subsetting leads to chaos.
248 We want guidelines that help a lot of people, make code more uniform, and strongly encourage people to modernize their code.
249 We want to encourage best practices, rather than leave all to individual choices and management pressures.
250 The ideal is to use all rules; that gives the greatest benefits.
252 This adds up to quite a few dilemmas.
253 We try to resolve those using tools.
254 Each rule has an **Enforcement** section listing ideas for enforcement.
255 Enforcement might be done by code review, by static analysis, by compiler, or by run-time checks.
256 Wherever possible, we prefer "mechanical" checking (humans are slow, inaccurate, and bore easily) and static checking.
257 Run-time checks are suggested only rarely where no alternative exists; we do not want to introduce "distributed fat".
258 Where appropriate, we label a rule (in the **Enforcement** sections) with the name of groups of related rules (called "profiles").
259 A rule can be part of several profiles, or none.
260 For a start, we have a few profiles corresponding to common needs (desires, ideals):
262 * **type**: No type violations (reinterpreting a `T` as a `U` through casts, unions, or varargs)
263 * **bounds**: No bounds violations (accessing beyond the range of an array)
264 * **lifetime**: No leaks (failing to `delete` or multiple `delete`) and no access to invalid objects (dereferencing `nullptr`, using a dangling reference).
266 The profiles are intended to be used by tools, but also serve as an aid to the human reader.
267 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.
269 Tools that implement these rules shall respect the following syntax to explicitly suppress a rule:
271     [[suppress(tag)]]
273 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
274 name of a profile group-of-rules ("type", "bounds", or "lifetime"),
275 or a specific rule in a profile ([type.4](#Pro-type-cstylecast), or [bounds.2](#Pro-bounds-arrayindex)).
277 ## <a name="SS-struct"></a>In.struct: The structure of this document
279 Each rule (guideline, suggestion) can have several parts:
281 * The rule itself -- e.g., **no naked `new`**
282 * A rule reference number -- e.g., **C.7** (the 7th rule related to classes).
283   Since the major sections are not inherently ordered, we use letters as the first part of a rule reference "number".
284   We leave gaps in the numbering to minimize "disruption" when we add or remove rules.
285 * **Reason**s (rationales) -- because programmers find it hard to follow rules they don't understand
286 * **Example**s -- because rules are hard to understand in the abstract; can be positive or negative
287 * **Alternative**s -- for "don't do this" rules
288 * **Exception**s -- we prefer simple general rules. However, many rules apply widely, but not universally, so exceptions must be listed
289 * **Enforcement** -- ideas about how the rule might be checked "mechanically"
290 * **See also**s -- references to related rules and/or further discussion (in this document or elsewhere)
291 * **Note**s (comments) -- something that needs saying that doesn't fit the other classifications
292 * **Discussion** -- references to more extensive rationale and/or examples placed outside the main lists of rules
294 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.
295 We hope that "mechanical" tools will improve with time to approximate what such an expert programmer notices.
296 Also, we assume that the rules will be refined over time to make them more precise and checkable.
298 A rule is aimed at being simple, rather than carefully phrased to mention every alternative and special case.
299 Such information is found in the **Alternative** paragraphs and the [Discussion](#S-discussion) sections.
300 If you don't understand a rule or disagree with it, please visit its **Discussion**.
301 If you feel that a discussion is missing or incomplete, enter an [Issue](https://github.com/isocpp/CppCoreGuidelines/issues)
302 explaining your concerns and possibly a corresponding PR.
304 This is not a language manual.
305 It is meant to be helpful, rather than complete, fully accurate on technical details, or a guide to existing code.
306 Recommended information sources can be found in [the references](#S-references).
308 ## <a name="SS-sec"></a>In.sec: Major sections
310 * [In: Introduction](#S-introduction)
311 * [P: Philosophy](#S-philosophy)
312 * [I: Interfaces](#S-interfaces)
313 * [F: Functions](#S-functions)
314 * [C: Classes and class hierarchies](#S-class)
315 * [Enum: Enumerations](#S-enum)
316 * [R: Resource management](#S-resource)
317 * [ES: Expressions and statements](#S-expr)
318 * [E: Error handling](#S-errors)
319 * [Con: Constants and immutability](#S-const)
320 * [T: Templates and generic programming](#S-templates)
321 * [CP: Concurrency](#S-concurrency)
322 * [SL: The Standard library](#S-stdlib)
323 * [SF: Source files](#S-source)
324 * [CPL: C-style programming](#S-cpl)
325 * [Pro: Profiles](#S-profile)
326 * [GSL: Guideline support library](#S-gsl)
327 * [FAQ: Answers to frequently asked questions](#S-faq)
329 Supporting sections:
331 * [NL: Naming and layout](#S-naming)
332 * [Per: Performance](#S-performance)
333 * [N: Non-Rules and myths](#S-not)
334 * [RF: References](#S-references)
335 * [Appendix A: Libraries](#S-libraries)
336 * [Appendix B: Modernizing code](#S-modernizing)
337 * [Appendix C: Discussion](#S-discussion)
338 * [Glossary](#S-glossary)
339 * [To-do: Unclassified proto-rules](#S-unclassified)
341 These sections are not orthogonal.
343 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.
344 The main section abbreviations are also used in rule numbers (e.g., "C.11" for "Make concrete types regular").
346 # <a name="S-philosophy"></a>P: Philosophy
348 The rules in this section are very general.
350 Philosophy rules summary:
352 * [P.1: Express ideas directly in code](#Rp-direct)
353 * [P.2: Write in ISO Standard C++](#Rp-Cplusplus)
354 * [P.3: Express intent](#Rp-what)
355 * [P.4: Ideally, a program should be statically type safe](#Rp-typesafe)
356 * [P.5: Prefer compile-time checking to run-time checking](#Rp-compile-time)
357 * [P.6: What cannot be checked at compile time should be checkable at run time](#Rp-run-time)
358 * [P.7: Catch run-time errors early](#Rp-early)
359 * [P.8: Don't leak any resources](#Rp-leak)
360 * [P.9: Don't waste time or space](#Rp-waste)
361 * [P.10: Prefer immutable data to mutable data](#Rp-mutable)
362 * [P.11: Encapsulate messy constructs, rather than spreading through the code](#Rp-library)
364 Philosophical rules are generally not mechanically checkable.
365 However, individual rules reflecting these philosophical themes are.
366 Without a philosophical basis the more concrete/specific/checkable rules lack rationale.
368 ### <a name="Rp-direct"></a>P.1: Express ideas directly in code
370 ##### Reason
372 Compilers don't read comments (or design documents) and neither do many programmers (consistently).
373 What is expressed in code has defined semantics and can (in principle) be checked by compilers and other tools.
375 ##### Example
377     class Date {
378         // ...
379     public:
380         Month month() const;  // do
381         int month();          // don't
382         // ...
383     };
385 The first declaration of `month` is explicit about returning a `Month` and about not modifying the state of the `Date` object.
386 The second version leaves the reader guessing and opens more possibilities for uncaught bugs.
388 ##### Example
390     void f(vector<string>& v)
391     {
392         string val;
393         cin >> val;
394         // ...
395         int index = -1;                    // bad
396         for (int i = 0; i < v.size(); ++i)
397             if (v[i] == val) {
398                 index = i;
399                 break;
400             }
401         // ...
402     }
404 That loop is a restricted form of `std::find`.
405 A much clearer expression of intent would be:
407     void f(vector<string>& v)
408     {
409         string val;
410         cin >> val;
411         // ...
412         auto p = find(begin(v), end(v), val);  // better
413         // ...
414     }
416 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.
418 A C++ programmer should know the basics of the standard library, and use it where appropriate.
419 Any programmer should know the basics of the foundation libraries of the project being worked on, and use them appropriately.
420 Any programmer using these guidelines should know the [guideline support library](#S-gsl), and use it appropriately.
422 ##### Example
424     change_speed(double s);   // bad: what does s signify?
425     // ...
426     change_speed(2.3);
428 A better approach is to be explicit about the meaning of the double (new speed or delta on old speed?) and the unit used:
430     change_speed(Speed s);    // better: the meaning of s is specified
431     // ...
432     change_speed(2.3);        // error: no unit
433     change_speed(23m / 10s);  // meters per second
435 We could have accepted a plain (unit-less) `double` as a delta, but that would have been error-prone.
436 If we wanted both absolute speed and deltas, we would have defined a `Delta` type.
438 ##### Enforcement
440 Very hard in general.
442 * use `const` consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference)
443 * flag uses of casts (casts neuter the type system)
444 * detect code that mimics the standard library (hard)
446 ### <a name="Rp-Cplusplus"></a>P.2: Write in ISO Standard C++
448 ##### Reason
450 This is a set of guidelines for writing ISO Standard C++.
452 ##### Note
454 There are environments where extensions are necessary, e.g., to access system resources.
455 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.
457 Extensions often do not have rigorously defined semantics.  Even extensions that
458 are common and implemented by multiple compilers may have slightly different
459 behaviors and edge case behavior as a direct result of *not* having a rigorous
460 standard definition.  With sufficient use of any such extension, expected
461 portability will be impacted.
463 ##### Note
465 Using valid ISO C++ does not guarantee portability (let alone correctness).
466 Avoid dependence on undefined behavior (e.g., [undefined order of evaluation](#Res-order))
467 and be aware of constructs with implementation defined meaning (e.g., `sizeof(int)`).
469 ##### Note
471 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.
472 In such cases, control their (dis)use with an extension of these Coding Guidelines customized to the specific environment.
474 ##### Enforcement
476 Use an up-to-date C++ compiler (currently C++11 or C++14) with a set of options that do not accept extensions.
478 ### <a name="Rp-what"></a>P.3: Express intent
480 ##### Reason
482 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.
484 ##### Example
486     int i = 0;
487     while (i < v.size()) {
488         // ... do something with v[i] ...
489     }
491 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.
493 Better:
495     for (const auto& x : v) { /* do something with x */ }
497 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:
499     for (auto& x : v) { /* do something with x */ }
501 Sometimes better still, use a named algorithm:
503     for_each(v, [](int x) { /* do something with x */ });
504     for_each(par, v, [](int x) { /* do something with x */ });
506 The last variant makes it clear that we are not interested in the order in which the elements of `v` are handled.
508 A programmer should be familiar with
510 * [The guideline support library](#S-gsl)
511 * [The ISO C++ standard library](#S-stdlib)
512 * Whatever foundation libraries are used for the current project(s)
514 ##### Note
516 Alternative formulation: Say what should be done, rather than just how it should be done.
518 ##### Note
520 Some language constructs express intent better than others.
522 ##### Example
524 If two `int`s are meant to be the coordinates of a 2D point, say so:
526     draw_line(int, int, int, int);  // obscure
527     draw_line(Point, Point);        // clearer
529 ##### Enforcement
531 Look for common patterns for which there are better alternatives
533 * simple `for` loops vs. range-`for` loops
534 * `f(T*, int)` interfaces vs. `f(span<T>)` interfaces
535 * loop variables in too large a scope
536 * naked `new` and `delete`
537 * functions with many arguments of built-in types
539 There is a huge scope for cleverness and semi-automated program transformation.
541 ### <a name="Rp-typesafe"></a>P.4: Ideally, a program should be statically type safe
543 ##### Reason
545 Ideally, a program would be completely statically (compile-time) type safe.
546 Unfortunately, that is not possible. Problem areas:
548 * unions
549 * casts
550 * array decay
551 * range errors
552 * narrowing conversions
554 ##### Note
556 These areas are sources of serious problems (e.g., crashes and security violations).
557 We try to provide alternative techniques.
559 ##### Enforcement
561 We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs.
562 Always suggest an alternative.
563 For example:
565 * unions -- use `variant` (in C++17)
566 * casts -- minimize their use; templates can help
567 * array decay -- use `span` (from the GSL)
568 * range errors -- use `span`
569 * narrowing conversions -- minimize their use and use `narrow` or `narrow_cast` (from the GSL) where they are necessary
571 ### <a name="Rp-compile-time"></a>P.5: Prefer compile-time checking to run-time checking
573 ##### Reason
575 Code clarity and performance.
576 You don't need to write error handlers for errors caught at compile time.
578 ##### Example
580     // Int is an alias used for integers
581     int bits = 0;         // don't: avoidable code
582     for (Int i = 1; i; i <<= 1)
583         ++bits;
584     if (bits < 32)
585         cerr << "Int too small\n"
587 This example is easily simplified
589     // Int is an alias used for integers
590     static_assert(sizeof(Int) >= 4);    // do: compile-time check
592 ##### Example
594     void read(int* p, int n);   // read max n integers into *p
596     int a[100];
597     read(a, 1000);    // bad
599 better
601     void read(span<int> r); // read into the range of integers r
603     int a[100];
604     read(a);        // better: let the compiler figure out the number of elements
606 **Alternative formulation**: Don't postpone to run time what can be done well at compile time.
608 ##### Enforcement
610 * Look for pointer arguments.
611 * Look for run-time checks for range violations.
613 ### <a name="Rp-run-time"></a>P.6: What cannot be checked at compile time should be checkable at run time
615 ##### Reason
617 Leaving hard-to-detect errors in a program is asking for crashes and bad results.
619 ##### Note
621 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).
623 ##### Example, bad
625     // separately compiled, possibly dynamically loaded
626     extern void f(int* p);
628     void g(int n)
629     {
630         // bad: the number of elements is not passed to f()
631         f(new int[n]);
632     }
634 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.
636 ##### Example, bad
638 We can of course pass the number of elements along with the pointer:
640     // separately compiled, possibly dynamically loaded
641     extern void f2(int* p, int n);
643     void g2(int n)
644     {
645         f2(new int[n], m);  // bad: a wrong number of elements can be passed to f()
646     }
648 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.
650 Also, it is implicit that `f2()` is supposed to `delete` its argument (or did the caller make a second mistake?).
652 ##### Example, bad
654 The standard library resource management pointers fail to pass the size when they point to an object:
656     // separately compiled, possibly dynamically loaded
657     // NB: this assumes the calling code is ABI-compatible, using a
658     // compatible C++ compiler and the same stdlib implementation
659     extern void f3(unique_ptr<int[]>, int n);
661     void g3(int n)
662     {
663         f3(make_unique<int[]>(n), m);    // bad: pass ownership and size separately
664     }
666 ##### Example
668 We need to pass the pointer and the number of elements as an integral object:
670     extern void f4(vector<int>&);   // separately compiled, possibly dynamically loaded
671     extern void f4(span<int>);      // separately compiled, possibly dynamically loaded
672                                     // NB: this assumes the calling code is ABI-compatible, using a
673                                     // compatible C++ compiler and the same stdlib implementation
675     void g3(int n)
676     {
677         vector<int> v(n);
678         f4(v);                     // pass a reference, retain ownership
679         f4(span<int>{v});          // pass a view, retain ownership
680     }
682 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.
684 ##### Example
686 How do we transfer both ownership and all information needed for validating use?
688     vector<int> f5(int n)    // OK: move
689     {
690         vector<int> v(n);
691         // ... initialize v ...
692         return v;
693     }
695     unique_ptr<int[]> f6(int n)    // bad: loses n
696     {
697         auto p = make_unique<int[]>(n);
698         // ... initialize *p ...
699         return p;
700     }
702     owner<int*> f7(int n)    // bad: loses n and we might forget to delete
703     {
704         owner<int*> p = new int[n];
705         // ... initialize *p ...
706         return p;
707     }
709 ##### Example
711 * ???
712 * show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
713   Or strings as "free-style" options
715 ##### Enforcement
717 * Flag (pointer, count)-style interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons)
718 * ???
720 ### <a name="Rp-early"></a>P.7: Catch run-time errors early
722 ##### Reason
724 Avoid "mysterious" crashes.
725 Avoid errors leading to (possibly unrecognized) wrong results.
727 ##### Example
729     void increment1(int* p, int n)    // bad: error prone
730     {
731         for (int i = 0; i < n; ++i) ++p[i];
732     }
734     void use1(int m)
735     {
736         const int n = 10;
737         int a[n] = {};
738         // ...
739         increment1(a, m);   // maybe typo, maybe m <= n is supposed
740                             // but assume that m == 20
741         // ...
742     }
744 Here we made a small error in `use1` that will lead to corrupted data or a crash.
745 The (pointer, count)-style interface leaves `increment1()` with no realistic way of defending itself against out-of-range errors.
746 Assuming that we could check subscripts for out of range access, the error would not be discovered until `p[10]` was accessed.
747 We could check earlier and improve the code:
749     void increment2(span<int> p)
750     {
751         for (int& x : p) ++x;
752     }
754     void use2(int m)
755     {
756         const int n = 10;
757         int a[n] = {};
758         // ...
759         increment2({a, m});    // maybe typo, maybe m <= n is supposed
760         // ...
761     }
763 Now, `m<=n` can be checked at the point of call (early) rather than later.
764 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):
766     void use3(int m)
767     {
768         const int n = 10;
769         int a[n] = {};
770         // ...
771         increment2(a);   // the number of elements of a need not be repeated
772         // ...
773     }
775 ##### Example, bad
777 Don't repeatedly check the same value. Don't pass structured data as strings:
779     Date read_date(istream& is);    // read date from istream
781     Date extract_date(const string& s);    // extract date from string
783     void user1(const string& date)    // manipulate date
784     {
785         auto d = extract_date(date);
786         // ...
787     }
789     void user2()
790     {
791         Date d = read_date(cin);
792         // ...
793         user1(d.to_string());
794         // ...
795     }
797 The date is validated twice (by the `Date` constructor) and passed as a character string (unstructured data).
799 ##### Example
801 Excess checking can be costly.
802 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)`).
804     class Jet {    // Physics says: e * e < x * x + y * y + z * z
805         float x;
806         float y;
807         float z;
808         float e;
809     public:
810         Jet(float x, float y, float z, float e)
811             :x(x), y(y), z(z), e(e)
812         {
813             // Should I check here that the values are physically meaningful?
814         }
816         float m() const
817         {
818             // Should I handle the degenerate case here?
819             return sqrt(x * x + y * y + z * z - e * e);
820         }
822         ???
823     };
825 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.
829 ##### Enforcement
831 * Look at pointers and arrays: Do range-checking early and not repeatedly
832 * Look at conversions: Eliminate or mark narrowing conversions
833 * Look for unchecked values coming from input
834 * Look for structured data (objects of classes with invariants) being converted into strings
835 * ???
837 ### <a name="Rp-leak"></a>P.8: Don't leak any resources
839 ##### Reason
841 Even a slow growth in resources will, over time, exhaust the availability of those resources.
842 This is particularly important for long-running programs, but is an essential piece of responsible programming behavior.
844 ##### Example, bad
846     void f(char* name)
847     {
848         FILE* input = fopen(name, "r");
849         // ...
850         if (something) return;   // bad: if something == true, a file handle is leaked
851         // ...
852         fclose(input);
853     }
855 Prefer [RAII](#Rr-raii):
857     void f(char* name)
858     {
859         ifstream input {name};
860         // ...
861         if (something) return;   // OK: no leak
862         // ...
863     }
865 **See also**: [The resource management section](#S-resource)
867 ##### Note
869 A leak is colloquially "anything that isn't cleaned up."
870 The more important classification is "anything that can no longer be cleaned up."
871 For example, allocating an object on the heap and then losing the last pointer that points to that allocation.
872 This rule should not be taken as requiring that allocations within long-lived objects must be returned during program shutdown.
873 For example, relying on system guaranteed cleanup such as file closing and memory deallocation upon process shutdown can simplify code.
874 However, relying on abstractions that implicitly clean up can be as simple, and often safer.
876 ##### Note
878 Enforcing [the lifetime profile](#In.force) eliminates leaks.
879 When combined with resource safety provided by [RAII](#Rr-raii), it eliminates the need for "garbage collection" (by generating no garbage).
880 Combine this with enforcement of [the type and bounds profiles](#In.force) and you get complete type- and resource-safety, guaranteed by tools.
882 ##### Enforcement
884 * Look at pointers: Classify them into non-owners (the default) and owners.
885   Where feasible, replace owners with standard-library resource handles (as in the example above).
886   Alternatively, mark an owner as such using `owner` from [the GSL](#S-gsl).
887 * Look for naked `new` and `delete`
888 * Look for known resource allocating functions returning raw pointers (such as `fopen`, `malloc`, and `strdup`)
890 ### <a name="Rp-waste"></a>P.9: Don't waste time or space
892 ##### Reason
894 This is C++.
896 ##### Note
898 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.
899 "Another benefit of striving for efficiency is that the process forces you to understand the problem in more depth." - Alex Stepanov
901 ##### Example, bad
903     struct X {
904         char ch;
905         int i;
906         string s;
907         char ch2;
909         X& operator=(const X& a);
910         X(const X&);
911     };
913     X waste(const char* p)
914     {
915         if (p == nullptr) throw Nullptr_error{};
916         int n = strlen(p);
917         auto buf = new char[n];
918         if (buf == nullptr) throw Allocation_error{};
919         for (int i = 0; i < n; ++i) buf[i] = p[i];
920         // ... manipulate buffer ...
921         X x;
922         x.ch = 'a';
923         x.s = string(n);    // give x.s space for *ps
924         for (int i = 0; i < x.s.size(); ++i) x.s[i] = buf[i];  // copy buf into x.s
925         delete buf;
926         return x;
927     }
929     void driver()
930     {
931         X x = waste("Typical argument");
932         // ...
933     }
935 Yes, this is a caricature, but we have seen every individual mistake in production code, and worse.
936 Note that the layout of `X` guarantees that at least 6 bytes (and most likely more) bytes are wasted.
937 The spurious definition of copy operations disables move semantics so that the return operation is slow
938 (please note that the Return Value Optimization, RVO, is not guaranteed here).
939 The use of `new` and `delete` for `buf` is redundant; if we really needed a local string, we should use a local `string`.
940 There are several more performance bugs and gratuitous complication.
942 ##### Example, bad
944     void lower(zstring s)
945     {
946         for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
947     }
949 Yes, this is an example from production code.
950 We leave it to the reader to figure out what's wasted.
952 ##### Note
954 An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert.
955 However, waste spread liberally across a code base can easily be significant and experts are not always as available as we would like.
956 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.
957 After that, we can look at waste related to algorithms and requirements, but that is beyond the scope of these guidelines.
959 ##### Enforcement
961 Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste.
963 ### <a name="Rp-mutable"></a>P.10: Prefer immutable data to mutable data
965 ##### Reason
967 It is easier to reason about constants than about variables.
968 Something immutable cannot change unexpectedly.
969 Sometimes immutability enables better optimization.
970 You can't have a data race on a constant.
972 See [Con: Constants and Immutability](#S-const)
974 ### <a name="Rp-library"></a>P.11: Encapsulate messy constructs, rather than spreading through the code
976 ##### Reason
978 Messy code is more likely to hide bugs and harder to write.
979 A good interface is easier and safer to use.
980 Messy, low-level code breeds more such code.
982 ##### Example
984     int sz = 100;
985     int* p = (int*) malloc(sizeof(int) * sz);
986     int count = 0;
987     // ...
988     for (;;) {
989         // ... read an int into x, exit loop if end of file is reached ...
990         // ... check that x is valid ...
991         if (count == sz)
992             p = (int*) realloc(p, sizeof(int) * sz * 2);
993         p[count++] = x;
994         // ...
995     }
997 This is low-level, verbose, and error-prone.
998 For example, we "forgot" to test for memory exhaustion.
999 Instead, we could use `vector`:
1001     vector<int> v;
1002     v.reserve(100);
1003     // ...
1004     for (int x; cin >> x; ) {
1005         // ... check that x is valid ...
1006         v.push_back(x);
1007     }
1009 ##### Note
1011 The standards library and the GSL are examples of this philosophy.
1012 For example, instead of messing with the arrays, unions, cast, tricky lifetime issues, `gsl::owner`, etc.
1013 that is needed to implement key abstractions, such as `vector`, `span`, `lock_guard`, and `future`, we use the libraries
1014 designed and implemented by people with more time and expertise than we usually have.
1015 Similarly, we can and should design and implement more specialized libraries, rather than leaving the users (often ourselves)
1016 with the challenge of repeatedly getting low-level code well.
1017 This is a variant of the [subset of superset principle](#R0) that underlies these guidelines.
1019 ##### Enforcement
1021 * Look for "messy code" such as complex pointer manipulation and casting outside the implementation of abstractions.
1024 # <a name="S-interfaces"></a>I: Interfaces
1026 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.
1027 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.
1029 Interface rule summary:
1031 * [I.1: Make interfaces explicit](#Ri-explicit)
1032 * [I.2: Avoid global variables](#Ri-global)
1033 * [I.3: Avoid singletons](#Ri-singleton)
1034 * [I.4: Make interfaces precisely and strongly typed](#Ri-typed)
1035 * [I.5: State preconditions (if any)](#Ri-pre)
1036 * [I.6: Prefer `Expects()` for expressing preconditions](#Ri-expects)
1037 * [I.7: State postconditions](#Ri-post)
1038 * [I.8: Prefer `Ensures()` for expressing postconditions](#Ri-ensures)
1039 * [I.9: If an interface is a template, document its parameters using concepts](#Ri-concepts)
1040 * [I.10: Use exceptions to signal a failure to perform a required tasks](#Ri-except)
1041 * [I.11: Never transfer ownership by a raw pointer (`T*`)](#Ri-raw)
1042 * [I.12: Declare a pointer that must not be null as `not_null`](#Ri-nullptr)
1043 * [I.13: Do not pass an array as a single pointer](#Ri-array)
1044 * [I.22: Avoid complex initialization of global objects](#Ri-global-init)
1045 * [I.23: Keep the number of function arguments low](#Ri-nargs)
1046 * [I.24: Avoid adjacent unrelated parameters of the same type](#Ri-unrelated)
1047 * [I.25: Prefer abstract classes as interfaces to class hierarchies](#Ri-abstract)
1048 * [I.26: If you want a cross-compiler ABI, use a C-style subset](#Ri-abi)
1050 See also
1052 * [F: Functions](#S-functions)
1053 * [C.concrete: Concrete types](#SS-concrete)
1054 * [C.hier: Class hierarchies](#SS-hier)
1055 * [C.over: Overloading and overloaded operators](#SS-overload)
1056 * [C.con: Containers and other resource handles](#SS-containers)
1057 * [E: Error handling](#S-errors)
1058 * [T: Templates and generic programming](#S-templates)
1060 ### <a name="Ri-explicit"></a>I.1: Make interfaces explicit
1062 ##### Reason
1064 Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.
1066 ##### Example, bad
1068 Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:
1070     int rnd(double d)
1071     {
1072         return (rnd_up) ? ceil(d) : d;    // don't: "invisible" dependency
1073     }
1075 It will not be obvious to a caller that the meaning of two calls of `rnd(7.2)` might give different results.
1077 ##### Exception
1079 Sometimes we control the details of a set of operations by an environment variable, e.g., normal vs. verbose output or debug vs. optimized.
1080 The use of a non-local control is potentially confusing, but controls only implementation details of otherwise fixed semantics.
1082 ##### Example, bad
1084 Reporting through non-local variables (e.g., `errno`) is easily ignored. For example:
1086     // don't: no test of printf's return value
1087     fprintf(connection, "logging: %d %d %d\n", x, y, s);
1089 What if the connection goes down so that no logging output is produced? See I.??.
1091 **Alternative**: Throw an exception. An exception cannot be ignored.
1093 **Alternative formulation**: Avoid passing information across an interface through non-local or implicit state.
1094 Note that non-`const` member functions pass information to other member functions through their object's state.
1096 **Alternative formulation**: An interface should be a function or a set of functions.
1097 Functions can be template functions and sets of functions can be classes or class templates.
1099 ##### Enforcement
1101 * (Simple) A function should not make control-flow decisions based on the values of variables declared at namespace scope.
1102 * (Simple) A function should not write to variables declared at namespace scope.
1104 ### <a name="Ri-global"></a>I.2 Avoid global variables
1106 ##### Reason
1108 Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes.
1110 ##### Example
1112     struct Data {
1113         // ... lots of stuff ...
1114     } data;            // non-const data
1116     void compute()     // don't
1117     {
1118         // ... use data ...
1119     }
1121     void output()     // don't
1122     {
1123         // ... use data ...
1124     }
1126 Who else might modify `data`?
1128 ##### Note
1130 Global constants are useful.
1132 ##### Note
1134 The rule against global variables applies to namespace scope variables as well.
1136 **Alternative**: If you use global (more generally namespace scope data) to avoid copying, consider passing the data as an object by reference to `const`.
1137 Another solution is to define the data as the state of some object and the operations as member functions.
1139 **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.
1140 Every pointer or reference to mutable data is a potential data race.
1142 ##### Note
1144 You cannot have a race condition on immutable data.
1146 **References**: See the [rules for calling functions](#SS-call).
1148 ##### Enforcement
1150 (Simple) Report all non-`const` variables declared at namespace scope.
1152 ### <a name="Ri-singleton"></a>I.3: Avoid singletons
1154 ##### Reason
1156 Singletons are basically complicated global objects in disguise.
1158 ##### Example
1160     class Singleton {
1161         // ... lots of stuff to ensure that only one Singleton object is created,
1162         // that it is initialized properly, etc.
1163     };
1165 There are many variants of the singleton idea.
1166 That's part of the problem.
1168 ##### Note
1170 If you don't want a global object to change, declare it `const` or `constexpr`.
1172 ##### Exception
1174 You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any:
1176     X& myX()
1177     {
1178         static X my_x {3};
1179         return my_x;
1180     }
1182 This is one of the most effective solutions to problems related to initialization order.
1183 In a multi-threaded environment the initialization of the static object does not introduce a race condition
1184 (unless you carelessly access a shared object from within its constructor).
1186 Note that the initialization of a local `static` does not imply a race condition.
1187 However, if the destruction of `X` involves an operation that needs to be synchronized we must use a less simple solution.
1188 For example:
1190     X& myX()
1191     {
1192         static auto p = new X {3};
1193         return *p;  // potential leak
1194     }
1196 Now someone has to `delete` that object in some suitably thread-safe way.
1197 That's error-prone, so we don't use that technique unless
1199 * `myX` is in multithreaded code,
1200 * that `X` object needs to be destroyed (e.g., because it releases a resource), and
1201 * `X`'s destructor's code needs to be synchronized.
1203 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.
1205 ##### Enforcement
1207 Very hard in general.
1209 * Look for classes with names that include `singleton`.
1210 * Look for classes for which only a single object is created (by counting objects or by examining constructors).
1211 * 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.
1213 ### <a name="Ri-typed"></a>I.4: Make interfaces precisely and strongly typed
1215 ##### Reason
1217 Types are the simplest and best documentation, have well-defined meaning, and are guaranteed to be checked at compile time.
1218 Also, precisely typed code is often optimized better.
1220 ##### Example, don't
1222 Consider:
1224     void pass(void* data);    // void* is suspicious
1226 Now the callee has to cast the data pointer (back) to a correct type to use it. That is error-prone and often verbose.
1227 Avoid `void*`, especially in interfaces.
1228 Consider using a `variant` or a pointer to base instead.
1230 **Alternative**: Often, a template parameter can eliminate the `void*` turning it into a `T*` or `T&`.
1231 For generic code these `T`s can be general or concept constrained template parameters.
1233 ##### Example, bad
1235 Consider:
1237     void draw_rect(int, int, int, int);   // great opportunities for mistakes
1239     draw_rect(p.x, p.y, 10, 20);          // what does 10, 20 mean?
1241 An `int` can carry arbitrary forms of information, so we must guess about the meaning of the four `int`s.
1242 Most likely, the first two are an `x`,`y` coordinate pair, but what are the last two?
1243 Comments and parameter names can help, but we could be explicit:
1245     void draw_rectangle(Point top_left, Point bottom_right);
1246     void draw_rectangle(Point top_left, Size height_width);
1248     draw_rectangle(p, Point{10, 20});  // two corners
1249     draw_rectangle(p, Size{10, 20});   // one corner and a (height, width) pair
1251 Obviously, we cannot catch all errors through the static type system
1252 (e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)).
1254 ##### Example, bad
1256 In the following example, it is not clear from the interface what `time_to_blink` means: Seconds? Milliseconds?
1258     void blink_led(int time_to_blink) // bad -- the unit is ambiguous
1259     {
1260         // ...
1261         // do something with time_to_blink
1262         // ...
1263     }
1265     void use()
1266     {
1267         blink_led(2);
1268     }
1270 ##### Example, good
1272 `std::chrono::duration` types (C++11) helps making the unit of time duration explicit.
1274     void blink_led(milliseconds time_to_blink) // good -- the unit is explicit
1275     {
1276         // ...
1277         // do something with time_to_blink
1278         // ...
1279     }
1281     void use()
1282     {
1283         blink_led(1500ms);
1284     }
1286 The function can also be written in such a way that it will accept any time duration unit.
1288     template<class rep, class period>
1289     void blink_led(duration<rep, period> time_to_blink) // good -- accepts any unit
1290     {
1291         // assuming that millisecond is the smallest relevant unit
1292         auto milliseconds_to_blink = duration_cast<milliseconds>(time_to_blink);
1293         // ...
1294         // do something with milliseconds_to_blink
1295         // ...
1296     }
1298     void use()
1299     {
1300         blink_led(2s);
1301         blink_led(1500ms);
1302     }
1304 ##### Enforcement
1306 * (Simple) Report the use of `void*` as a parameter or return type.
1307 * (Hard to do well) Look for member functions with many built-in type arguments.
1309 ### <a name="Ri-pre"></a>I.5: State preconditions (if any)
1311 ##### Reason
1313 Arguments have meaning that may constrain their proper use in the callee.
1315 ##### Example
1317 Consider:
1319     double sqrt(double x);
1321 Here `x` must be nonnegative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
1323     double sqrt(double x); // x must be nonnegative
1325 Some preconditions can be expressed as assertions. For example:
1327     double sqrt(double x) { Expects(x >= 0); /* ... */ }
1329 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).
1331 **References**: `Expects()` is described in [GSL](#S-gsl).
1333 ##### Note
1335 Prefer a formal specification of requirements, such as `Expects(p != nullptr);`.
1336 If that is infeasible, use English text in comments, such as `// the sequence [p:q) is ordered using <`.
1338 ##### Note
1340 Most member functions have as a precondition that some class invariant holds.
1341 That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class.
1342 We don't need to mention it for each member function.
1344 ##### Enforcement
1346 (Not enforceable)
1348 **See also**: The rules for passing pointers. ???
1350 ### <a name="Ri-expects"></a>I.6: Prefer `Expects()` for expressing preconditions
1352 ##### Reason
1354 To make it clear that the condition is a precondition and to enable tool use.
1356 ##### Example
1358     int area(int height, int width)
1359     {
1360         Expects(height > 0 && width > 0);            // good
1361         if (height <= 0 || width <= 0) my_error();   // obscure
1362         // ...
1363     }
1365 ##### Note
1367 Preconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
1368 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?).
1370 ##### Note
1372 Preconditions should be part of the interface rather than part of the implementation,
1373 but we don't yet have the language facilities to do that.
1374 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.
1376 ##### Note
1378 `Expects()` can also be used to check a condition in the middle of an algorithm.
1380 ##### Enforcement
1382 (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.
1384 ### <a name="Ri-post"></a>I.7: State postconditions
1386 ##### Reason
1388 To detect misunderstandings about the result and possibly catch erroneous implementations.
1390 ##### Example, bad
1392 Consider:
1394     int area(int height, int width) { return height * width; }  // bad
1396 Here, we (incautiously) left out the precondition specification, so it is not explicit that height and width must be positive.
1397 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.
1398 Overflow can happen.
1399 Consider using:
1401     int area(int height, int width)
1402     {
1403         auto res = height * width;
1404         Ensures(res > 0);
1405         return res;
1406     }
1408 ##### Example, bad
1410 Consider a famous security bug:
1412     void f()    // problematic
1413     {
1414         char buffer[MAX];
1415         // ...
1416         memset(buffer, 0, MAX);
1417     }
1419 There was no postcondition stating that the buffer should be cleared and the optimizer eliminated the apparently redundant `memset()` call:
1421     void f()    // better
1422     {
1423         char buffer[MAX];
1424         // ...
1425         memset(buffer, 0, MAX);
1426         Ensures(buffer[0] == 0);
1427     }
1429 ##### Note
1431 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.
1433 ##### Note
1435 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.
1437 ##### Example
1439 Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions:
1441     mutex m;
1443     void manipulate(Record& r)    // don't
1444     {
1445         m.lock();
1446         // ... no m.unlock() ...
1447     }
1449 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.
1450 Stating the postcondition would have made it clear:
1452     void manipulate(Record& r)    // postcondition: m is unlocked upon exit
1453     {
1454         m.lock();
1455         // ... no m.unlock() ...
1456     }
1458 The bug is now obvious (but only to a human reading comments)
1460 Better still, use [RAII](#Rr-raii) to ensure that the postcondition ("the lock must be released") is enforced in code:
1462     void manipulate(Record& r)    // best
1463     {
1464         lock_guard<mutex> _ {m};
1465         // ...
1466     }
1468 ##### Note
1470 Ideally, postconditions are stated in the interface/declaration so that users can easily see them.
1471 Only postconditions related to the users can be stated in the interface.
1472 Postconditions related only to internal state belongs in the definition/implementation.
1474 ##### Enforcement
1476 (Not enforceable) This is a philosophical guideline that is infeasible to check
1477 directly in the general case. Domain specific checkers (like lock-holding
1478 checkers) exist for many toolchains.
1480 ### <a name="Ri-ensures"></a>I.8: Prefer `Ensures()` for expressing postconditions
1482 ##### Reason
1484 To make it clear that the condition is a postcondition and to enable tool use.
1486 ##### Example
1488     void f()
1489     {
1490         char buffer[MAX];
1491         // ...
1492         memset(buffer, 0, MAX);
1493         Ensures(buffer[0] == 0);
1494     }
1496 ##### Note
1498 Postconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
1499 This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics.
1501 **Alternative**: Postconditions of the form "this resource must be released" are best expressed by [RAII](#Rr-raii).
1503 ##### Note
1505 Ideally, that `Ensures` should be part of the interface, but that's not easily done.
1506 For now, we place it in the definition (function body).
1507 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.
1509 ##### Enforcement
1511 (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.
1513 ### <a name="Ri-concepts"></a>I.9: If an interface is a template, document its parameters using concepts
1515 ##### Reason
1517 Make the interface precisely specified and compile-time checkable in the (not so distant) future.
1519 ##### Example
1521 Use the ISO Concepts TS style of requirements specification. For example:
1523     template<typename Iter, typename Val>
1524     // requires InputIterator<Iter> && EqualityComparable<ValueType<Iter>>, Val>
1525     Iter find(Iter first, Iter last, Val v)
1526     {
1527         // ...
1528     }
1530 ##### Note
1532 Soon (maybe in 2017), most compilers will be able to check `requires` clauses once the `//` is removed.
1533 For now, the concept TS is supported only in GCC 6.1.
1535 **See also**: See [generic programming](#SS-GP) and [concepts](#SS-t-concepts).
1537 ##### Enforcement
1539 (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).
1541 ### <a name="Ri-except"></a>I.10: Use exceptions to signal a failure to perform a required task
1543 ##### Reason
1545 It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state.
1546 This is a major source of errors.
1548 ##### Example
1550     int printf(const char* ...);    // bad: return negative number if output fails
1552     template <class F, class ...Args>
1553     // good: throw system_error if unable to start the new thread
1554     explicit thread(F&& f, Args&&... args);
1556 ##### Note
1558 What is an error?
1560 An error means that the function cannot achieve its advertised purpose (including establishing postconditions).
1561 Calling code that ignores the error could lead to wrong results or undefined systems state.
1562 For example, not being able to connect to a remote server is not by itself an error:
1563 the server can refuse a connection for all kinds of reasons, so the natural thing is to return a result that the caller always has to check.
1564 However, if failing to make a connection is considered an error, then a failure should throw an exception.
1566 ##### Exception
1568 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.
1570 ##### Alternative
1572 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:
1574     int val;
1575     int error_code;
1576     tie(val, error_code) = do_something();
1577     if (error_code == 0) {
1578         // ... handle the error or exit ...
1579     }
1580     // ... use val ...
1582 This style unfortunately leads to uninitialized variable.
1583 A facility [structured bindings](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0144r1.pdf) to deal with that will become available in C++17.
1585     [val, error_code] = do_something();
1586     if (error_code == 0) {
1587         // ... handle the error or exit ...
1588     }
1589     // ... use val ...
1592 ##### Note
1594 We don't consider "performance" a valid reason not to use exceptions.
1596 * Often, explicit error checking and handling consume as much time and space as exception handling.
1597 * Often, cleaner code yields better performance with exceptions (simplifying the tracing of paths through the program and their optimization).
1598 * A good rule for performance critical code is to move checking outside the critical part of the code ([checking](#Rper-checking)).
1599 * In the longer term, more regular code gets better optimized.
1600 * Always carefully [measure](#Rper-measure) before making performance claims.
1602 **See also**: [I.5](#Ri-pre) and [I.7](#Ri-post) for reporting precondition and postcondition violations.
1604 ##### Enforcement
1606 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
1607 * Look for `errno`.
1609 ### <a name="Ri-raw"></a>I.11: Never transfer ownership by a raw pointer (`T*`)
1611 ##### Reason
1613 If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.
1615 ##### Example
1617 Consider:
1619     X* compute(args)    // don't
1620     {
1621         X* res = new X{};
1622         // ...
1623         return res;
1624     }
1626 Who deletes the returned `X`? The problem would be harder to spot if compute returned a reference.
1627 Consider returning the result by value (use move semantics if the result is large):
1629     vector<double> compute(args)  // good
1630     {
1631         vector<double> res(10000);
1632         // ...
1633         return res;
1634     }
1636 **Alternative**: Pass ownership using a "smart pointer", such as `unique_ptr` (for exclusive ownership) and `shared_ptr` (for shared ownership).
1637 However that is less elegant and less efficient unless reference semantics are needed.
1639 **Alternative**: Sometimes older code can't be modified because of ABI compatibility requirements or lack of resources.
1640 In that case, mark owning pointers using `owner` from [guideline support library](#S-gsl):
1642     owner<X*> compute(args)    // It is now clear that ownership is transferred
1643     {
1644         owner<X*> res = new X{};
1645         // ...
1646         return res;
1647     }
1649 This tells analysis tools that `res` is an owner.
1650 That is, its value must be `delete`d or transferred to another owner, as is done here by the `return`.
1652 `owner` is used similarly in the implementation of resource handles.
1654 ##### Note
1656 Every object passed as a raw pointer (or iterator) is assumed to be owned by the
1657 caller, so that its lifetime is handled by the caller. Viewed another way:
1658 ownership transferring APIs are relatively rare compared to pointer-passing APIs,
1659 so the default is "no ownership transfer."
1661 **See also**: [Argument passing](#Rf-conventional) and [value return](#Rf-T-return).
1663 ##### Enforcement
1665 * (Simple) Warn on `delete` of a raw pointer that is not an `owner`.
1666 * (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path.
1667 * (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
1669 ### <a name="Ri-nullptr"></a>I.12: Declare a pointer that must not be null as `not_null`
1671 ##### Reason
1673 To help avoid dereferencing `nullptr` errors.
1674 To improve performance by avoiding redundant checks for `nullptr`.
1676 ##### Example
1678     int length(const char* p);            // it is not clear whether length(nullptr) is valid
1680     length(nullptr);                      // OK?
1682     int length(not_null<const char*> p);  // better: we can assume that p cannot be nullptr
1684     int length(const char* p);            // we must assume that p can be nullptr
1686 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.
1688 ##### Note
1690 `not_null` is defined in the [guideline support library](#S-gsl)
1692 ##### Note
1694 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 `zstring` in preference to `const char*`.
1696     // we can assume that p cannot be nullptr
1697     // we can assume that p points to a zero-terminated array of characters
1698     int length(not_null<zstring> p);
1700 Note: `length()` is, of course, `std::strlen()` in disguise.
1702 ##### Enforcement
1704 * (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`.
1705 * (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`.
1707 ### <a name="Ri-array"></a>I.13: Do not pass an array as a single pointer
1709 ##### Reason
1711  (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.
1713 ##### Example
1715 Consider:
1717     void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
1719 What if there are fewer than `n` elements in the array pointed to by `q`? Then, we overwrite some probably unrelated memory.
1720 What if there are fewer than `n` elements in the array pointed to by `p`? Then, we read some probably unrelated memory.
1721 Either is undefined behavior and a potentially very nasty bug.
1723 ##### Alternative
1725 Consider using explicit spans:
1727     void copy(span<const T> r, span<T> r2); // copy r to r2
1729 ##### Example, bad
1731 Consider:
1733     void draw(Shape* p, int n);  // poor interface; poor code
1734     Circle arr[10];
1735     // ...
1736     draw(arr, 10);
1738 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.
1740 **Alternative**: Use a support class that ensures that the number of elements is correct and prevents dangerous implicit conversions. For example:
1742     void draw2(span<Circle>);
1743     Circle arr[10];
1744     // ...
1745     draw2(span<Circle>(arr));  // deduce the number of elements
1746     draw2(arr);    // deduce the element type and array size
1748     void draw3(span<Shape>);
1749     draw3(arr);    // error: cannot convert Circle[10] to span<Shape>
1751 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 ???.
1753 ##### Exception
1755 Use `zstring` and `czstring` to represent a C-style, zero-terminated strings.
1756 But when doing so, use `string_span` from the [GSL](#GSL) to prevent range errors.
1758 ##### Enforcement
1760 * (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.
1761 * (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.
1763 ### <a name="Ri-global-init"></a>I.22: Avoid complex initialization of global objects
1765 ##### Reason
1767 Complex initialization can lead to undefined order of execution.
1769 ##### Example
1771     // file1.c
1773     extern const X x;
1775     const Y y = f(x);   // read x; write y
1777     // file2.c
1779     extern const Y y;
1781     const X x = g(y);   // read y; write x
1783 Since `x` and `y` are in different translation units the order of calls to `f()` and `g()` is undefined;
1784 one will access an uninitialized `const`.
1785 This particular example shows that the order-of-initialization problem for global (namespace scope) objects is not limited to global *variables*.
1787 ##### Note
1789 Order of initialization problems become particularly difficult to handle in concurrent code.
1790 It is usually best to avoid global (namespace scope) objects altogether.
1792 ##### Enforcement
1794 * Flag initializers of globals that call non-`constexpr` functions
1795 * Flag initializers of globals that access `extern` objects
1797 ### <a name="Ri-nargs"></a>I.23: Keep the number of function arguments low
1799 ##### Reason
1801 Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.
1803 ##### Example
1805 The standard-library `merge()` is at the limit of what we can comfortably handle
1807     template<class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
1808     OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
1809                          InputIterator2 first2, InputIterator2 last2,
1810                          OutputIterator result, Compare comp);
1812 Here, we have four template arguments and six function arguments.
1813 To simplify the most frequent and simplest uses, the comparison argument can be defaulted to `<`:
1815     template<class InputIterator1, class InputIterator2, class OutputIterator>
1816     OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
1817                          InputIterator2 first2, InputIterator2 last2,
1818                          OutputIterator result);
1820 This doesn't reduce the total complexity, but it reduces the surface complexity presented to many users.
1821 To really reduce the number of arguments, we need to bundle the arguments into higher-level abstractions:
1823     template<class InputRange1, class InputRange2, class OutputIterator>
1824     OutputIterator merge(InputRange1 r1, InputRange2 r2, OutputIterator result);
1826 Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking.
1828 Alternatively, we could use concepts (as defined by the ISO TS) to define the notion of three types that must be usable for merging:
1830     Mergeable{In1 In2, Out}
1831     OutputIterator merge(In1 r1, In2 r2, Out result);
1833 ##### Note
1835 How many arguments are too many? Four arguments is a lot.
1836 There are functions that are best expressed with four individual arguments, but not many.
1838 **Alternative**: Group arguments into meaningful objects and pass the objects (by value or by reference).
1840 **Alternative**: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments.
1842 ##### Enforcement
1844 * Warn when a functions declares two iterators (including pointers) of the same type instead of a range or a view.
1845 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
1847 ### <a name="Ri-unrelated"></a>I.24: Avoid adjacent unrelated parameters of the same type
1849 ##### Reason
1851 Adjacent arguments of the same type are easily swapped by mistake.
1853 ##### Example, bad
1855 Consider:
1857     void copy_n(T* p, T* q, int n);  // copy from [p:p+n) to [q:q+n)
1859 This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.
1861 Use `const` for the "from" argument:
1863     void copy_n(const T* p, T* q, int n);  // copy from [p:p+n) to [q:q+n)
1865 ##### Exception
1867 If the order of the parameters is not important, there is no problem:
1869     int max(int a, int b);
1871 ##### Alternative
1873 Don't pass arrays as pointers, pass an object representing a range (e.g., a `span`):
1875     void copy_n(span<const T> p, span<T> q);  // copy from p to q
1877 ##### Alternative
1879 Define a `struct` as the parameter type and name the fields for those parameters accordingly:
1881     struct SystemParams {
1882         string config_file;
1883         string output_path;
1884         seconds timeout;
1885     };
1886     void initialize(SystemParams p);
1888 This has a tendency to make invocations of this clear to future readers, as the parameters
1889 are often filled in by name at the call site.
1891 ##### Enforcement
1893 (Simple) Warn if two consecutive parameters share the same type.
1895 ### <a name="Ri-abstract"></a>I.25: Prefer abstract classes as interfaces to class hierarchies
1897 ##### Reason
1899 Abstract classes are more likely to be stable than base classes with state.
1901 ##### Example, bad
1903 You just knew that `Shape` would turn up somewhere :-)
1905     class Shape {  // bad: interface class loaded with data
1906     public:
1907         Point center() const { return c; }
1908         virtual void draw() const;
1909         virtual void rotate(int);
1910         // ...
1911     private:
1912         Point c;
1913         vector<Point> outline;
1914         Color col;
1915     };
1917 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:
1919     class Shape {    // better: Shape is a pure interface
1920     public:
1921         virtual Point center() const = 0;   // pure virtual function
1922         virtual void draw() const = 0;
1923         virtual void rotate(int) = 0;
1924         // ...
1925         // ... no data members ...
1926     };
1928 ##### Enforcement
1930 (Simple) Warn if a pointer to a class `C` is assigned to a pointer to a base of `C` and the base class contains data members.
1932 ### <a name="Ri-abi"></a>I.26: If you want a cross-compiler ABI, use a C-style subset
1934 ##### Reason
1936 Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.
1938 ##### Exception
1940 You can carefully craft an interface using a few carefully selected higher-level C++ types. See ???.
1942 ##### Exception
1944 Common ABIs are emerging on some platforms freeing you from the more draconian restrictions.
1946 ##### Note
1948 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.
1950 ##### Enforcement
1952 (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
1954 # <a name="S-functions"></a>F: Functions
1956 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.
1958 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.
1959 Functions are the most critical part in most interfaces, so see the interface rules.
1961 Function rule summary:
1963 Function definition rules:
1965 * [F.1: "Package" meaningful operations as carefully named functions](#Rf-package)
1966 * [F.2: A function should perform a single logical operation](#Rf-logical)
1967 * [F.3: Keep functions short and simple](#Rf-single)
1968 * [F.4: If a function may have to be evaluated at compile time, declare it `constexpr`](#Rf-constexpr)
1969 * [F.5: If a function is very small and time-critical, declare it inline](#Rf-inline)
1970 * [F.6: If your function may not throw, declare it `noexcept`](#Rf-noexcept)
1971 * [F.7: For general use, take `T*` or `T&` arguments rather than smart pointers](#Rf-smart)
1972 * [F.8: Prefer pure functions](#Rf-pure)
1974 Parameter passing expression rules:
1976 * [F.15: Prefer simple and conventional ways of passing information](#Rf-conventional)
1977 * [F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`](#Rf-in)
1978 * [F.17: For "in-out" parameters, pass by reference to non-`const`](#Rf-inout)
1979 * [F.18: For "consume" parameters, pass by `X&&` and `std::move` the parameter](#Rf-consume)
1980 * [F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter](#Rf-forward)
1981 * [F.20: For "out" output values, prefer return values to output parameters](#Rf-out)
1982 * [F.21: To return multiple "out" values, prefer returning a tuple or struct](#Rf-out-multi)
1983 * [F.60: Prefer `T*` over `T&` when "no argument" is a valid option](#Rf-ptr-ref)
1985 Parameter passing semantic rules:
1987 * [F.22: Use `T*` or `owner<T*>` or a smart pointer to designate a single object](#Rf-ptr)
1988 * [F.23: Use a `not_null<T>` to indicate "null" is not a valid value](#Rf-nullptr)
1989 * [F.24: Use a `span<T>` or a `span_p<T>` to designate a half-open sequence](#Rf-range)
1990 * [F.25: Use a `zstring` or a `not_null<zstring>` to designate a C-style string](#Rf-string)
1991 * [F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed](#Rf-unique_ptr)
1992 * [F.27: Use a `shared_ptr<T>` to share ownership](#Rf-shared_ptr)
1994 Value return semantic rules:
1996 * [F.42: Return a `T*` to indicate a position (only)](#Rf-return-ptr)
1997 * [F.43: Never (directly or indirectly) return a pointer or a reference to a local object](#Rf-dangle)
1998 * [F.44: Return a `T&` when copy is undesirable and "returning no object" isn't an option](#Rf-return-ref)
1999 * [F.45: Don't return a `T&&`](#Rf-return-ref-ref)
2000 * [F.46: `int` is the return type for `main()`](#Rf-main)
2001 * [F.47: Return `T&` from assignment operators.](#Rf-assignment-op)
2003 Other function rules:
2005 * [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)
2006 * [F.51: Where there is a choice, prefer default arguments over overloading](#Rf-default-args)
2007 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
2008 * [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)
2009 * [F.54: If you capture `this`, capture all variables explicitly (no default capture)](#Rf-this-capture)
2011 Functions have strong similarities to lambdas and function objects so see also Section ???.
2013 ## <a name="SS-fct-def"></a>F.def: Function definitions
2015 A function definition is a function declaration that also specifies the function's implementation, the function body.
2017 ### <a name="Rf-package"></a>F.1: "Package" meaningful operations as carefully named functions
2019 ##### Reason
2021 Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code.
2022 If something is a well-specified action, separate it out from its surrounding code and give it a name.
2024 ##### Example, don't
2026     void read_and_print(istream& is)    // read and print an int
2027     {
2028         int x;
2029         if (is >> x)
2030             cout << "the int is " << x << '\n';
2031         else
2032             cerr << "no int on input\n";
2033     }
2035 Almost everything is wrong with `read_and_print`.
2036 It reads, it writes (to a fixed `ostream`), it writes error messages (to a fixed `ostream`), it handles only `int`s.
2037 There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use.
2038 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
2039 mess could become hard to understand.
2041 ##### Note
2043 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.
2045 ##### Example
2047     sort(a, b, [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); });
2049 Naming that lambda breaks up the expression into its logical parts and provides a strong hint to the meaning of the lambda.
2051     auto lessT = [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); };
2053     sort(a, b, lessT);
2054     find_if(a, b, lessT);
2056 The shortest code is not always the best for performance or maintainability.
2058 ##### Exception
2060 Loop bodies, including lambdas used as loop bodies, rarely need to be named.
2061 However, large loop bodies (e.g., dozens of lines or dozens of pages) can be a problem.
2062 The rule [Keep functions short](#Rf-single) implies "Keep loop bodies short."
2063 Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unlikely to be re-usable.
2065 ##### Enforcement
2067 * See [Keep functions short](#Rf-single)
2068 * Flag identical and very similar lambdas used in different places.
2070 ### <a name="Rf-logical"></a>F.2: A function should perform a single logical operation
2072 ##### Reason
2074 A function that performs a single operation is simpler to understand, test, and reuse.
2076 ##### Example
2078 Consider:
2080     void read_and_print()    // bad
2081     {
2082         int x;
2083         cin >> x;
2084         // check for errors
2085         cout << x << "\n";
2086     }
2088 This is a monolith that is tied to a specific input and will never find a another (different) use. Instead, break functions up into suitable logical parts and parameterize:
2090     int read(istream& is)    // better
2091     {
2092         int x;
2093         is >> x;
2094         // check for errors
2095         return x;
2096     }
2098     void print(ostream& os, int x)
2099     {
2100         os << x << "\n";
2101     }
2103 These can now be combined where needed:
2105     void read_and_print()
2106     {
2107         auto x = read(cin);
2108         print(cout, x);
2109     }
2111 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:
2113     auto read = [](auto& input, auto& value)    // better
2114     {
2115         input >> value;
2116         // check for errors
2117     };
2119     auto print(auto& output, const auto& value)
2120     {
2121         output << value << "\n";
2122     }
2124 ##### Enforcement
2126 * Consider functions with more than one "out" parameter suspicious. Use return values instead, including `tuple` for multiple return values.
2127 * Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
2128 * Consider functions with 7 or more parameters suspicious.
2130 ### <a name="Rf-single"></a>F.3: Keep functions short and simple
2132 ##### Reason
2134 Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes.
2135 Functions with complex control structures are more likely to be long and more likely to hide logical errors
2137 ##### Example
2139 Consider:
2141     double simpleFunc(double val, int flag1, int flag2)
2142         // simpleFunc: takes a value and calculates the expected ASIC output,
2143         // given the two mode flags.
2144     {
2145         double intermediate;
2146         if (flag1 > 0) {
2147             intermediate = func1(val);
2148             if (flag2 % 2)
2149                  intermediate = sqrt(intermediate);
2150         }
2151         else if (flag1 == -1) {
2152             intermediate = func1(-val);
2153             if (flag2 % 2)
2154                  intermediate = sqrt(-intermediate);
2155             flag1 = -flag1;
2156         }
2157         if (abs(flag2) > 10) {
2158             intermediate = func2(intermediate);
2159         }
2160         switch (flag2 / 10) {
2161             case 1: if (flag1 == -1) return finalize(intermediate, 1.171);
2162                     break;
2163             case 2: return finalize(intermediate, 13.1);
2164             default: break;
2165         }
2166         return finalize(intermediate, 0.);
2167     }
2169 This is too complex (and also pretty long).
2170 How would you know if all possible alternatives have been correctly handled?
2171 Yes, it breaks other rules also.
2173 We can refactor:
2175     double func1_muon(double val, int flag)
2176     {
2177         // ???
2178     }
2180     double funct1_tau(double val, int flag1, int flag2)
2181     {
2182         // ???
2183     }
2185     double simpleFunc(double val, int flag1, int flag2)
2186         // simpleFunc: takes a value and calculates the expected ASIC output,
2187         // given the two mode flags.
2188     {
2189         if (flag1 > 0)
2190             return func1_muon(val, flag2);
2191         if (flag1 == -1)
2192             // handled by func1_tau: flag1 = -flag1;
2193             return func1_tau(-val, flag1, flag2);
2194         return 0.;
2195     }
2197 ##### Note
2199 "It doesn't fit on a screen" is often a good practical definition of "far too large."
2200 One-to-five-line functions should be considered normal.
2202 ##### Note
2204 Break large functions up into smaller cohesive and named functions.
2205 Small simple functions are easily inlined where the cost of a function call is significant.
2207 ##### Enforcement
2209 * Flag functions that do not "fit on a screen."
2210   How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
2211 * Flag functions that are too complex. How complex is too complex?
2212   You could use cyclomatic complexity. Try "more than 10 logical path through." Count a simple switch as one path.
2214 ### <a name="Rf-constexpr"></a>F.4: If a function may have to be evaluated at compile time, declare it `constexpr`
2216 ##### Reason
2218  `constexpr` is needed to tell the compiler to allow compile-time evaluation.
2220 ##### Example
2222 The (in)famous factorial:
2224     constexpr int fac(int n)
2225     {
2226         constexpr int max_exp = 17;      // constexpr enables max_exp to be used in Expects
2227         Expects(0 <= n && n < max_exp);  // prevent silliness and overflow
2228         int x = 1;
2229         for (int i = 2; i <= n; ++i) x *= i;
2230         return x;
2231     }
2233 This is C++14.
2234 For C++11, use a recursive formulation of `fac()`.
2236 ##### Note
2238 `constexpr` does not guarantee compile-time evaluation;
2239 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.
2241     constexpr int min(int x, int y) { return x < y ? x : y; }
2243     void test(int v)
2244     {
2245         int m1 = min(-1, 2);            // probably compile-time evaluation
2246         constexpr int m2 = min(-1, 2);  // compile-time evaluation
2247         int m3 = min(-1, v);            // run-time evaluation
2248         constexpr int m4 = min(-1, v);  // error: cannot evaluate at compile-time
2249     }
2251 ##### Note
2253 `constexpr` functions are pure: they can have no side effects.
2255     int dcount = 0;
2256     constexpr int double(int v)
2257     {
2258         ++dcount;   // error: attempted side effect from constexpr function
2259         return v + v;
2260     }
2262 This is usually a very good thing.
2264 When given a non-constant argument, a `constexpr` function can throw.
2265 If you consider exiting by throwing a side-effect, a `constexpr` function isn't completely pure;
2266 if not, this is not an issue.
2267 ??? A question for the committee: can a constructor for an exception thrown by a `constexpr` function modify state?
2268 "No" would be a nice answer that matches most practice.
2270 ##### Note
2272 Don't try to make all functions `constexpr`.
2273 Most computation is best done at run time.
2275 ##### Note
2277 Any API that may eventually depend on high-level runtime configuration or
2278 business logic should not be made `constexpr`. Such customization can not be
2279 evaluated by the compiler, and any `constexpr` functions that depend upon that
2280 API will have to be refactored or drop `constexpr`.
2282 ##### Enforcement
2284 Impossible and unnecessary.
2285 The compiler gives an error if a non-`constexpr` function is called where a constant is required.
2287 ### <a name="Rf-inline"></a>F.5: If a function is very small and time-critical, declare it `inline`
2289 ##### Reason
2291 Some optimizers are good at inlining without hints from the programmer, but don't rely on it.
2292 Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans.
2293 We are still waiting.
2294 Specifying `inline` encourages the compiler to do a better job.
2296 ##### Example
2298     inline string cat(const string& s, const string& s2) { return s + s2; }
2300 ##### Exception
2302 Do not put an `inline` function in what is meant to be a stable interface unless you are really sure that it will not change.
2303 An inline function is part of the ABI.
2305 ##### Note
2307 `constexpr` implies `inline`.
2309 ##### Note
2311 Member functions defined in-class are `inline` by default.
2313 ##### Exception
2315 Template functions (incl. template member functions) must be in headers and therefore inline.
2317 ##### Enforcement
2319 Flag `inline` functions that are more than three statements and could have been declared out of line (such as class member functions).
2321 ### <a name="Rf-noexcept"></a>F.6: If your function may not throw, declare it `noexcept`
2323 ##### Reason
2325 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.
2327 ##### Example
2329 Put `noexcept` on every function written completely in C or in any other language without exceptions.
2330 The C++ standard library does that implicitly for all functions in the C standard library.
2332 ##### Note
2334 `constexpr` functions cannot throw, so you don't need to use `noexcept` for those.
2336 ##### Example
2338 You can use `noexcept` even on functions that can throw:
2340     vector<string> collect(istream& is) noexcept
2341     {
2342         vector<string> res;
2343         for (string s; is >> s;)
2344             res.push_back(s);
2345         return res;
2346     }
2348 If `collect()` runs out of memory, the program crashes.
2349 Unless the program is crafted to survive memory exhaustion, that may be just the right thing to do;
2350 `terminate()` may generate suitable error log information (but after memory runs out it is hard to do anything clever).
2352 ##### Note
2354 You must be aware of the execution environment that your code is running when
2355 deciding whether to tag a function `noexcept`, especially because of the issue
2356 of throwing and allocation.  Code that is intended to be perfectly general (like
2357 the standard library and other utility code of that sort) needs to support
2358 environments where a `bad_alloc` exception may be handled meaningfully.
2359 However, the majority of programs and execution environments cannot meaningfully
2360 handle a failure to allocate, and aborting the program is the cleanest and
2361 simplest response to an allocation failure in those cases.  If you know that
2362 your application code cannot respond to an allocation failure, it may be
2363 appropriate to add `noexcept` even on functions that allocate.
2365 Put another way: In most programs, most functions can throw (e.g., because they
2366 use `new`, call functions that do, or use library functions that reports failure
2367 by throwing), so don't just sprinkle `noexcept` all over the place without
2368 considering whether the possible exceptions can be handled.
2370 `noexcept` is most useful (and most clearly correct) for frequently used,
2371 low-level functions.
2373 ##### Note
2375 Destructors, `swap` functions, move operations, and default constructors should never throw.
2377 ##### Enforcement
2379 * Flag functions that are not `noexcept`, yet cannot throw.
2380 * Flag throwing `swap`, `move`, destructors, and default constructors.
2382 ### <a name="Rf-smart"></a>F.7: For general use, take `T*` or `T&` arguments rather than smart pointers
2384 ##### Reason
2386 Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended (see [R.30](#Rr-smartptrparam)).
2387 Passing by smart pointer restricts the use of a function to callers that use smart pointers.
2388 Passing a shared smart pointer (e.g., `std::shared_ptr`) implies a run-time cost.
2390 ##### Example
2392     // accepts any int*
2393     void f(int*);
2395     // can only accept ints for which you want to transfer ownership
2396     void g(unique_ptr<int>);
2398     // can only accept ints for which you are willing to share ownership
2399     void g(shared_ptr<int>);
2401     // doesn't change ownership, but requires a particular ownership of the caller
2402     void h(const unique_ptr<int>&);
2404     // accepts any int
2405     void h(int&);
2407 ##### Example, bad
2409     // callee
2410     void f(shared_ptr<widget>& w)
2411     {
2412         // ...
2413         use(*w); // only use of w -- the lifetime is not used at all
2414         // ...
2415     };
2417 See further in [R.30](#Rr-smartptrparam).
2419 ##### Note
2421 We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers.
2423 **See also**: [when to prefer `T*` and when to prefer `T&`](#Rf-ptr-ref).
2425 **See also**: Discussion of [smart pointer use](#Rr-summary-smartptrs).
2427 ##### Enforcement
2429 Flag a parameter of a smart pointer type (a type that overloads `operator->` or `operator*`) for which the ownership semantics are not used;
2430 that is
2432 * copyable but never copied/moved from or movable but never moved
2433 * and that is never modified or passed along to another function that could do so.
2435 ### <a name="Rf-pure"></a>F.8: Prefer pure functions
2437 ##### Reason
2439 Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.
2441 ##### Example
2443     template<class T>
2444     auto square(T t) { return t * t; }
2446 ##### Note
2448 `constexpr` functions are pure.
2450 When given a non-constant argument, a `constexpr` function can throw.
2451 If you consider exiting by throwing a side-effect, a `constexpr` function isn't completely pure;
2452 if not, this is not an issue.
2453 ??? A question for the committee: can a constructor for an exception thrown by a `constexpr` function modify state?
2454 "No" would be a nice answer that matches most practice.
2456 ##### Enforcement
2458 Not possible.
2460 ## <a name="SS-call"></a>F.call: Parameter passing
2462 There are a variety of ways to pass parameters to a function and to return values.
2464 ### <a name="Rf-conventional"></a>F.15: Prefer simple and conventional ways of passing information
2466 ##### Reason
2468 Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs.
2469 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.
2471 The following tables summarize the advice in the following Guidelines, F.16-21.
2473 Normal parameter passing:
2475 ![Normal parameter passing table](./param-passing-normal.png "Normal parameter passing")
2477 Advanced parameter passing:
2479 ![Advanced parameter passing table](./param-passing-advanced.png "Advanced parameter passing")
2481 Use the advanced techniques only after demonstrating need, and document that need in a comment.
2483 ### <a name="Rf-in"></a>F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`
2485 ##### Reason
2487 Both let the caller know that a function will not modify the argument, and both allow initialization by rvalues.
2489 What is "cheap to copy" depends on the machine architecture, but two or three words (doubles, pointers, references) are usually best passed by value.
2490 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.
2492 ##### Example
2494     void f1(const string& s);  // OK: pass by reference to const; always cheap
2496     void f2(string s);         // bad: potentially expensive
2498     void f3(int x);            // OK: Unbeatable
2500     void f4(const int& x);     // bad: overhead on access in f4()
2502 For advanced uses (only), where you really need to optimize for rvalues passed to "input-only" parameters:
2504 * If the function is going to unconditionally move from the argument, take it by `&&`. See [F.18](#Rf-consume).
2505 * If the function is going to keep a copy of the argument, in addition to passing by `const&` (for lvalues),
2506   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 "consume"; see [F.18](#Rf-consume).
2507 * In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. See [F.19](#Rf-forward).
2509 ##### Example
2511     int multiply(int, int); // just input ints, pass by value
2513     // suffix is input-only but not as cheap as an int, pass by const&
2514     string& concatenate(string&, const string& suffix);
2516     void sink(unique_ptr<widget>);  // input only, and consumes the widget
2518 Avoid "esoteric techniques" such as:
2520 * Passing arguments as `T&&` "for efficiency".
2521   Most rumors about performance advantages from passing by `&&` are false or brittle (but see [F.25](#Rf-pass-ref-move).)
2522 * Returning `const T&` from assignments and similar operations (see [F.47](#Rf-assignment-op).)
2524 ##### Example
2526 Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`):
2528     Matrix operator+(const Matrix& a, const Matrix& b)
2529     {
2530         Matrix res;
2531         // ... fill res with the sum ...
2532         return res;
2533     }
2535     Matrix x = m1 + m2;  // move constructor
2537     y = m3 + m3;         // move assignment
2539 ##### Notes
2541 The return value optimization doesn't handle the assignment case, but the move assignment does.
2543 A reference may be assumed to refer to a valid object (language rule).
2544 There is no (legitimate) "null reference."
2545 If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value."
2547 ##### Enforcement
2549 * (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than `4 * sizeof(int)`.
2550   Suggest using a reference to `const` instead.
2551 * (Simple) ((Foundation)) Warn when a `const` parameter being passed by reference has a size less than `3 * sizeof(int)`. Suggest passing by value instead.
2552 * (Simple) ((Foundation)) Warn when a `const` parameter being passed by reference is `move`d.
2554 ### <a name="Rf-inout"></a>F.17: For "in-out" parameters, pass by reference to non-`const`
2556 ##### Reason
2558 This makes it clear to callers that the object is assumed to be modified.
2560 ##### Example
2562     void update(Record& r);  // assume that update writes to r
2564 ##### Note
2566 A `T&` argument can pass information into a function as well as well as out of it.
2567 Thus `T&` could be an in-out-parameter. That can in itself be a problem and a source of errors:
2569     void f(string& s)
2570     {
2571         s = "New York";  // non-obvious error
2572     }
2574     void g()
2575     {
2576         string buffer = ".................................";
2577         f(buffer);
2578         // ...
2579     }
2581 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).
2582 If the writer of `g()` makes an assumption about the size of `buffer` a bad logic error can happen.
2584 ##### Enforcement
2586 * (Moderate) ((Foundation)) Warn about functions with reference to non-`const` parameters that do *not* write to them.
2587 * (Simple) ((Foundation)) Warn when a non-`const` parameter being passed by reference is `move`d.
2589 ### <a name="Rf-consume"></a>F.18: For "consume" parameters, pass by `X&&` and `std::move` the parameter
2591 ##### Reason
2593 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.
2595 ##### Example
2597     void sink(vector<int>&& v) {   // sink takes ownership of whatever the argument owned
2598         // usually there might be const accesses of v here
2599         store_somewhere(std::move(v));
2600         // usually no more use of v here; it is moved-from
2601     }
2603 Note that the `std::move(v)` makes it possible for `store_somewhere()` to leave `v` in a moved-from state.
2604 [That could be dangerous](#Rc-move-semantic).
2607 ##### Exception
2609 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.
2611 For example:
2613     template <class T>
2614     void sink(std::unique_ptr<T> p) {
2615         // use p ... possibly std::move(p) onward somewhere else
2616     }   // p gets destroyed
2618 ##### Enforcement
2620 * Flag all `X&&` parameters (where `X` is not a template type parameter name) where the function body uses them without `std::move`.
2621 * Flag access to moved-from objects.
2622 * Don't conditionally move from objects
2624 ### <a name="Rf-forward"></a>F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter
2626 ##### Reason
2628 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.
2630 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.
2632 ##### Example
2634     template <class F, class... Args>
2635     inline auto invoke(F f, Args&&... args) {
2636         return f(forward<Args>(args)...);
2637     }
2639     ??? calls ???
2641 ##### Enforcement
2643 * 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.
2645 ### <a name="Rf-out"></a>F.20: For "out" output values, prefer return values to output parameters
2647 ##### Reason
2649 A return value is self-documenting, whereas a `&` could be either in-out or out-only and is liable to be misused.
2651 This includes large objects like standard containers that use implicit move operations for performance and to avoid explicit memory management.
2653 If you have multiple values to return, [use a tuple](#Rf-out-multi) or similar multi-member type.
2655 ##### Example
2657     // OK: return pointers to elements with the value x
2658     vector<const int*> find_all(const vector<int>&, int x);
2660     // Bad: place pointers to elements with value x in out
2661     void find_all(const vector<int>&, vector<const int*>& out, int x);
2663 ##### Note
2665 A `struct` of many (individually cheap-to-move) elements may be in aggregate expensive to move.
2667 It is not recommended to return a `const` value.
2668 Such older advice is now obsolete; it does not add value, and it interferes with move semantics.
2670     const vector<int> fct();    // bad: that "const" is more trouble than it is worth
2672     vector<int> g(const vector<int>& vx)
2673     {
2674         // ...
2675         f() = vx;   // prevented by the "const"
2676         // ...
2677         return f(); // expensive copy: move semantics suppressed by the "const"
2678     }
2680 The argument for adding `const` to a return value is that it prevents (very rare) accidental access to a temporary.
2681 The argument against is prevents (very frequent) use of move semantics.
2683 ##### Exceptions
2685 * For non-value types, such as types in an inheritance hierarchy, return the object by `unique_ptr` or `shared_ptr`.
2686 * 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).
2687 * 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).
2689 ##### Example
2691     struct Package {      // exceptional case: expensive-to-move object
2692         char header[16];
2693         char load[2024 - 16];
2694     };
2696     Package fill();       // Bad: large return value
2697     void fill(Package&);  // OK
2699     int val();            // OK
2700     void val(int&);       // Bad: Is val reading its argument
2702 ##### Enforcement
2704 * 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.
2705 * Flag returning a `const` value. To fix: Remove `const` to return a non-`const` value instead.
2707 ### <a name="Rf-out-multi"></a>F.21: To return multiple "out" values, prefer returning a tuple or struct
2709 ##### Reason
2711 A return value is self-documenting as an "output-only" value.
2712 Note that C++ does have multiple return values, by convention of using a `tuple`,
2713 possibly with the extra convenience of `tie` at the call site.
2715 ##### Example
2717     // BAD: output-only parameter documented in a comment
2718     int f(const string& input, /*output only*/ string& output_data)
2719     {
2720         // ...
2721         output_data = something();
2722         return status;
2723     }
2725     // GOOD: self-documenting
2726     tuple<int, string> f(const string& input)
2727     {
2728         // ...
2729         return make_tuple(status, something());
2730     }
2732 C++98's standard library already used this style, because a `pair` is like a two-element `tuple`.
2733 For example, given a `set<string> my_set`, consider:
2735     // C++98
2736     result = my_set.insert("Hello");
2737     if (result.second) do_something_with(result.first);    // workaround
2739 With C++11 we can write this, putting the results directly in existing local variables:
2741     Sometype iter;                                // default initialize if we haven't already
2742     Someothertype success;                        // used these variables for some other purpose
2744     tie(iter, success) = my_set.insert("Hello");   // normal return value
2745     if (success) do_something_with(iter);
2747 With C++17 we should be able to use "structured bindings" to declare and initialize the multiple variables:
2749     if (auto [ iter, success ] = my_set.insert("Hello"); success) do_something_with(iter);
2751 ##### Exception
2753 Sometimes, we need to pass an object to a function to manipulate its state.
2754 In such cases, passing the object by reference [`T&`](#Rf-inout) is usually the right technique.
2755 Explicitly passing an in-out parameter back out again as a return value is often not necessary.
2756 For example:
2758     istream& operator>>(istream& is, string& s);    // much like std::operator>>()
2760     for (string s; cin >> s; ) {
2761         // do something with line
2762     }
2764 Here, both `s` and `cin` are used as in-out parameters.
2765 We pass `cin` by (non-`const`) reference to be able to manipulate its state.
2766 We pass `s` to avoid repeated allocations.
2767 By reusing `s` (passed by reference), we allocate new memory only when we need to expand `s`'s capacity.
2768 This technique is sometimes called the "caller-allocated out" pattern and is particularly useful for types,
2769 such as `string` and `vector`, that needs to do free store allocations.
2771 To compare, if we passed out all values as return values, we would something like this:
2773     pair<istream&, string> get_string(istream& is);  // not recommended
2774     {
2775         string s;
2776         cin >> s;
2777         return {is, s};
2778     }
2780     for (auto p = get_string(cin); p.first; ) {
2781         // do something with p.second
2782     }
2784 We consider that significantly less elegant and definitely significantly slower.
2786 For a really strict reading this rule (F.21), the exceptions isn't really an exception because it relies on in-out parameters,
2787 rather than the plain out parameters mentioned in the rule.
2788 However, we prefer to be explicit, rather than subtle.
2790 ##### Note
2792 In many cases it may be useful to return a specific, user-defined "Value or error" type.
2793 For example:
2795     struct
2797 The overly-generic `pair` and `tuple` should be used only when the value returned represents to independent entities rather than an abstraction.
2799 type along the lines of `variant<T, error_code>`, rather than using the generic `tuple`.
2801 ##### Enforcement
2803 * Output parameters should be replaced by return values.
2804   An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`.
2806 ### <a name="Rf-ptr"></a>F.22: Use `T*` or `owner<T*>` to designate a single object
2808 ##### Reason
2810 Readability: it makes the meaning of a plain pointer clear.
2811 Enables significant tool support.
2813 ##### Note
2815 In traditional C and C++ code, plain `T*` is used for many weakly-related purposes, such as:
2817 * Identify a (single) object (not to be deleted by this function)
2818 * Point to an object allocated on the free store (and delete it later)
2819 * Hold the `nullptr`
2820 * Identify a C-style string (zero-terminated array of characters)
2821 * Identify an array with a length specified separately
2822 * Identify a location in an array
2824 This makes it hard to understand what the code does and is supposed to do.
2825 It complicates checking and tool support.
2827 ##### Example
2829     void use(int* p, int n, char* s, int* q)
2830     {
2831         p[n - 1] = 666; // Bad: we don't know if p points to n elements;
2832                         // assume it does not or use span<int>
2833         cout << s;      // Bad: we don't know if that s points to a zero-terminated array of char;
2834                         // assume it does not or use zstring
2835         delete q;       // Bad: we don't know if *q is allocated on the free store;
2836                         // assume it does not or use owner
2837     }
2839 better
2841     void use2(span<int> p, zstring s, owner<int*> q)
2842     {
2843         p[p.size() - 1] = 666; // OK, a range error can be caught
2844         cout << s; // OK
2845         delete q;  // OK
2846     }
2848 ##### Note
2850 `owner<T*>` represents ownership, `zstring` represents a C-style string.
2852 **Also**: Assume that a `T*` obtained from a smart pointer to `T` (e.g., `unique_ptr<T>`) points to a single element.
2854 **See also**: [Support library](#S-gsl).
2856 ##### Enforcement
2858 * (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
2860 ### <a name="Rf-nullptr"></a>F.23: Use a `not_null<T>` to indicate that "null" is not a valid value
2862 ##### Reason
2864 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.
2865 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`.
2867 ##### Example
2869 `not_null<T*>` makes it obvious to a reader (human or machine) that a test for `nullptr` is not necessary before dereference.
2870 Additionally, when debugging, `owner<T*>` and `not_null<T>` can be instrumented to check for correctness.
2872 Consider:
2874     int length(Record* p);
2876 When I call `length(p)` should I test for `p == nullptr` first? Should the implementation of `length()` test for `p == nullptr`?
2878     // it is the caller's job to make sure p != nullptr
2879     int length(not_null<Record*> p);
2881     // the implementor of length() must assume that p == nullptr is possible
2882     int length(Record* p);
2884 ##### Note
2886 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).
2888 ##### Note
2890 `not_null` is not just for built-in pointers. It works for `unique_ptr`, `shared_ptr`, and other pointer-like types.
2892 ##### Enforcement
2894 * (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.
2895 * (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against `nullptr` (or equivalent) within the function and sometimes is not.
2896 * (Simple) Warn if a `not_null` pointer is tested against `nullptr` within a function.
2898 ### <a name="Rf-range"></a>F.24: Use a `span<T>` or a `span_p<T>` to designate a half-open sequence
2900 ##### Reason
2902 Informal/non-explicit ranges are a source of errors.
2904 ##### Example
2906     X* find(span<X> r, const X& v);    // find v in r
2908     vector<X> vec;
2909     // ...
2910     auto p = find({vec.begin(), vec.end()}, X{});  // find X{} in vec
2912 ##### Note
2914 Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure.
2915 In particular, given a pair of arguments `(p, n)` designating an array \[`p`:`p+n`),
2916 it is in general impossible to know if there really are `n` elements to access following `*p`.
2917 `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.
2919 ##### Example
2921 A `span` represents a range of elements, but how do we manipulate elements of that range?
2923     void f(span<int> s)
2924     {
2925         // range traversal (guaranteed correct)
2926         for (int x : s) cout << x << '\n';
2928         // C-style traversal (potentially checked)
2929         for (int i = 0; i < s.size(); ++i) cout << s[i] << '\n';
2931         // random access (potentially checked)
2932         s[7] = 9;
2934         // extract pointers (potentially checked)
2935         std::sort(&s[0], &s[s.size() / 2]);
2936     }
2938 ##### Note
2940 A `span<T>` object does not own its elements and is so small that it can be passed by value.
2942 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.
2944 **See also**: [Support library](#S-gsl).
2946 ##### Enforcement
2948 (Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `span` instead.
2950 ### <a name="Rf-string"></a>F.25: Use a `zstring` or a `not_null<zstring>` to designate a C-style string
2952 ##### Reason
2954 C-style strings are ubiquitous. They are defined by convention: zero-terminated arrays of characters.
2955 We must distinguish C-style strings from a pointer to a single character or an old-fashioned pointer to an array of characters.
2957 ##### Example
2959 Consider:
2961     int length(const char* p);
2963 When I call `length(s)` should I test for `s == nullptr` first? Should the implementation of `length()` test for `p == nullptr`?
2965     // the implementor of length() must assume that p == nullptr is possible
2966     int length(zstring p);
2968     // it is the caller's job to make sure p != nullptr
2969     int length(not_null<zstring> p);
2971 ##### Note
2973 `zstring` do not represent ownership.
2975 **See also**: [Support library](#S-gsl).
2977 ### <a name="Rf-unique_ptr"></a>F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed
2979 ##### Reason
2981 Using `unique_ptr` is the cheapest way to pass a pointer safely.
2983 ##### Example
2985     unique_ptr<Shape> get_shape(istream& is)  // assemble shape from input stream
2986     {
2987         auto kind = read_header(is); // read header and identify the next shape on input
2988         switch (kind) {
2989         case kCircle:
2990             return make_unique<Circle>(is);
2991         case kTriangle:
2992             return make_unique<Triangle>(is);
2993         // ...
2994         }
2995     }
2997 ##### Note
2999 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).
3001 ##### Enforcement
3003 (Simple) Warn if a function returns a locally-allocated raw pointer. Suggest using either `unique_ptr` or `shared_ptr` instead.
3005 ### <a name="Rf-shared_ptr"></a>F.27: Use a `shared_ptr<T>` to share ownership
3007 ##### Reason
3009 Using `std::shared_ptr` is the standard way to represent shared ownership. That is, the last owner deletes the object.
3011 ##### Example
3013     shared_ptr<const Image> im { read_image(somewhere) };
3015     std::thread t0 {shade, args0, top_left, im};
3016     std::thread t1 {shade, args1, top_right, im};
3017     std::thread t2 {shade, args2, bottom_left, im};
3018     std::thread t3 {shade, args3, bottom_right, im};
3020     // detach threads
3021     // last thread to finish deletes the image
3023 ##### Note
3025 Prefer a `unique_ptr` over a `shared_ptr` if there is never more than one owner at a time.
3026 `shared_ptr` is for shared ownership.
3028 Note that pervasive use of `shared_ptr` has a cost (atomic operations on the `shared_ptr`'s reference count have a measurable aggregate cost).
3030 ##### Alternative
3032 Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.
3034 ##### Enforcement
3036 (Not enforceable) This is a too complex pattern to reliably detect.
3038 ### <a name="Rf-ptr-ref"></a>F.60: Prefer `T*` over `T&` when "no argument" is a valid option
3040 ##### Reason
3042 A pointer (`T*`) can be a `nullptr` and a reference (`T&`) cannot, there is no valid "null reference".
3043 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.
3045 ##### Example
3047     string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string
3048     {
3049         if (p == nullptr) return string{};    // p might be nullptr; remember to check
3050         return string{p};
3051     }
3053     void print(const vector<int>& r)
3054     {
3055         // r refers to a vector<int>; no check needed
3056     }
3058 ##### Note
3060 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;`).
3061 That error is very uncommon.
3063 ##### Note
3065 If you prefer the pointer notation (`->` and/or `*` vs. `.`), `not_null<T*>` provides the same guarantee as `T&`.
3067 ##### Enforcement
3069 * Flag ???
3071 ### <a name="Rf-return-ptr"></a>F.42: Return a `T*` to indicate a position (only)
3073 ##### Reason
3075 That's what pointers are good for.
3076 Returning a `T*` to transfer ownership is a misuse.
3078 ##### Example
3080     Node* find(Node* t, const string& s)  // find s in a binary tree of Nodes
3081     {
3082         if (t == nullptr || t->name == s) return t;
3083         if ((auto p = find(t->left, s))) return p;
3084         if ((auto p = find(t->right, s))) return p;
3085         return nullptr;
3086     }
3088 If it isn't the `nullptr`, the pointer returned by `find` indicates a `Node` holding `s`.
3089 Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller.
3091 ##### Note
3093 Positions can also be transferred by iterators, indices, and references.
3094 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](???).
3096 ##### Note
3098 Do not return a pointer to something that is not in the caller's scope; see [F.43](#Rf-dangle).
3100 **See also**: [discussion of dangling pointer prevention](#???).
3102 ##### Enforcement
3104 * Flag `delete`, `std::free()`, etc. applied to a plain `T*`.
3105 Only owners should be deleted.
3106 * Flag `new`, `malloc()`, etc. assigned to a plain `T*`.
3107 Only owners should be responsible for deletion.
3109 ### <a name="Rf-dangle"></a>F.43: Never (directly or indirectly) return a pointer or a reference to a local object
3111 ##### Reason
3113 To avoid the crashes and data corruption that can result from the use of such a dangling pointer.
3115 ##### Example, bad
3117 After the return from a function its local objects no longer exist:
3119     int* f()
3120     {
3121         int fx = 9;
3122         return &fx;  // BAD
3123     }
3125     void g(int* p)   // looks innocent enough
3126     {
3127         int gx;
3128         cout << "*p == " << *p << '\n';
3129         *p = 999;
3130         cout << "gx == " << gx << '\n';
3131     }
3133     void h()
3134     {
3135         int* p = f();
3136         int z = *p;  // read from abandoned stack frame (bad)
3137         g(p);        // pass pointer to abandoned stack frame to function (bad)
3138     }
3140 Here on one popular implementation I got the output:
3142     *p == 999
3143     gx == 999
3145 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`.
3147 * Imagine what would happen if `fx` and `gx` were of different types.
3148 * Imagine what would happen if `fx` or `gx` was a type with an invariant.
3149 * Imagine what would happen if more that dangling pointer was passed around among a larger set of functions.
3150 * Imagine what a cracker could do with that dangling pointer.
3152 Fortunately, most (all?) modern compilers catch and warn against this simple case.
3154 ##### Note
3156 This applies to references as well:
3158     int& f()
3159     {
3160         int x = 7;
3161         // ...
3162         return x;  // Bad: returns reference to object that is about to be destroyed
3163     }
3165 ##### Note
3167 This applies only to non-`static` local variables.
3168 All `static` variables are (as their name indicates) statically allocated, so that pointers to them cannot dangle.
3170 ##### Example, bad
3172 Not all examples of leaking a pointer to a local variable are that obvious:
3174     int* glob;       // global variables are bad in so many ways
3176     template<class T>
3177     void steal(T x)
3178     {
3179         glob = x();  // BAD
3180     }
3182     void f()
3183     {
3184         int i = 99;
3185         steal([&] { return &i; });
3186     }
3188     int main()
3189     {
3190         f();
3191         cout << *glob << '\n';
3192     }
3194 Here I managed to read the location abandoned by the call of `f`.
3195 The pointer stored in `glob` could be used much later and cause trouble in unpredictable ways.
3197 ##### Note
3199 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.
3201 ##### Note
3203 Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one;
3204 such examples are handled equivalently to leaks of pointers out of a function.
3206 A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to.
3208 **See also**: Another way of getting dangling pointers is [pointer invalidation](#???).
3209 It can be detected/prevented with similar techniques.
3211 ##### Enforcement
3213 * Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals.
3214 * Static analysis can catch many common patterns of the use of pointers indicating positions (thus eliminating dangling pointers)
3216 ### <a name="Rf-return-ref"></a>F.44: Return a `T&` when copy is undesirable and "returning no object" isn't needed
3218 ##### Reason
3220 The language guarantees that a `T&` refers to an object, so that testing for `nullptr` isn't necessary.
3222 **See also**: The return of a reference must not imply transfer of ownership:
3223 [discussion of dangling pointer prevention](#???) and [discussion of ownership](#???).
3225 ##### Example
3227     class Car
3228     {
3229         array<wheel, 4> w;
3230         // ...
3231     public:
3232         wheel& get_wheel(size_t i) { Expects(i < 4); return w[i]; }
3233         // ...
3234     };
3236     void use()
3237     {
3238         Car c;
3239         wheel& w0 = c.get_wheel(0); // w0 has the same lifetime as c
3240     }
3242 ##### Enforcement
3244 Flag functions where no `return` expression could yield `nullptr`
3246 ### <a name="Rf-return-ref-ref"></a>F.45: Don't return a `T&&`
3248 ##### Reason
3250 It's asking to return a reference to a destroyed temporary object. A `&&` is a magnet for temporary objects. This is fine when the reference to the temporary is being passed "downward" to a callee, because the temporary is guaranteed to outlive the function call. (See [F.24](#Rf-pass-ref-ref) and [F.25](#Rf-pass-ref-move).) However, it's not fine when passing such a reference "upward" to a larger caller scope. See also ???.
3252 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&&`).
3254 ##### Example, bad
3256 If `F` returns by value, this function returns a reference to a temporary.
3258     template<class F>
3259     auto&& wrapper(F f)
3260     {
3261         log_call(typeid(f)); // or whatever instrumentation
3262         return f();
3263     }
3265 ##### Example, good
3267 Better:
3269     template<class F>
3270     auto wrapper(F f)
3271     {
3272         log_call(typeid(f)); // or whatever instrumentation
3273         return f();
3274     }
3276 ##### Exception
3278 `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 `&&`.
3280 ##### Enforcement
3282 Flag any use of `&&` as a return type, except in `std::move` and `std::forward`.
3284 ### <a name="Rf-main"></a>F.46: `int` is the return type for `main()`
3286 ##### Reason
3288 It's a language rule, but violated through "language extensions" so often that it is worth mentioning.
3289 Declaring `main` (the one global `main` of a program) `void` limits portability.
3291 ##### Example
3293         void main() { /* ... */ };  // bad, not C++
3295         int main()
3296         {
3297             std::cout << "This is the way to do it\n";
3298         }
3300 ##### Note
3302 We mention this only because of the persistence of this error in the community.
3304 ##### Enforcement
3306 * The compiler should do it
3307 * If the compiler doesn't do it, let tools flag it
3309 ### <a name="Rf-assignment-op"></a>F.47: Return `T&` from assignment operators
3311 ##### Reason
3313 The convention for operator overloads (especially on value types) is for
3314 `operator=(const T&)` to perform the assignment and then return (non-const)
3315 `*this`.  This ensures consistency with standard library types and follows the
3316 principle of "do as the ints do."
3318 ##### Note
3320 Historically there was some guidance to make the assignment operator return `const T&`.
3321 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.
3323 ##### Example
3325     class Foo
3326     {
3327      public:
3328         ...
3329         Foo& operator=(const Foo& rhs) {
3330           // Copy members.
3331           ...
3332           return *this;
3333         }
3334     };
3336 ##### Enforcement
3338 This should be enforced by tooling by checking the return type (and return
3339 value) of any assignment operator.
3341 ### <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)
3343 ##### Reason
3345 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.
3347 ##### Example
3349     // writing a function that should only take an int or a string
3350     // -- overloading is natural
3351     void f(int);
3352     void f(const string&);
3354     // writing a function object that needs to capture local state and appear
3355     // at statement or expression scope -- a lambda is natural
3356     vector<work> v = lots_of_work();
3357     for (int tasknum = 0; tasknum < max; ++tasknum) {
3358         pool.run([=, &v]{
3359             /*
3360             ...
3361             ... process 1 / max - th of v, the tasknum - th chunk
3362             ...
3363             */
3364         });
3365     }
3366     pool.join();
3368 ##### Exception
3370 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.
3372 ##### Enforcement
3374 * 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.
3376 ### <a name="Rf-default-args"></a>F.51: Where there is a choice, prefer default arguments over overloading
3378 ##### Reason
3380 Default arguments simply provides alternative interfaces to a single implementation.
3381 There is no guarantee that a set of overloaded functions all implement the same semantics.
3382 The use of default arguments can avoid code replication.
3384 ##### Note
3386 There is a choice between using default argument and overloading when the alternatives are from a set of arguments of the same types.
3387 For example:
3389     void print(const string& s, format f = {});
3391 as opposed to
3393     void print(const string& s);  // use default format
3394     void print(const string& s, format f);
3396 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:
3398     void print(const char&);
3399     void print(int);
3400     void print(zstring);
3402 ##### See also
3405 [Default arguments for virtual functions](#Rh-virtual-default-arg)
3407 ##### Enforcement
3409     ???
3411 ### <a name="Rf-reference-capture"></a>F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms
3413 ##### Reason
3415 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.
3417 ##### Example
3419 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.
3421     void send_packets(buffers& bufs)
3422     {
3423         stage encryptor([] (buffer& b){ encrypt(b); });
3424         stage compressor([&](buffer& b){ compress(b); encryptor.process(b); });
3425         stage decorator([&](buffer& b){ decorate(b); compressor.process(b); });
3426         for (auto& b : bufs) { decorator.process(b); }
3427     }  // automatically blocks waiting for pipeline to finish
3429 ##### Enforcement
3433 ### <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
3435 ##### Reason
3437 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.
3439 ##### Example, bad
3441     int local = 42;
3443     // Want a reference to local.
3444     // Note, that after program exits this scope,
3445     // local no longer exists, therefore
3446     // process() call will have undefined behavior!
3447     thread_pool.queue_work([&]{ process(local); });
3449 ##### Example, good
3451     int local = 42;
3452     // Want a copy of local.
3453     // Since a copy of local is made, it will be
3454     // available at all times for the call.
3455     thread_pool.queue_work([=]{ process(local); });
3457 ##### Enforcement
3459 * (Simple) Warn when capture-list contains a reference to a locally declared variable
3460 * (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
3462 ### <a name="Rf-this-capture"></a>F.54: If you capture `this`, capture all variables explicitly (no default capture)
3464 ##### Reason
3466 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.
3468 ##### Example
3470     class My_class {
3471         int x = 0;
3472         // ...
3474         void f() {
3475             int i = 0;
3476             // ...
3478             auto lambda = [=]{ use(i, x); };   // BAD: "looks like" copy/value capture
3479             // [&] has identical semantics and copies the this pointer under the current rules
3480             // [=,this] and [&,this] are not much better, and confusing
3482             x = 42;
3483             lambda(); // calls use(42);
3484             x = 43;
3485             lambda(); // calls use(43);
3487             // ...
3489             auto lambda2 = [i, this]{ use(i, x); }; // ok, most explicit and least confusing
3491             // ...
3492         }
3493     };
3495 ##### Note
3497 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.
3499 ##### Enforcement
3501 * Flag any lambda capture-list that specifies a default capture and also captures `this` (whether explicitly or via default capture)
3503 # <a name="S-class"></a>C: Classes and Class Hierarchies
3505 A class is a user-defined type, for which a programmer can define the representation, operations, and interfaces.
3506 Class hierarchies are used to organize related classes into hierarchical structures.
3508 Class rule summary:
3510 * [C.1: Organize related data into structures (`struct`s or `class`es)](#Rc-org)
3511 * [C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently](#Rc-struct)
3512 * [C.3: Represent the distinction between an interface and an implementation using a class](#Rc-interface)
3513 * [C.4: Make a function a member only if it needs direct access to the representation of a class](#Rc-member)
3514 * [C.5: Place helper functions in the same namespace as the class they support](#Rc-helper)
3515 * [C.7: Don't define a class or enum and declare a variable of its type in the same statement](#Rc-standalone)
3516 * [C.8: Use `class` rather than `struct` if any member is non-public](#Rc-class)
3517 * [C.9: Minimize exposure of members](#Rc-private)
3519 Subsections:
3521 * [C.concrete: Concrete types](#SS-concrete)
3522 * [C.ctor: Constructors, assignments, and destructors](#S-ctor)
3523 * [C.con: Containers and other resource handles](#SS-containers)
3524 * [C.lambdas: Function objects and lambdas](#SS-lambdas)
3525 * [C.hier: Class hierarchies (OOP)](#SS-hier)
3526 * [C.over: Overloading and overloaded operators](#SS-overload)
3527 * [C.union: Unions](#SS-union)
3529 ### <a name="Rc-org"></a>C.1: Organize related data into structures (`struct`s or `class`es)
3531 ##### Reason
3533 Ease of comprehension. If data is related (for fundamental reasons), that fact should be reflected in code.
3535 ##### Example
3537     void draw(int x, int y, int x2, int y2);  // BAD: unnecessary implicit relationships
3538     void draw(Point from, Point to);          // better
3540 ##### Note
3542 A simple class without virtual functions implies no space or time overhead.
3544 ##### Note
3546 From a language perspective `class` and `struct` differ only in the default visibility of their members.
3548 ##### Enforcement
3550 Probably impossible. Maybe a heuristic looking for data items used together is possible.
3552 ### <a name="Rc-struct"></a>C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently
3554 ##### Reason
3556 Readability.
3557 Ease of comprehension.
3558 The use of `class` alerts the programmer to the need for an invariant.
3559 This is a useful convention.
3561 ##### Note
3563 An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume.
3564 After the invariant is established (typically by a constructor) every member function can be called for the object.
3565 An invariant can be stated informally (e.g., in a comment) or more formally using `Expects`.
3567 If all data members can vary independently of each other, no invariant is possible.
3569 ##### Example
3571     struct Pair {  // the members can vary independently
3572         string name;
3573         int volume;
3574     };
3576 but:
3578     class Date {
3579     public:
3580         // validate that {yy, mm, dd} is a valid date and initialize
3581         Date(int yy, Month mm, char dd);
3582         // ...
3583     private:
3584         int y;
3585         Month m;
3586         char d;    // day
3587     };
3589 ##### Note
3591 If a class has any `private` data, a user cannot completely initialize an object without the use of a constructor.
3592 Hence, the class definer will provide a constructor and must specify its meaning.
3593 This effectively means the definer need to define an invariant.
3595 * See also [define a class with private data as `class`](#Rc-class).
3596 * See also [Prefer to place the interface first in a class](#Rl-order).
3597 * See also [minimize exposure of members](#Rc-private).
3598 * See also [Avoid `protected` data](#Rh-protected).
3600 ##### Enforcement
3602 Look for `struct`s with all data private and `class`es with public members.
3604 ### <a name="Rc-interface"></a>C.3: Represent the distinction between an interface and an implementation using a class
3606 ##### Reason
3608 An explicit distinction between interface and implementation improves readability and simplifies maintenance.
3610 ##### Example
3612     class Date {
3613         // ... some representation ...
3614     public:
3615         Date();
3616         // validate that {yy, mm, dd} is a valid date and initialize
3617         Date(int yy, Month mm, char dd);
3619         int day() const;
3620         Month month() const;
3621         // ...
3622     };
3624 For example, we can now change the representation of a `Date` without affecting its users (recompilation is likely, though).
3626 ##### Note
3628 Using a class in this way to represent the distinction between interface and implementation is of course not the only way.
3629 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.
3630 The most important issue is to explicitly distinguish between an interface and its implementation "details."
3631 Ideally, and typically, an interface is far more stable than its implementation(s).
3633 ##### Enforcement
3637 ### <a name="Rc-member"></a>C.4: Make a function a member only if it needs direct access to the representation of a class
3639 ##### Reason
3641 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.
3643 ##### Example
3645     class Date {
3646         // ... relatively small interface ...
3647     };
3649     // helper functions:
3650     Date next_weekday(Date);
3651     bool operator==(Date, Date);
3653 The "helper functions" have no need for direct access to the representation of a `Date`.
3655 ##### Note
3657 This rule becomes even better if C++ gets ["uniform function call"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0251r0.pdf).
3659 ##### Enforcement
3661 Look for member function that do not touch data members directly.
3662 The snag is that many member functions that do not need to touch data members directly do.
3664 ### <a name="Rc-helper"></a>C.5: Place helper functions in the same namespace as the class they support
3666 ##### Reason
3668 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.
3669 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.
3671 ##### Example
3673     namespace Chrono { // here we keep time-related services
3675         class Time { /* ... */ };
3676         class Date { /* ... */ };
3678         // helper functions:
3679         bool operator==(Date, Date);
3680         Date next_weekday(Date);
3681         // ...
3682     }
3684 ##### Note
3686 This is especially important for [overloaded operators](#Ro-namespace).
3688 ##### Enforcement
3690 * Flag global functions taking argument types from a single namespace.
3692 ### <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
3694 ##### Reason
3696 Mixing a type definition and the definition of another entity in the same declaration is confusing and unnecessary.
3698 ##### Example; bad
3700     struct Data { /*...*/ } data{ /*...*/ };
3702 ##### Example; good
3704     struct Data { /*...*/ };
3705     Data data{ /*...*/ };
3707 ##### Enforcement
3709 * Flag if the `}` of a class or enumeration definition is not followed by a `;`. The `;` is missing.
3711 ### <a name="Rc-class"></a>C.8: Use `class` rather than `struct` if any member is non-public
3713 ##### Reason
3715 Readability.
3716 To make it clear that something is being hidden/abstracted.
3717 This is a useful convention.
3719 ##### Example, bad
3721     struct Date {
3722         int d, m;
3724         Date(int i, Month m);
3725         // ... lots of functions ...
3726     private:
3727         int y;  // year
3728     };
3730 There is nothing wrong with this code as far as the C++ language rules are concerned,
3731 but nearly everything is wrong from a design perspective.
3732 The private data is hidden far from the public data.
3733 The data is split in different parts of the class declaration.
3734 Different parts of the data have different access.
3735 All of this decreases readability and complicates maintenance.
3737 ##### Note
3739 Prefer to place the interface first in a class [see](#Rl-order).
3741 ##### Enforcement
3743 Flag classes declared with `struct` if there is a `private` or `public` member.
3745 ### <a name="Rc-private"></a>C.9: Minimize exposure of members
3747 ##### Reason
3749 Encapsulation.
3750 Information hiding.
3751 Minimize the chance of untended access.
3752 This simplifies maintenance.
3754 ##### Example
3756     ???
3758 ##### Note
3760 Prefer the order `public` members before `protected` members before `private` members [see](#Rl-order).
3762 ##### Enforcement
3764 Flag protected data.
3766 ## <a name="SS-concrete"></a>C.concrete: Concrete types
3768 One ideal for a class is to be a regular type.
3769 That means roughly "behaves like an `int`." A concrete type is the simplest kind of class.
3770 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.
3771 If a concrete type has both `=` and `==`, `a = b` should result in `a == b` being `true`.
3772 Concrete classes without assignment and equality can be defined, but they are (and should be) rare.
3773 The C++ built-in types are regular, and so are standard-library classes, such as `string`, `vector`, and `map`.
3774 Concrete types are also often referred to as value types to distinguish them from types used as part of a hierarchy.
3776 Concrete type rule summary:
3778 * [C.10: Prefer a concrete type over more complicated classes](#Rc-concrete)
3779 * [C.11: Make concrete types regular](#Rc-regular)
3781 ### <a name="Rc-concrete"></a>C.10 Prefer a concrete type over more complicated classes
3783 ##### Reason
3785 A concrete type is fundamentally simpler than a hierarchy:
3786 easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster.
3787 You need a reason (use cases) for using a hierarchy.
3789 ##### Example
3791     class Point1 {
3792         int x, y;
3793         // ... operations ...
3794         // ... no virtual functions ...
3795     };
3797     class Point2 {
3798         int x, y;
3799         // ... operations, some virtual ...
3800         virtual ~Point2();
3801     };
3803     void use()
3804     {
3805         Point1 p11 {1, 2};   // make an object on the stack
3806         Point1 p12 {p11};    // a copy
3808         auto p21 = make_unique<Point2>(1, 2);   // make an object on the free store
3809         auto p22 = p21.clone();                 // make a copy
3810         // ...
3811     }
3813 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.
3814 That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections.
3816 ##### Note
3818 Concrete types can be stack allocated and be members of other classes.
3820 ##### Note
3822 The use of indirection is fundamental for run-time polymorphic interfaces.
3823 The allocation/deallocation overhead is not (that's just the most common case).
3824 We can use a base class as the interface of a scoped object of a derived class.
3825 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.
3827 ##### Enforcement
3831 ### <a name="Rc-regular"></a>C.11: Make concrete types regular
3833 ##### Reason
3835 Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).
3837 ##### Example
3839     struct Bundle {
3840         string name;
3841         vector<Record> vr;
3842     };
3844     bool operator==(const Bundle& a, const Bundle& b)
3845     {
3846         return a.name == b.name && a.vr == b.vr;
3847     }
3849     Bundle b1 { "my bundle", {r1, r2, r3}};
3850     Bundle b2 = b1;
3851     if (!(b1 == b2)) error("impossible!");
3852     b2.name = "the other bundle";
3853     if (b1 == b2) error("No!");
3855 In particular, if a concrete type has an assignment also give it an equals operator so that `a = b` implies `a == b`.
3857 ##### Enforcement
3861 ## <a name="S-ctor"></a>C.ctor: Constructors, assignments, and destructors
3863 These functions control the lifecycle of objects: creation, copy, move, and destruction.
3864 Define constructors to guarantee and simplify initialization of classes.
3866 These are *default operations*:
3868 * a default constructor: `X()`
3869 * a copy constructor: `X(const X&)`
3870 * a copy assignment: `operator=(const X&)`
3871 * a move constructor: `X(X&&)`
3872 * a move assignment: `operator=(X&&)`
3873 * a destructor: `~X()`
3875 By default, the compiler defines each of these operations if it is used, but the default can be suppressed.
3877 The default operations are a set of related operations that together implement the lifecycle semantics of an object.
3878 By default, C++ treats classes as value-like types, but not all types are value-like.
3880 Set of default operations rules:
3882 * [C.20: If you can avoid defining any default operations, do](#Rc-zero)
3883 * [C.21: If you define or `=delete` any default operation, define or `=delete` them all](#Rc-five)
3884 * [C.22: Make default operations consistent](#Rc-matched)
3886 Destructor rules:
3888 * [C.30: Define a destructor if a class needs an explicit action at object destruction](#Rc-dtor)
3889 * [C.31: All resources acquired by a class must be released by the class's destructor](#Rc-dtor-release)
3890 * [C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning](#Rc-dtor-ptr)
3891 * [C.33: If a class has an owning pointer member, define or `=delete` a destructor](#Rc-dtor-ptr2)
3892 * [C.34: If a class has an owning reference member, define or `=delete` a destructor](#Rc-dtor-ref)
3893 * [C.35: A base class with a virtual function needs a virtual destructor](#Rc-dtor-virtual)
3894 * [C.36: A destructor may not fail](#Rc-dtor-fail)
3895 * [C.37: Make destructors `noexcept`](#Rc-dtor-noexcept)
3897 Constructor rules:
3899 * [C.40: Define a constructor if a class has an invariant](#Rc-ctor)
3900 * [C.41: A constructor should create a fully initialized object](#Rc-complete)
3901 * [C.42: If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
3902 * [C.43: Ensure that a class has a default constructor](#Rc-default0)
3903 * [C.44: Prefer default constructors to be simple and non-throwing](#Rc-default00)
3904 * [C.45: Don't define a default constructor that only initializes data members; use member initializers instead](#Rc-default)
3905 * [C.46: By default, declare single-argument constructors `explicit`](#Rc-explicit)
3906 * [C.47: Define and initialize member variables in the order of member declaration](#Rc-order)
3907 * [C.48: Prefer in-class initializers to member initializers in constructors for constant initializers](#Rc-in-class-initializer)
3908 * [C.49: Prefer initialization to assignment in constructors](#Rc-initialize)
3909 * [C.50: Use a factory function if you need "virtual behavior" during initialization](#Rc-factory)
3910 * [C.51: Use delegating constructors to represent common actions for all constructors of a class](#Rc-delegating)
3911 * [C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization](#Rc-inheriting)
3913 Copy and move rules:
3915 * [C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`](#Rc-copy-assignment)
3916 * [C.61: A copy operation should copy](#Rc-copy-semantic)
3917 * [C.62: Make copy assignment safe for self-assignment](#Rc-move-self)
3918 * [C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const&`](#Rc-move-assignment)
3919 * [C.64: A move operation should move and leave its source in a valid state](#Rc-move-semantic)
3920 * [C.65: Make move assignment safe for self-assignment](#Rc-copy-self)
3921 * [C.66: Make move operations `noexcept`](#Rc-move-noexcept)
3922 * [C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired](#Rc-copy-virtual)
3924 Other default operations rules:
3926 * [C.80: Use `=default` if you have to be explicit about using the default semantics](#Rc-eqdefault)
3927 * [C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)](#Rc-delete)
3928 * [C.82: Don't call virtual functions in constructors and destructors](#Rc-ctor-virtual)
3929 * [C.83: For value-like types, consider providing a `noexcept` swap function](#Rc-swap)
3930 * [C.84: A `swap` may not fail](#Rc-swap-fail)
3931 * [C.85: Make `swap` `noexcept`](#Rc-swap-noexcept)
3932 * [C.86: Make `==` symmetric with respect of operand types and `noexcept`](#Rc-eq)
3933 * [C.87: Beware of `==` on base classes](#Rc-eq-base)
3934 * [C.89: Make a `hash` `noexcept`](#Rc-hash)
3936 ## <a name="SS-defop"></a>C.defop: Default Operations
3938 By default, the language supplies the default operations with their default semantics.
3939 However, a programmer can disable or replace these defaults.
3941 ### <a name="Rc-zero"></a>C.20: If you can avoid defining default operations, do
3943 ##### Reason
3945 It's the simplest and gives the cleanest semantics.
3947 ##### Example
3949     struct Named_map {
3950     public:
3951         // ... no default operations declared ...
3952     private:
3953         string name;
3954         map<int, int> rep;
3955     };
3957     Named_map nm;        // default construct
3958     Named_map nm2 {nm};  // copy construct
3960 Since `std::map` and `string` have all the special functions, no further work is needed.
3962 ##### Note
3964 This is known as "the rule of zero".
3966 ##### Enforcement
3968 (Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule.
3969 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`.
3971 ### <a name="Rc-five"></a>C.21: If you define or `=delete` any default operation, define or `=delete` them all
3973 ##### Reason
3975 The semantics of the special functions are closely related, so if one needs to be non-default, the odds are that others need modification too.
3977 ##### Example, bad
3979     struct M2 {   // bad: incomplete set of default operations
3980     public:
3981         // ...
3982         // ... no copy or move operations ...
3983         ~M2() { delete[] rep; }
3984     private:
3985         pair<int, int>* rep;  // zero-terminated set of pairs
3986     };
3988     void use()
3989     {
3990         M2 x;
3991         M2 y;
3992         // ...
3993         x = y;   // the default assignment
3994         // ...
3995     }
3997 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).
3999 ##### Note
4001 This is known as "the rule of five" or "the rule of six", depending on whether you count the default constructor.
4003 ##### Note
4005 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.
4006 If you don't want a default operation, suppress it with `=delete`.
4008 ##### Note
4010 Compilers enforce much of this rule and ideally warn about any violation.
4012 ##### Note
4014 Relying on an implicitly generated copy operation in a class with a destructor is deprecated.
4016 ##### Enforcement
4018 (Simple) A class should have a declaration (even a `=delete` one) for either all or none of the special functions.
4020 ### <a name="Rc-matched"></a>C.22: Make default operations consistent
4022 ##### Reason
4024 The default operations are conceptually a matched set. Their semantics are interrelated.
4025 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.
4027 ##### Example, bad
4029     class Silly {   // BAD: Inconsistent copy operations
4030         class Impl {
4031             // ...
4032         };
4033         shared_ptr<Impl> p;
4034     public:
4035         Silly(const Silly& a) : p{a.p} { *p = *a.p; }   // deep copy
4036         Silly& operator=(const Silly& a) { p = a.p; }   // shallow copy
4037         // ...
4038     };
4040 These operations disagree about copy semantics. This will lead to confusion and bugs.
4042 ##### Enforcement
4044 * (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.
4045 * (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors.
4046 * (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable.
4047 * (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators.
4049 ## <a name="SS-dtor"></a>C.dtor: Destructors
4051 "Does this class need a destructor?" is a surprisingly powerful design question.
4052 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);
4053 that is, its members can take care of themselves as concerns destruction.
4054 If the answer is "yes", much of the design of the class follows (see [the rule of five](#Rc-five)).
4056 ### <a name="Rc-dtor"></a>C.30: Define a destructor if a class needs an explicit action at object destruction
4058 ##### Reason
4060 A destructor is implicitly invoked at the end of an object's lifetime.
4061 If the default destructor is sufficient, use it.
4062 Only define a non-default destructor if a class needs to execute code that is not already part of its members' destructors.
4064 ##### Example
4066     template<typename A>
4067     struct final_action {   // slightly simplified
4068         A act;
4069         final_action(A a) :act{a} {}
4070         ~final_action() { act(); }
4071     };
4073     template<typename A>
4074     final_action<A> finally(A act)   // deduce action type
4075     {
4076         return final_action<A>{act};
4077     }
4079     void test()
4080     {
4081         auto act = finally([]{ cout << "Exit test\n"; });  // establish exit action
4082         // ...
4083         if (something) return;   // act done here
4084         // ...
4085     } // act done here
4087 The whole purpose of `final_action` is to get a piece of code (usually a lambda) executed upon destruction.
4089 ##### Note
4091 There are two general categories of classes that need a user-defined destructor:
4093 * A class with a resource that is not already represented as a class with a destructor, e.g., a `vector` or a transaction class.
4094 * A class that exists primarily to execute an action upon destruction, such as a tracer or `final_action`.
4096 ##### Example, bad
4098     class Foo {   // bad; use the default destructor
4099     public:
4100         // ...
4101         ~Foo() { s = ""; i = 0; vi.clear(); }  // clean up
4102     private:
4103         string s;
4104         int i;
4105         vector<int> vi;
4106     };
4108 The default destructor does it better, more efficiently, and can't get it wrong.
4110 ##### Note
4112 If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use `=default`.
4114 ##### Enforcement
4116 Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors.
4118 ### <a name="Rc-dtor-release"></a>C.31: All resources acquired by a class must be released by the class's destructor
4120 ##### Reason
4122 Prevention of resource leaks, especially in error cases.
4124 ##### Note
4126 For resources represented as classes with a complete set of default operations, this happens automatically.
4128 ##### Example
4130     class X {
4131         ifstream f;   // may own a file
4132         // ... no default operations defined or =deleted ...
4133     };
4135 `X`'s `ifstream` implicitly closes any file it may have open upon destruction of its `X`.
4137 ##### Example, bad
4139     class X2 {     // bad
4140         FILE* f;   // may own a file
4141         // ... no default operations defined or =deleted ...
4142     };
4144 `X2` may leak a file handle.
4146 ##### Note
4148 What about a sockets that won't close? A destructor, close, or cleanup operation [should never fail](#Rc-dtor-fail).
4149 If it does nevertheless, we have a problem that has no really good solution.
4150 For starters, the writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
4151 See [discussion](#Sd-never-fail).
4152 To make the problem worse, many "close/release" operations are not retryable.
4153 Many have tried to solve this problem, but no general solution is known.
4154 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
4156 ##### Note
4158 A class can hold pointers and references to objects that it does not own.
4159 Obviously, such objects should not be `delete`d by the class's destructor.
4160 For example:
4162     Preprocessor pp { /* ... */ };
4163     Parser p { pp, /* ... */ };
4164     Type_checker tc { p, /* ... */ };
4166 Here `p` refers to `pp` but does not own it.
4168 ##### Enforcement
4170 * (Simple) If a class has pointer or reference member variables that are owners
4171   (e.g., deemed owners by using `gsl::owner`), then they should be referenced in its destructor.
4172 * (Hard) Determine if pointer or reference member variables are owners when there is no explicit statement of ownership
4173   (e.g., look into the constructors).
4175 ### <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
4177 ##### Reason
4179 There is a lot of code that is non-specific about ownership.
4181 ##### Example
4183     ???
4185 ##### Note
4187 If the `T*` or `T&` is owning, mark it `owning`. If the `T*` is not owning, consider marking it `ptr`.
4188 This will aid documentation and analysis.
4190 ##### Enforcement
4192 Look at the initialization of raw member pointers and member references and see if an allocation is used.
4194 ### <a name="Rc-dtor-ptr2"></a>C.33: If a class has an owning pointer member, define a destructor
4196 ##### Reason
4198 An owned object must be `deleted` upon destruction of the object that owns it.
4200 ##### Example
4202 A pointer member may represent a resource.
4203 [A `T*` should not do so](#Rr-ptr), but in older code, that's common.
4204 Consider a `T*` a possible owner and therefore suspect.
4206     template<typename T>
4207     class Smart_ptr {
4208         T* p;   // BAD: vague about ownership of *p
4209         // ...
4210     public:
4211         // ... no user-defined default operations ...
4212     };
4214     void use(Smart_ptr<int> p1)
4215     {
4216         // error: p2.p leaked (if not nullptr and not owned by some other code)
4217         auto p2 = p1;
4218     }
4220 Note that if you define a destructor, you must define or delete [all default operations](#Rc-five):
4222     template<typename T>
4223     class Smart_ptr2 {
4224         T* p;   // BAD: vague about ownership of *p
4225         // ...
4226     public:
4227         // ... no user-defined copy operations ...
4228         ~Smart_ptr2() { delete p; }  // p is an owner!
4229     };
4231     void use(Smart_ptr2<int> p1)
4232     {
4233         auto p2 = p1;   // error: double deletion
4234     }
4236 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:
4238     template<typename T>
4239     class Smart_ptr3 {
4240         owner<T*> p;   // OK: explicit about ownership of *p
4241         // ...
4242     public:
4243         // ...
4244         // ... copy and move operations ...
4245         ~Smart_ptr3() { delete p; }
4246     };
4248     void use(Smart_ptr3<int> p1)
4249     {
4250         auto p2 = p1;   // error: double deletion
4251     }
4253 ##### Note
4255 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.
4257 ##### Note
4259 Why not just require all owning pointers to be "smart pointers"?
4260 That would sometimes require non-trivial code changes and may affect ABIs.
4262 ##### Enforcement
4264 * A class with a pointer data member is suspect.
4265 * A class with an `owner<T>` should define its default operations.
4267 ### <a name="Rc-dtor-ref"></a>C.34: If a class has an owning reference member, define a destructor
4269 ##### Reason
4271 A reference member may represent a resource.
4272 It should not do so, but in older code, that's common.
4273 See [pointer members and destructors](#Rc-dtor-ptr).
4274 Also, copying may lead to slicing.
4276 ##### Example, bad
4278     class Handle {  // Very suspect
4279         Shape& s;   // use reference rather than pointer to prevent rebinding
4280                     // BAD: vague about ownership of *p
4281         // ...
4282     public:
4283         Handle(Shape& ss) : s{ss} { /* ... */ }
4284         // ...
4285     };
4287 The problem of whether `Handle` is responsible for the destruction of its `Shape` is the same as for [the pointer case](#Rc-dtor-ptr):
4288 If the `Handle` owns the object referred to by `s` it must have a destructor.
4290 ##### Example
4292     class Handle {        // OK
4293         owner<Shape&> s;  // use reference rather than pointer to prevent rebinding
4294         // ...
4295     public:
4296         Handle(Shape& ss) : s{ss} { /* ... */ }
4297         ~Handle() { delete &s; }
4298         // ...
4299     };
4301 Independently of whether `Handle` owns its `Shape`, we must consider the default copy operations suspect:
4303     // the Handle had better own the Circle or we have a leak
4304     Handle x {*new Circle{p1, 17}};
4306     Handle y {*new Triangle{p1, p2, p3}};
4307     x = y;     // the default assignment will try *x.s = *y.s
4309 That `x = y` is highly suspect.
4310 Assigning a `Triangle` to a `Circle`?
4311 Unless `Shape` has its [copy assignment `=deleted`](#Rc-copy-virtual), only the `Shape` part of `Triangle` is copied into the `Circle`.
4313 ##### Note
4315 Why not just require all owning references to be replaced by "smart pointers"?
4316 Changing from references to smart pointers implies code changes.
4317 We don't (yet) have smart references.
4318 Also, that may affect ABIs.
4320 ##### Enforcement
4322 * A class with a reference data member is suspect.
4323 * A class with an `owner<T>` reference should define its default operations.
4325 ### <a name="Rc-dtor-virtual"></a>C.35: A base class destructor should be either public and virtual, or protected and nonvirtual
4327 ##### Reason
4329 To prevent undefined behavior.
4330 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.
4331 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.
4332 In general, the writer of a base class does not know the appropriate action to be done upon destruction.
4334 ##### Discussion
4336 See [this in the Discussion section](#Sd-dtor).
4338 ##### Example, bad
4340     struct Base {  // BAD: no virtual destructor
4341         virtual void f();
4342     };
4344     struct D : Base {
4345         string s {"a resource needing cleanup"};
4346         ~D() { /* ... do some cleanup ... */ }
4347         // ...
4348     };
4350     void use()
4351     {
4352         unique_ptr<Base> p = make_unique<D>();
4353         // ...
4354     } // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more
4356 ##### Note
4358 A virtual function defines an interface to derived classes that can be used without looking at the derived classes.
4359 If the interface allows destroying, it should be safe to do so.
4361 ##### Note
4363 A destructor must be nonprivate or it will prevent using the type :
4365     class X {
4366         ~X();   // private destructor
4367         // ...
4368     };
4370     void use()
4371     {
4372         X a;                        // error: cannot destroy
4373         auto p = make_unique<X>();  // error: cannot destroy
4374     }
4376 ##### Exception
4378 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.
4380 ##### Enforcement
4382 * A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.
4384 ### <a name="Rc-dtor-fail"></a>C.36: A destructor may not fail
4386 ##### Reason
4388 In general we do not know how to write error-free code if a destructor should fail.
4389 The standard library requires that all classes it deals with have destructors that do not exit by throwing.
4391 ##### Example
4393     class X {
4394     public:
4395         ~X() noexcept;
4396         // ...
4397     };
4399     X::~X() noexcept
4400     {
4401         // ...
4402         if (cannot_release_a_resource) terminate();
4403         // ...
4404     }
4406 ##### Note
4408 Many have tried to devise a fool-proof scheme for dealing with failure in destructors.
4409 None have succeeded to come up with a general scheme.
4410 This can be a real practical problem: For example, what about a socket that won't close?
4411 The writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
4412 See [discussion](#Sd-dtor).
4413 To make the problem worse, many "close/release" operations are not retryable.
4414 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
4416 ##### Note
4418 Declare a destructor `noexcept`. That will ensure that it either completes normally or terminate the program.
4420 ##### Note
4422 If a resource cannot be released and the program may not fail, try to signal the failure to the rest of the system somehow
4423 (maybe even by modifying some global state and hope something will notice and be able to take care of the problem).
4424 Be fully aware that this technique is special-purpose and error-prone.
4425 Consider the "my connection will not close" example.
4426 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.
4427 The destructor could send a message (somehow) to the responsible part of the system, consider that to have closed the connection, and return normally.
4429 ##### Note
4431 If a destructor uses operations that may fail, it can catch exceptions and in some cases still complete successfully
4432 (e.g., by using a different clean-up mechanism from the one that threw an exception).
4434 ##### Enforcement
4436 (Simple) A destructor should be declared `noexcept`.
4438 ### <a name="Rc-dtor-noexcept"></a>C.37: Make destructors `noexcept`
4440 ##### Reason
4442  [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.
4444 ##### Note
4446 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.
4448 ##### Enforcement
4450 (Simple) A destructor should be declared `noexcept`.
4452 ## <a name="SS-ctor"></a>C.ctor: Constructors
4454 A constructor defines how an object is initialized (constructed).
4456 ### <a name="Rc-ctor"></a>C.40: Define a constructor if a class has an invariant
4458 ##### Reason
4460 That's what constructors are for.
4462 ##### Example
4464     class Date {  // a Date represents a valid date
4465                   // in the January 1, 1900 to December 31, 2100 range
4466         Date(int dd, int mm, int yy)
4467             :d{dd}, m{mm}, y{yy}
4468         {
4469             if (!is_valid(d, m, y)) throw Bad_date{};  // enforce invariant
4470         }
4471         // ...
4472     private:
4473         int d, m, y;
4474     };
4476 It is often a good idea to express the invariant as an `Ensures` on the constructor.
4478 ##### Note
4480 A constructor can be used for convenience even if a class does not have an invariant. For example:
4482     struct Rec {
4483         string s;
4484         int i {0};
4485         Rec(const string& ss) : s{ss} {}
4486         Rec(int ii) :i{ii} {}
4487     };
4489     Rec r1 {7};
4490     Rec r2 {"Foo bar"};
4492 ##### Note
4494 The C++11 initializer list rule eliminates the need for many constructors. For example:
4496     struct Rec2{
4497         string s;
4498         int i;
4499         Rec2(const string& ss, int ii = 0) :s{ss}, i{ii} {}   // redundant
4500     };
4502     Rec2 r1 {"Foo", 7};
4503     Rec2 r2 {"Bar"};
4505 The `Rec2` constructor is redundant.
4506 Also, the default for `int` would be better done as a [member initializer](#Rc-in-class-initializer).
4508 **See also**: [construct valid object](#Rc-complete) and [constructor throws](#Rc-throw).
4510 ##### Enforcement
4512 * Flag classes with user-defined copy operations but no constructor (a user-defined copy is a good indicator that the class has an invariant)
4514 ### <a name="Rc-complete"></a>C.41: A constructor should create a fully initialized object
4516 ##### Reason
4518 A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
4520 ##### Example, bad
4522     class X1 {
4523         FILE* f;   // call init() before any other function
4524         // ...
4525     public:
4526         X1() {}
4527         void init();   // initialize f
4528         void read();   // read from f
4529         // ...
4530     };
4532     void f()
4533     {
4534         X1 file;
4535         file.read();   // crash or bad read!
4536         // ...
4537         file.init();   // too late
4538         // ...
4539     }
4541 Compilers do not read comments.
4543 ##### Exception
4545 If a valid object cannot conveniently be constructed by a constructor, [use a factory function](#Rc-factory).
4547 ##### Enforcement
4549 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
4550 * (Unknown) If a constructor has an `Ensures` contract, try to see if it holds as a postcondition.
4552 ##### Note
4554 If a constructor acquires a resource (to create a valid object), that resource should be [released by the destructor](#Rc-dtor-release).
4555 The idiom of having constructors acquire resources and destructors release them is called [RAII](#Rr-raii) ("Resource Acquisition Is Initialization").
4557 ### <a name="Rc-throw"></a>C.42: If a constructor cannot construct a valid object, throw an exception
4559 ##### Reason
4561 Leaving behind an invalid object is asking for trouble.
4563 ##### Example
4565     class X2 {
4566         FILE* f;   // call init() before any other function
4567         // ...
4568     public:
4569         X2(const string& name)
4570             :f{fopen(name.c_str(), "r")}
4571         {
4572             if (f == nullptr) throw runtime_error{"could not open" + name};
4573             // ...
4574         }
4576         void read();      // read from f
4577         // ...
4578     };
4580     void f()
4581     {
4582         X2 file {"Zeno"}; // throws if file isn't open
4583         file.read();      // fine
4584         // ...
4585     }
4587 ##### Example, bad
4589     class X3 {     // bad: the constructor leaves a non-valid object behind
4590         FILE* f;   // call init() before any other function
4591         bool valid;
4592         // ...
4593     public:
4594         X3(const string& name)
4595             :f{fopen(name.c_str(), "r")}, valid{false}
4596         {
4597             if (f) valid = true;
4598             // ...
4599         }
4601         bool is_valid() { return valid; }
4602         void read();   // read from f
4603         // ...
4604     };
4606     void f()
4607     {
4608         X3 file {"Heraclides"};
4609         file.read();   // crash or bad read!
4610         // ...
4611         if (file.is_valid()) {
4612             file.read();
4613             // ...
4614         }
4615         else {
4616             // ... handle error ...
4617         }
4618         // ...
4619     }
4621 ##### Note
4623 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.
4624 Leaving behind an invalid object and relying on users to consistently check an `is_valid()` function before use is tedious, error-prone, and inefficient.
4626 ##### Exception
4628 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.
4629 There the `is_valid()` technique must be used. In such cases, check `is_valid()` consistently and immediately to simulate [RAII](#Rr-raii).
4631 **Alternative**: If you feel tempted to use some "post-constructor initialization" or "two-stage initialization" idiom, try not to do that.
4632 If you really have to, look at [factory functions](#Rc-factory).
4634 ##### Note
4636 One reason people have used `init()` functions rather than doing the initialization work in a constructor has been to avoid code replication.
4637 [Delegating constructors](#Rc-delegating) and [default member initialization](#Rc-in-class-initializer) do that better.
4638 Another reason is 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)
4640 ##### Enforcement
4642 ### <a name="Rc-default0"></a>C.43: Ensure that a class has a default constructor
4644 ##### Reason
4646 Many language and library facilities rely on default constructors to initialize their elements, e.g. `T a[10]` and `std::vector<T> v(10)`.
4648 ##### Example , bad
4650     class Date { // BAD: no default constructor
4651     public:
4652         Date(int dd, int mm, int yyyy);
4653         // ...
4654     };
4656     vector<Date> vd1(1000);   // default Date needed here
4657     vector<Date> vd2(1000, Date{Month::october, 7, 1885});   // alternative
4659 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.
4661 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.
4662 `{0, 0, 0}` is not a valid date in most calendar systems, so choosing that would be introducing something like floating-point's `NaN`.
4663 However, most realistic `Date` classes have a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial.
4665 ##### Example
4667     class Date {
4668     public:
4669         Date(int dd, int mm, int yyyy);
4670         Date() = default; // See also C.45
4671         // ...
4672     private:
4673         int dd = 1;
4674         int mm = 1;
4675         int yyyy = 1970;
4676         // ...
4677     };
4679     vector<Date> vd1(1000);
4681 ##### Note
4683 A class with members that all have default constructors implicitly gets a default constructor:
4685     struct X {
4686         string s;
4687         vector<int> v;
4688     };
4690     X x; // means X{{}, {}}; that is the empty string and the empty vector
4692 Beware that built-in types are not properly default constructed:
4694     struct X {
4695         string s;
4696         int i;
4697     };
4699     void f()
4700     {
4701         X x;    // x.s is initialized to the empty string; x.i is uninitialized
4703         cout << x.s << ' ' << x.i << '\n';
4704         ++x.i;
4705     }
4707 Statically allocated objects of built-in types are by default initialized to `0`, but local built-in variables are not.
4708 Beware that your compiler may default initialize local built-in variables, whereas an optimized build will not.
4709 Thus, code like the example above may appear to work, but it relies on undefined behavior.
4710 Assuming that you want initialization, an explicit default initialization can help:
4712     struct X {
4713         string s;
4714         int i {};   // default initialize (to 0)
4715     };
4717 ##### Enforcement
4719 * Flag classes without a default constructor
4721 ### <a name="Rc-default00"></a>C.44: Prefer default constructors to be simple and non-throwing
4723 ##### Reason
4725 Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.
4727 ##### Example, problematic
4729     template<typename T>
4730     // elem points to space-elem element allocated using new
4731     class Vector0 {
4732     public:
4733         Vector0() :Vector0{0} {}
4734         Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
4735         // ...
4736     private:
4737         own<T*> elem;
4738         T* space;
4739         T* last;
4740     };
4742 This is nice and general, but setting a `Vector0` to empty after an error involves an allocation, which may fail.
4743 Also, having a default `Vector` represented as `{new T[0], 0, 0}` seems wasteful.
4744 For example, `Vector0 v(100)` costs 100 allocations.
4746 ##### Example
4748     template<typename T>
4749     // elem is nullptr or elem points to space-elem element allocated using new
4750     class Vector1 {
4751     public:
4752         // sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
4753         Vector1() noexcept {}
4754         Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
4755         // ...
4756     private:
4757         own<T*> elem = nullptr;
4758         T* space = nullptr;
4759         T* last = nullptr;
4760     };
4762 Using `{nullptr, nullptr, nullptr}` makes `Vector1{}` cheap, but a special case and implies run-time checks.
4763 Setting a `Vector1` to empty after detecting an error is trivial.
4765 ##### Enforcement
4767 * Flag throwing default constructors
4769 ### <a name="Rc-default"></a>C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead
4771 ##### Reason
4773 Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
4775 ##### Example, bad
4777     class X1 { // BAD: doesn't use member initializers
4778         string s;
4779         int i;
4780     public:
4781         X1() :s{"default"}, i{1} { }
4782         // ...
4783     };
4785 ##### Example
4787     class X2 {
4788         string s = "default";
4789         int i = 1;
4790     public:
4791         // use compiler-generated default constructor
4792         // ...
4793     };
4795 ##### Enforcement
4797 (Simple) A default constructor should do more than just initialize member variables with constants.
4799 ### <a name="Rc-explicit"></a>C.46: By default, declare single-argument constructors explicit
4801 ##### Reason
4803 To avoid unintended conversions.
4805 ##### Example, bad
4807     class String {
4808         // ...
4809     public:
4810         String(int);   // BAD
4811         // ...
4812     };
4814     String s = 10;   // surprise: string of size 10
4816 ##### Exception
4818 If you really want an implicit conversion from the constructor argument type to the class type, don't use `explicit`:
4820     class Complex {
4821         // ...
4822     public:
4823         Complex(double d);   // OK: we want a conversion from d to {d, 0}
4824         // ...
4825     };
4827     Complex z = 10.7;   // unsurprising conversion
4829 **See also**: [Discussion of implicit conversions](#Ro-conversion).
4831 ##### Enforcement
4833 (Simple) Single-argument constructors should be declared `explicit`. Good single argument non-`explicit` constructors are rare in most code based. Warn for all that are not on a "positive list".
4835 ### <a name="Rc-order"></a>C.47: Define and initialize member variables in the order of member declaration
4837 ##### Reason
4839 To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).
4841 ##### Example, bad
4843     class Foo {
4844         int m1;
4845         int m2;
4846     public:
4847         Foo(int x) :m2{x}, m1{++x} { }   // BAD: misleading initializer order
4848         // ...
4849     };
4851     Foo x(1); // surprise: x.m1 == x.m2 == 2
4853 ##### Enforcement
4855 (Simple) A member initializer list should mention the members in the same order they are declared.
4857 **See also**: [Discussion](#Sd-order)
4859 ### <a name="Rc-in-class-initializer"></a>C.48: Prefer in-class initializers to member initializers in constructors for constant initializers
4861 ##### Reason
4863 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.
4865 ##### Example, bad
4867     class X {   // BAD
4868         int i;
4869         string s;
4870         int j;
4871     public:
4872         X() :i{666}, s{"qqq"} { }   // j is uninitialized
4873         X(int ii) :i{ii} {}         // s is "" and j is uninitialized
4874         // ...
4875     };
4877 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.
4879 ##### Example
4881     class X2 {
4882         int i {666};
4883         string s {"qqq"};
4884         int j {0};
4885     public:
4886         X2() = default;        // all members are initialized to their defaults
4887         X2(int ii) :i{ii} {}   // s and j initialized to their defaults
4888         // ...
4889     };
4891 **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:
4893     class X3 {   // BAD: inexplicit, argument passing overhead
4894         int i;
4895         string s;
4896         int j;
4897     public:
4898         X3(int ii = 666, const string& ss = "qqq", int jj = 0)
4899             :i{ii}, s{ss}, j{jj} { }   // all members are initialized to their defaults
4900         // ...
4901     };
4903 ##### Enforcement
4905 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
4906 * (Simple) Default arguments to constructors suggest an in-class initializer may be more appropriate.
4908 ### <a name="Rc-initialize"></a>C.49: Prefer initialization to assignment in constructors
4910 ##### Reason
4912 An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.
4914 ##### Example, good
4916     class A {   // Good
4917         string s1;
4918     public:
4919         A() : s1{"Hello, "} { }    // GOOD: directly construct
4920         // ...
4921     };
4923 ##### Example, bad
4925     class B {   // BAD
4926         string s1;
4927     public:
4928         B() { s1 = "Hello, "; }   // BAD: default constructor followed by assignment
4929         // ...
4930     };
4932     class C {   // UGLY, aka very bad
4933         int* p;
4934     public:
4935         C() { cout << *p; p = new int{10}; }   // accidental use before initialized
4936         // ...
4937     };
4939 ### <a name="Rc-factory"></a>C.50: Use a factory function if you need "virtual behavior" during initialization
4941 ##### Reason
4943 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.
4945 ##### Example, bad
4947     class B {
4948     public:
4949         B()
4950         {
4951             // ...
4952             f();   // BAD: virtual call in constructor
4953             // ...
4954         }
4956         virtual void f() = 0;
4958         // ...
4959     };
4961 ##### Example
4963     class B {
4964     protected:
4965         B() { /* ... */ }              // create an imperfectly initialized object
4967         virtual void PostInitialize()  // to be called right after construction
4968         {
4969             // ...
4970             f();    // GOOD: virtual dispatch is safe
4971             // ...
4972         }
4974     public:
4975         virtual void f() = 0;
4977         template<class T>
4978         static shared_ptr<T> Create()  // interface for creating objects
4979         {
4980             auto p = make_shared<T>();
4981             p->PostInitialize();
4982             return p;
4983         }
4984     };
4986     class D : public B { /* ... */ };            // some derived class
4988     shared_ptr<D> p = D::Create<D>();  // creating a D object
4990 By making the constructor `protected` we avoid an incompletely constructed object escaping into the wild.
4991 By providing the factory function `Create()`, we make construction (on the free store) convenient.
4993 ##### Note
4995 Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object.
4997 **See also**: [Discussion](#Sd-factory)
4999 ### <a name="Rc-delegating"></a>C.51: Use delegating constructors to represent common actions for all constructors of a class
5001 ##### Reason
5003 To avoid repetition and accidental differences.
5005 ##### Example, bad
5007     class Date {   // BAD: repetitive
5008         int d;
5009         Month m;
5010         int y;
5011     public:
5012         Date(int ii, Month mm, year yy)
5013             :i{ii}, m{mm}, y{yy}
5014             { if (!valid(i, m, y)) throw Bad_date{}; }
5016         Date(int ii, Month mm)
5017             :i{ii}, m{mm} y{current_year()}
5018             { if (!valid(i, m, y)) throw Bad_date{}; }
5019         // ...
5020     };
5022 The common action gets tedious to write and may accidentally not be common.
5024 ##### Example
5026     class Date2 {
5027         int d;
5028         Month m;
5029         int y;
5030     public:
5031         Date2(int ii, Month mm, year yy)
5032             :i{ii}, m{mm}, y{yy}
5033             { if (!valid(i, m, y)) throw Bad_date{}; }
5035         Date2(int ii, Month mm)
5036             :Date2{ii, mm, current_year()} {}
5037         // ...
5038     };
5040 **See also**: If the "repeated action" is a simple initialization, consider [an in-class member initializer](#Rc-in-class-initializer).
5042 ##### Enforcement
5044 (Moderate) Look for similar constructor bodies.
5046 ### <a name="Rc-inheriting"></a>C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization
5048 ##### Reason
5050 If you need those constructors for a derived class, re-implementing them is tedious and error prone.
5052 ##### Example
5054 `std::vector` has a lot of tricky constructors, so if I want my own `vector`, I don't want to reimplement them:
5056     class Rec {
5057         // ... data and lots of nice constructors ...
5058     };
5060     class Oper : public Rec {
5061         using Rec::Rec;
5062         // ... no data members ...
5063         // ... lots of nice utility functions ...
5064     };
5066 ##### Example, bad
5068     struct Rec2 : public Rec {
5069         int x;
5070         using Rec::Rec;
5071     };
5073     Rec2 r {"foo", 7};
5074     int val = r.x;   // uninitialized
5076 ##### Enforcement
5078 Make sure that every member of the derived class is initialized.
5080 ## <a name="SS-copy"></a>C.copy: Copy and move
5082 Value types should generally be copyable, but interfaces in a class hierarchy should not.
5083 Resource handles may or may not be copyable.
5084 Types can be defined to move for logical as well as performance reasons.
5086 ### <a name="Rc-copy-assignment"></a>C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`
5088 ##### Reason
5090 It is simple and efficient. If you want to optimize for rvalues, provide an overload that takes a `&&` (see [F.24](#Rf-pass-ref-ref)).
5092 ##### Example
5094     class Foo {
5095     public:
5096         Foo& operator=(const Foo& x)
5097         {
5098             // GOOD: no need to check for self-assignment (other than performance)
5099             auto tmp = x;
5100             std::swap(*this, tmp);
5101             return *this;
5102         }
5103         // ...
5104     };
5106     Foo a;
5107     Foo b;
5108     Foo f();
5110     a = b;    // assign lvalue: copy
5111     a = f();  // assign rvalue: potentially move
5113 ##### Note
5115 The `swap` implementation technique offers the [strong guarantee](???).
5117 ##### Example
5119 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:
5121     template<typename T>
5122     class Vector {
5123     public:
5124         Vector& operator=(const Vector&);
5125         // ...
5126     private:
5127         T* elem;
5128         int sz;
5129     };
5131     Vector& Vector::operator=(const Vector& a)
5132     {
5133         if (a.sz > sz) {
5134             // ... use the swap technique, it can't be bettered ...
5135             return *this
5136         }
5137         // ... copy sz elements from *a.elem to elem ...
5138         if (a.sz < sz) {
5139             // ... destroy the surplus elements in *this* and adjust size ...
5140         }
5141         return *this;
5142     }
5144 By writing directly to the target elements, we will get only [the basic guarantee](#???) rather than the strong guarantee offered by the `swap` technique. Beware of [self assignment](#Rc-copy-self).
5146 **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&)`.
5147 See [copy constructor vs. `clone()`](#Rc-copy-virtual).
5149 ##### Enforcement
5151 * (Simple) An assignment operator should not be virtual. Here be dragons!
5152 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
5153 * (Moderate) An assignment operator should (implicitly or explicitly) invoke all base and member assignment operators.
5154   Look at the destructor to determine if the type has pointer semantics or value semantics.
5156 ### <a name="Rc-copy-semantic"></a>C.61: A copy operation should copy
5158 ##### Reason
5160 That is the generally assumed semantics. After `x = y`, we should have `x == y`.
5161 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).
5163 ##### Example
5165     class X {   // OK: value semantics
5166     public:
5167         X();
5168         X(const X&);     // copy X
5169         void modify();   // change the value of X
5170         // ...
5171         ~X() { delete[] p; }
5172     private:
5173         T* p;
5174         int sz;
5175     };
5177     bool operator==(const X& a, const X& b)
5178     {
5179         return a.sz == b.sz && equal(a.p, a.p + a.sz, b.p, b.p + b.sz);
5180     }
5182     X::X(const X& a)
5183         :p{new T[a.sz]}, sz{a.sz}
5184     {
5185         copy(a.p, a.p + sz, a.p);
5186     }
5188     X x;
5189     X y = x;
5190     if (x != y) throw Bad{};
5191     x.modify();
5192     if (x == y) throw Bad{};   // assume value semantics
5194 ##### Example
5196     class X2 {  // OK: pointer semantics
5197     public:
5198         X2();
5199         X2(const X&) = default; // shallow copy
5200         ~X2() = default;
5201         void modify();          // change the value of X
5202         // ...
5203     private:
5204         T* p;
5205         int sz;
5206     };
5208     bool operator==(const X2& a, const X2& b)
5209     {
5210         return a.sz == b.sz && a.p == b.p;
5211     }
5213     X2 x;
5214     X2 y = x;
5215     if (x != y) throw Bad{};
5216     x.modify();
5217     if (x != y) throw Bad{};  // assume pointer semantics
5219 ##### Note
5221 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.
5223 ##### Enforcement
5225 (Not enforceable)
5227 ### <a name="Rc-copy-self"></a>C.62: Make copy assignment safe for self-assignment
5229 ##### Reason
5231 If `x = x` changes the value of `x`, people will be surprised and bad errors will occur (often including leaks).
5233 ##### Example
5235 The standard-library containers handle self-assignment elegantly and efficiently:
5237     std::vector<int> v = {3, 1, 4, 1, 5, 9};
5238     v = v;
5239     // the value of v is still {3, 1, 4, 1, 5, 9}
5241 ##### Note
5243 The default assignment generated from members that handle self-assignment correctly handles self-assignment.
5245     struct Bar {
5246         vector<pair<int, int>> v;
5247         map<string, int> m;
5248         string s;
5249     };
5251     Bar b;
5252     // ...
5253     b = b;   // correct and efficient
5255 ##### Note
5257 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)).
5259     class Foo {
5260         string s;
5261         int i;
5262     public:
5263         Foo& operator=(const Foo& a);
5264         // ...
5265     };
5267     Foo& Foo::operator=(const Foo& a)   // OK, but there is a cost
5268     {
5269         if (this == &a) return *this;
5270         s = a.s;
5271         i = a.i;
5272         return *this;
5273     }
5275 This is obviously safe and apparently efficient.
5276 However, what if we do one self-assignment per million assignments?
5277 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).
5278 Consider:
5280     Foo& Foo::operator=(const Foo& a)   // simpler, and probably much better
5281     {
5282         s = a.s;
5283         i = a.i;
5284         return *this;
5285     }
5287 `std::string` is safe for self-assignment and so are `int`. All the cost is carried by the (rare) case of self-assignment.
5289 ##### Enforcement
5291 (Simple) Assignment operators should not contain the pattern `if (this == &a) return *this;` ???
5293 ### <a name="Rc-move-assignment"></a>C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const &`
5295 ##### Reason
5297 It is simple and efficient.
5299 **See**: [The rule for copy-assignment](#Rc-copy-assignment).
5301 ##### Enforcement
5303 Equivalent to what is done for [copy-assignment](#Rc-copy-assignment).
5305 * (Simple) An assignment operator should not be virtual. Here be dragons!
5306 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
5307 * (Moderate) A move assignment operator should (implicitly or explicitly) invoke all base and member move assignment operators.
5309 ### <a name="Rc-move-semantic"></a>C.64: A move operation should move and leave its source in a valid state
5311 ##### Reason
5313 That is the generally assumed semantics.
5314 After `y = std::move(x)` the value of `y` should be the value `x` had and `x` should be in a valid state.
5316 ##### Example
5318     template<typename T>
5319     class X {   // OK: value semantics
5320     public:
5321         X();
5322         X(X&& a);          // move X
5323         void modify();     // change the value of X
5324         // ...
5325         ~X() { delete[] p; }
5326     private:
5327         T* p;
5328         int sz;
5329     };
5332     X::X(X&& a)
5333         :p{a.p}, sz{a.sz}  // steal representation
5334     {
5335         a.p = nullptr;     // set to "empty"
5336         a.sz = 0;
5337     }
5339     void use()
5340     {
5341         X x{};
5342         // ...
5343         X y = std::move(x);
5344         x = X{};   // OK
5345     } // OK: x can be destroyed
5347 ##### Note
5349 Ideally, that moved-from should be the default value of the type.
5350 Ensure that unless there is an exceptionally good reason not to.
5351 However, not all types have a default value and for some types establishing the default value can be expensive.
5352 The standard requires only that the moved-from object can be destroyed.
5353 Often, we can easily and cheaply do better: The standard library assumes that it it possible to assign to a moved-from object.
5354 Always leave the moved-from object in some (necessarily specified) valid state.
5356 ##### Note
5358 Unless there is an exceptionally strong reason not to, make `x = std::move(y); y = z;` work with the conventional semantics.
5360 ##### Enforcement
5362 (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.
5364 ### <a name="Rc-move-self"></a>C.65: Make move assignment safe for self-assignment
5366 ##### Reason
5368 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.
5370 ##### Example
5372     class Foo {
5373         string s;
5374         int i;
5375     public:
5376         Foo& operator=(Foo&& a);
5377         // ...
5378     };
5380     Foo& Foo::operator=(Foo&& a)       // OK, but there is a cost
5381     {
5382         if (this == &a) return *this;  // this line is redundant
5383         s = std::move(a.s);
5384         i = a.i;
5385         return *this;
5386     }
5388 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.
5390 ##### Note
5392 There is no know general way of avoiding a `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).
5394 ##### Note
5396 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.
5398 ##### Example
5400 Here is a way to move a pointer without a test (imagine it as code in the implementation a move assignment):
5402     // move from other.ptr to this->ptr
5403     T* temp = other.ptr;
5404     other.ptr = nullptr;
5405     delete ptr;
5406     ptr = temp;
5408 ##### Enforcement
5410 * (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`.
5411 * (Not enforceable) Look at the use of standard-library container types (incl. `string`) and consider them safe for ordinary (not life-critical) uses.
5413 ### <a name="Rc-move-noexcept"></a>C.66: Make move operations `noexcept`
5415 ##### Reason
5417 A throwing move violates most people's reasonably assumptions.
5418 A non-throwing move will be used more efficiently by standard-library and language facilities.
5420 ##### Example
5422     template<typename T>
5423     class Vector {
5424         // ...
5425         Vector(Vector&& a) noexcept :elem{a.elem}, sz{a.sz} { a.sz = 0; a.elem = nullptr; }
5426         Vector& operator=(Vector&& a) noexcept { elem = a.elem; sz = a.sz; a.sz = 0; a.elem = nullptr; }
5427         // ...
5428     public:
5429         T* elem;
5430         int sz;
5431     };
5433 These copy operations do not throw.
5435 ##### Example, bad
5437     template<typename T>
5438     class Vector2 {
5439         // ...
5440         Vector2(Vector2&& a) { *this = a; }             // just use the copy
5441         Vector2& operator=(Vector2&& a) { *this = a; }  // just use the copy
5442         // ...
5443     public:
5444         T* elem;
5445         int sz;
5446     };
5448 This `Vector2` is not just inefficient, but since a vector copy requires allocation, it can throw.
5450 ##### Enforcement
5452 (Simple) A move operation should be marked `noexcept`.
5454 ### <a name="Rc-copy-virtual"></a>C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired
5456 ##### Reason
5458 To prevent slicing, because the normal copy operations will copy only the base portion of a derived object.
5460 ##### Example, bad
5462     class B { // BAD: base class doesn't suppress copying
5463         int data;
5464         // ... nothing about copy operations, so uses default ...
5465     };
5467     class D : public B {
5468         string more_data; // add a data member
5469         // ...
5470     };
5472     auto d = make_unique<D>();
5474     // oops, slices the object; gets only d.data but drops d.more_data
5475     auto b = make_unique<B>(d);
5477 ##### Example
5479     class B { // GOOD: base class suppresses copying
5480         B(const B&) = delete;
5481         B& operator=(const B&) = delete;
5482         virtual unique_ptr<B> clone() { return /* B object */; }
5483         // ...
5484     };
5486     class D : public B {
5487         string more_data; // add a data member
5488         unique_ptr<B> clone() override { return /* D object */; }
5489         // ...
5490     };
5492     auto d = make_unique<D>();
5493     auto b = d.clone(); // ok, deep clone
5495 ##### Note
5497 It's good to return a smart pointer, but unlike with raw pointers the return type cannot be covariant (for example, `D::clone` can't return a `unique_ptr<D>`. Don't let this tempt you into returning an owning raw pointer; this is a minor drawback compared to the major robustness benefit delivered by the owning smart pointer.
5499 ##### Exception
5501 If you need covariant return types, return an `owner<derived*>`. See [C.130](#Rh-copy).
5503 ##### Enforcement
5505 A class with any virtual function should not have a copy constructor or copy assignment operator (compiler-generated or handwritten).
5507 ## C.other: Other default operation rules
5509 In addition to the operations for which the language offer default implementations,
5510 there are a few operations that are so foundational that it rules for their definition are needed:
5511 comparisons, `swap`, and `hash`.
5513 ### <a name="Rc-eqdefault"></a>C.80: Use `=default` if you have to be explicit about using the default semantics
5515 ##### Reason
5517 The compiler is more likely to get the default semantics right and you cannot implement these functions better than the compiler.
5519 ##### Example
5521     class Tracer {
5522         string message;
5523     public:
5524         Tracer(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
5525         ~Tracer() { cerr << "exiting " << message << '\n'; }
5527         Tracer(const Tracer&) = default;
5528         Tracer& operator=(const Tracer&) = default;
5529         Tracer(Tracer&&) = default;
5530         Tracer& operator=(Tracer&&) = default;
5531     };
5533 Because we defined the destructor, we must define the copy and move operations. The `= default` is the best and simplest way of doing that.
5535 ##### Example, bad
5537     class Tracer2 {
5538         string message;
5539     public:
5540         Tracer2(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
5541         ~Tracer2() { cerr << "exiting " << message << '\n'; }
5543         Tracer2(const Tracer2& a) : message{a.message} {}
5544         Tracer2& operator=(const Tracer2& a) { message = a.message; return *this; }
5545         Tracer2(Tracer2&& a) :message{a.message} {}
5546         Tracer2& operator=(Tracer2&& a) { message = a.message; return *this; }
5547     };
5549 Writing out the bodies of the copy and move operations is verbose, tedious, and error-prone. A compiler does it better.
5551 ##### Enforcement
5553 (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
5555 ### <a name="Rc-delete"></a>C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)
5557 ##### Reason
5559 In a few cases, a default operation is not desirable.
5561 ##### Example
5563     class Immortal {
5564     public:
5565         ~Immortal() = delete;   // do not allow destruction
5566         // ...
5567     };
5569     void use()
5570     {
5571         Immortal ugh;   // error: ugh cannot be destroyed
5572         Immortal* p = new Immortal{};
5573         delete p;       // error: cannot destroy *p
5574     }
5576 ##### Example
5578 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:
5580     template <class T, class D = default_delete<T>> class unique_ptr {
5581     public:
5582         // ...
5583         constexpr unique_ptr() noexcept;
5584         explicit unique_ptr(pointer p) noexcept;
5585         // ...
5586         unique_ptr(unique_ptr&& u) noexcept;   // move constructor
5587         // ...
5588         unique_ptr(const unique_ptr&) = delete; // disable copy from lvalue
5589         // ...
5590     };
5592     unique_ptr<int> make();   // make "something" and return it by moving
5594     void f()
5595     {
5596         unique_ptr<int> pi {};
5597         auto pi2 {pi};      // error: no move constructor from lvalue
5598         auto pi3 {make()};  // OK, move: the result of make() is an rvalue
5599     }
5601 ##### Enforcement
5603 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.
5605 ### <a name="Rc-ctor-virtual"></a>C.82: Don't call virtual functions in constructors and destructors
5607 ##### Reason
5609 The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class.
5610 This can be most confusing.
5611 Worse, a direct or indirect call to an unimplemented pure virtual function from a constructor or destructor results in undefined behavior.
5613 ##### Example, bad
5615     class Base {
5616     public:
5617         virtual void f() = 0;   // not implemented
5618         virtual void g();       // implemented with Base version
5619         virtual void h();       // implemented with Base version
5620     };
5622     class Derived : public Base {
5623     public:
5624         void g() override;   // provide Derived implementation
5625         void h() final;      // provide Derived implementation
5627         Derived()
5628         {
5629             // BAD: attempt to call an unimplemented virtual function
5630             f();
5632             // BAD: will call Derived::g, not dispatch further virtually
5633             g();
5635             // GOOD: explicitly state intent to call only the visible version
5636             Derived::g();
5638             // ok, no qualification needed, h is final
5639             h();
5640         }
5641     };
5643 Note that calling a specific explicitly qualified function is not a virtual call even if the function is `virtual`.
5645 **See also** [factory functions](#Rc-factory) for how to achieve the effect of a call to a derived class function without risking undefined behavior.
5647 ##### Note
5649 There is nothing inherently wrong with calling virtual functions from constructors and destructors.
5650 The semantics of such calls is type safe.
5651 However, experience shows that such calls are rarely needed, easily confuse maintainers, and become a source of errors when used by novices.
5653 ##### Enforcement
5655 * Flag calls of virtual functions from constructors and destructors.
5657 ### <a name="Rc-swap"></a>C.83: For value-like types, consider providing a `noexcept` swap function
5659 ##### Reason
5661 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).
5663 ##### Example, good
5665     class Foo {
5666         // ...
5667     public:
5668         void swap(Foo& rhs) noexcept
5669         {
5670             m1.swap(rhs.m1);
5671             std::swap(m2, rhs.m2);
5672         }
5673     private:
5674         Bar m1;
5675         int m2;
5676     };
5678 Providing a nonmember `swap` function in the same namespace as your type for callers' convenience.
5680     void swap(Foo& a, Foo& b)
5681     {
5682         a.swap(b);
5683     }
5685 ##### Enforcement
5687 * (Simple) A class without virtual functions should have a `swap` member function declared.
5688 * (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
5690 ### <a name="Rc-swap-fail"></a>C.84: A `swap` function may not fail
5692 ##### Reason
5694  `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.
5696 ##### Example, bad
5698     void swap(My_vector& x, My_vector& y)
5699     {
5700         auto tmp = x;   // copy elements
5701         x = y;
5702         y = tmp;
5703     }
5705 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.
5707 ##### Enforcement
5709 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
5711 ### <a name="Rc-swap-noexcept"></a>C.85: Make `swap` `noexcept`
5713 ##### Reason
5715  [A `swap` may not fail](#Rc-swap-fail).
5716 If a `swap` tries to exit with an exception, it's a bad design error and the program had better terminate.
5718 ##### Enforcement
5720 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
5722 ### <a name="Rc-eq"></a>C.86: Make `==` symmetric with respect to operand types and `noexcept`
5724 ##### Reason
5726 Asymmetric treatment of operands is surprising and a source of errors where conversions are possible.
5727 `==` is a fundamental operations and programmers should be able to use it without fear of failure.
5729 ##### Example
5731     class X {
5732         string name;
5733         int number;
5734     };
5736     bool operator==(const X& a, const X& b) noexcept {
5737         return a.name == b.name && a.number == b.number;
5738     }
5740 ##### Example, bad
5742     class B {
5743         string name;
5744         int number;
5745         bool operator==(const B& a) const {
5746             return name == a.name && number == a.number;
5747         }
5748         // ...
5749     };
5751 `B`'s comparison accepts conversions for its second operand, but not its first.
5753 ##### Note
5755 If a class has a failure state, like `double`'s `NaN`, there is a temptation to make a comparison against the failure state throw.
5756 The alternative is to make two failure states compare equal and any valid state compare false against the failure state.
5758 #### Note
5760 This rule applies to all the usual comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
5762 ##### Enforcement
5764 * Flag an `operator==()` for which the argument types differ; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
5765 * Flag member `operator==()`s; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
5767 ### <a name="Rc-eq-base"></a>C.87: Beware of `==` on base classes
5769 ##### Reason
5771 It is really hard to write a foolproof and useful `==` for a hierarchy.
5773 ##### Example, bad
5775     class B {
5776         string name;
5777         int number;
5778         virtual bool operator==(const B& a) const
5779         {
5780              return name == a.name && number == a.number;
5781         }
5782         // ...
5783     };
5785 `B`'s comparison accepts conversions for its second operand, but not its first.
5787     class D :B {
5788         char character;
5789         virtual bool operator==(const D& a) const
5790         {
5791             return name == a.name && number == a.number && character == a.character;
5792         }
5793         // ...
5794     };
5796     B b = ...
5797     D d = ...
5798     b == d;    // compares name and number, ignores d's character
5799     d == b;    // error: no == defined
5800     D d2;
5801     d == d2;   // compares name, number, and character
5802     B& b2 = d2;
5803     b2 == d;   // compares name and number, ignores d2's and d's character
5805 Of course there are ways of making `==` work in a hierarchy, but the naive approaches do not scale
5807 #### Note
5809 This rule applies to all the usual comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
5811 ##### Enforcement
5813 * Flag a virtual `operator==()`; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
5815 ### <a name="Rc-hash"></a>C.89: Make a `hash` `noexcept`
5817 ##### Reason
5819 Users of hashed containers use hash indirectly and don't expect simple access to throw.
5820 It's a standard-library requirement.
5822 ##### Example, bad
5824     template<>
5825     struct hash<My_type> {  // thoroughly bad hash specialization
5826         using result_type = size_t;
5827         using argument_type = My_type;
5829         size_t operator() (const My_type & x) const
5830         {
5831             size_t xs = x.s.size();
5832             if (xs < 4) throw Bad_My_type{};    // "Nobody expects the Spanish inquisition!"
5833             return hash<size_t>()(x.s.size()) ^ trim(x.s);
5834         }
5835     };
5837     int main()
5838     {
5839         unordered_map<My_type, int> m;
5840         My_type mt{ "asdfg" };
5841         m[mt] = 7;
5842         cout << m[My_type{ "asdfg" }] << '\n';
5843     }
5845 If you have to define a `hash` specialization, try simply to let it combine standard-library `hash` specializations with `^` (xor).
5846 That tends to work better than "cleverness" for non-specialists.
5848 ##### Enforcement
5850 * Flag throwing `hash`es.
5852 ## <a name="SS-containers"></a>C.con: Containers and other resource handles
5854 A container is an object holding a sequence of objects of some type; `std::vector` is the archetypical container.
5855 A resource handle is a class that owns a resource; `std::vector` is the typical resource handle; its resource is its sequence of elements.
5857 Summary of container rules:
5859 * [C.100: Follow the STL when defining a container](#Rcon-stl)
5860 * [C.101: Give a container value semantics](#Rcon-val)
5861 * [C.102: Give a container move operations](#Rcon-move)
5862 * [C.103: Give a container an initializer list constructor](#Rcon-init)
5863 * [C.104: Give a container a default constructor that sets it to empty](#Rcon-empty)
5864 * [C.105: Give a constructor and `Extent` constructor](#Rcon-val)
5865 * ???
5866 * [C.109: If a resource handle has pointer semantics, provide `*` and `->`](#rcon-ptr)
5868 **See also**: [Resources](#S-resource)
5870 ## <a name="SS-lambdas"></a>C.lambdas: Function objects and lambdas
5872 A function object is an object supplying an overloaded `()` so that you can call it.
5873 A lambda expression (colloquially often shortened to "a lambda") is a notation for generating a function object.
5874 Function objects should be cheap to copy (and therefore [passed by value](#Rf-in)).
5876 Summary:
5878 * [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)
5879 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
5880 * [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)
5881 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
5883 ## <a name="SS-hier"></a>C.hier: Class hierarchies (OOP)
5885 A class hierarchy is constructed to represent a set of hierarchically organized concepts (only).
5886 Typically base classes act as interfaces.
5887 There are two major uses for hierarchies, often named implementation inheritance and interface inheritance.
5889 Class hierarchy rule summary:
5891 * [C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)](#Rh-domain)
5892 * [C.121: If a base class is used as an interface, make it a pure abstract class](#Rh-abstract)
5893 * [C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed](#Rh-separation)
5895 Designing rules for classes in a hierarchy summary:
5897 * [C.126: An abstract class typically doesn't need a constructor](#Rh-abstract-ctor)
5898 * [C.127: A class with a virtual function should have a virtual or protected destructor](#Rh-dtor)
5899 * [C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final`](#Rh-override)
5900 * [C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance](#Rh-kind)
5901 * [C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead](#Rh-copy)
5902 * [C.131: Avoid trivial getters and setters](#Rh-get)
5903 * [C.132: Don't make a function `virtual` without reason](#Rh-virtual)
5904 * [C.133: Avoid `protected` data](#Rh-protected)
5905 * [C.134: Ensure all non-`const` data members have the same access level](#Rh-public)
5906 * [C.135: Use multiple inheritance to represent multiple distinct interfaces](#Rh-mi-interface)
5907 * [C.136: Use multiple inheritance to represent the union of implementation attributes](#Rh-mi-implementation)
5908 * [C.137: Use `virtual` bases to avoid overly general base classes](#Rh-vbase)
5909 * [C.138: Create an overload set for a derived class and its bases with `using`](#Rh-using)
5910 * [C.139: Use `final` sparingly](#Rh-final)
5911 * [C.140: Do not provide different default arguments for a virtual function and an overrider](#Rh-virtual-default-arg)
5913 Accessing objects in a hierarchy rule summary:
5915 * [C.145: Access polymorphic objects through pointers and references](#Rh-poly)
5916 * [C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable](#Rh-dynamic_cast)
5917 * [C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error](#Rh-ptr-cast)
5918 * [C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative](#Rh-ref-cast)
5919 * [C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`](#Rh-smart)
5920 * [C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s](#Rh-make_unique)
5921 * [C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s](#Rh-make_shared)
5922 * [C.152: Never assign a pointer to an array of derived class objects to a pointer to its base](#Rh-array)
5924 ### <a name="Rh-domain"></a>C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)
5926 ##### Reason
5928 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.
5930 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.
5932 ##### Example
5934     ??? Good old Shape example?
5936 ##### Example, bad
5938 Do *not* represent non-hierarchical domain concepts as class hierarchies.
5940     template<typename T>
5941     class Container {
5942     public:
5943         // list operations:
5944         virtual T& get() = 0;
5945         virtual void put(T&) = 0;
5946         virtual void insert(Position) = 0;
5947         // ...
5948         // vector operations:
5949         virtual T& operator[](int) = 0;
5950         virtual void sort() = 0;
5951         // ...
5952         // tree operations:
5953         virtual void balance() = 0;
5954         // ...
5955     };
5957 Here most overriding classes cannot implement most of the functions required in the interface well.
5958 Thus the base class becomes an implementation burden.
5959 Furthermore, the user of `Container` cannot rely on the member functions actually performing a meaningful operations reasonably efficiently;
5960 it may throw an exception instead.
5961 Thus users have to resort to run-time checking and/or
5962 not using this (over)general interface in favor of a particular interface found by a run-time type inquiry (e.g., a `dynamic_cast`).
5964 ##### Enforcement
5966 * Look for classes with lots of members that do nothing but throw.
5967 * 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`.
5969 ### <a name="Rh-abstract"></a>C.121: If a base class is used as an interface, make it a pure abstract class
5971 ##### Reason
5973 A class is more stable (less brittle) if it does not contain data.
5974 Interfaces should normally be composed entirely of public pure virtual functions and a default/empty virtual destructor.
5976 ##### Example
5978     class My_interface {
5979     public:
5980         // ...only pure virtual functions here ...
5981         virtual ~My_interface() {}   // or =default
5982     };
5984 ##### Example, bad
5986     class Goof {
5987     public:
5988         // ...only pure virtual functions here ...
5989         // no virtual destructor
5990     };
5992     class Derived : public Goof {
5993         string s;
5994         // ...
5995     };
5997     void use()
5998     {
5999         unique_ptr<Goof> p {new Derived{"here we go"}};
6000         f(p.get()); // use Derived through the Goof interface
6001         g(p.get()); // use Derived through the Goof interface
6002     } // leak
6004 The `Derived` is `delete`d through its `Goof` interface, so its `string` is leaked.
6005 Give `Goof` a virtual destructor and all is well.
6008 ##### Enforcement
6010 * Warn on any class that contains data members and also has an overridable (non-`final`) virtual function.
6012 ### <a name="Rh-separation"></a>C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed
6014 ##### Reason
6016 Such as on an ABI (link) boundary.
6018 ##### Example
6020     struct Device {
6021         virtual void write(span<const char> outbuf) = 0;
6022         virtual void read(span<char> inbuf) = 0;
6023     };
6025     class D1 : public Device {
6026         // ... data ...
6028         void write(span<const char> outbuf) override;
6029         void read(span<char> inbuf) override;
6030     };
6032     class D2 : public Device {
6033         // ... different data ...
6035         void write(span<const char> outbuf) override;
6036         void read(span<char> inbuf) override;
6037     };
6039 A user can now use `D1`s and `D2`s interchangeably through the interface provided by `Device`.
6040 Furthermore, we can update `D1` and `D2` in a ways that are not binary compatible with older versions as long as all access goes through `Device`.
6042 ##### Enforcement
6044     ???
6046 ## C.hierclass: Designing classes in a hierarchy:
6048 ### <a name="Rh-abstract-ctor"></a>C.126: An abstract class typically doesn't need a constructor
6050 ##### Reason
6052 An abstract class typically does not have any data for a constructor to initialize.
6054 ##### Example
6056     ???
6058 ##### Exception
6060 * A base class constructor that does work, such as registering an object somewhere, may need a constructor.
6061 * In extremely rare cases, you might find it reasonable for an abstract class to have a bit of data shared by all derived classes
6062   (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.
6064 ##### Enforcement
6066 Flag abstract classes with constructors.
6068 ### <a name="Rh-dtor"></a>C.127: A class with a virtual function should have a virtual or protected destructor
6070 ##### Reason
6072 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).
6074 ##### Example, bad
6076     struct B {
6077         virtual int f() = 0;
6078         // ... no user-written destructor, defaults to public nonvirtual ...
6079     };
6081     // bad: class with a resource derived from a class without a virtual destructor
6082     struct D : B {
6083         string s {"default"};
6084     };
6086     void use()
6087     {
6088         auto p = make_unique<D>();
6089         // ...
6090     } // calls B::~B only, leaks the string
6092 ##### Note
6094 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`.
6096 ##### Enforcement
6098 * A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.
6099 * Flag `delete` of a class with a virtual function but no virtual destructor.
6101 ### <a name="Rh-override"></a>C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final`
6103 ##### Reason
6105 Readability.
6106 Detection of mistakes.
6107 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.
6109 Use `virtual` only when declaring a new virtual function. Use `override` only when declaring an overrider. Use `final` only when declaring a final overrider. If a base class destructor is declared `virtual`, derived class destructors should neither be declared `virtual` nor `override`.
6111 ##### Example, bad
6113     struct B {
6114         void f1(int);
6115         virtual void f2(int) const;
6116         virtual void f3(int);
6117         // ...
6118     };
6120     struct D : B {
6121         void f1(int);        // bad (hope for a warning): D::f1() hides B::f1()
6122         void f2(int) const;  // bad (but conventional and valid): no explicit override
6123         void f3(double);     // bad (hope for a warning): D::f3() hides B::f3()
6124         // ...
6125     };
6127     struct Better : B {
6128         void f1(int) override;        // error (caught): D::f1() hides B::f1()
6129         void f2(int) const override;
6130         void f3(double) override;     // error (caught): D::f3() hides B::f3()
6131         // ...
6132     };
6134 ##### Enforcement
6136 * Compare names in base and derived classes and flag uses of the same name that does not override.
6137 * Flag overrides with neither `override` nor `final`.
6138 * Flag function declarations that use more than one of `virtual`, `override`, and `final`.
6140 ### <a name="Rh-kind"></a>C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance
6142 ##### Reason
6144 Implementation details in an interface makes the interface brittle;
6145 that is, makes its users vulnerable to having to recompile after changes in the implementation.
6146 Data in a base class increases the complexity of implementing the base and can lead to replication of code.
6148 ##### Note
6150 Definition:
6152 * interface inheritance is the use of inheritance to separate users from implementations,
6153 in particular to allow derived classes to be added and changed without affecting the users of base classes.
6154 * implementation inheritance is the use of inheritance to simplify implementation of new facilities
6155 by making useful operations available for implementers of related new operations (sometimes called "programming by difference").
6157 A pure interface class is simply a set of pure virtual functions; see [I.25](#Ri-abstract).
6159 In early OOP (e.g., in the 1980s and 1990s), implementation inheritance and interface inheritance were often mixed
6160 and bad habits die hard.
6161 Even now, mixtures are not uncommon in old code bases and in old-style teaching material.
6163 The importance of keeping the two kinds of inheritance increases
6165 * with the size of a hierarchy (e.g., dozens of derived classes),
6166 * with the length of time the hierarchy is used (e.g., decades), and
6167 * with the number of distinct organizations in which a hierarchy is used
6168 (e.g., it can be difficult to distribute an update to a base class)
6171 ##### Example, bad
6173     class Shape {   // BAD, mixed interface and implementation
6174     public:
6175         Shape();
6176         Shape(Point ce = {0, 0}, Color co = none): cent{ce}, col {co} { /* ... */}
6178         Point center() const { return cent; }
6179         Color color() const { return col; }
6181         virtual void rotate(int) = 0;
6182         virtual void move(Point p) { cent = p; redraw(); }
6184         virtual void redraw();
6186         // ...
6187     public:
6188         Point cent;
6189         Color col;
6190     };
6192     class Circle : public Shape {
6193     public:
6194         Circle(Point c, int r) :Shape{c}, rad{r} { /* ... */ }
6196         // ...
6197     private:
6198         int rad;
6199     };
6201     class Triangle : public Shape {
6202     public:
6203         Triangle(Point p1, Point p2, Point p3); // calculate center
6204         // ...
6205     };
6207 Problems:
6209 * As the hierarchy grows and more data is added to `Shape`, the constructors gets harder to write and maintain.
6210 * Why calculate the center for the `Triangle`? we may never us it.
6211 * Add a data member to `Shape` (e.g., drawing style or canvas)
6212 and all derived classes and all users needs to be reviewed, possibly changes, and probably recompiled.
6214 The implementation of `Shape::move()` is an example of implementation inheritance:
6215 we have defined `move()` once and for all for all derived classes.
6216 The more code there is in such base class member function implementations and the more data is shared by placing it in the base,
6217 the more benefits we gain - and the less stable the hierarchy is.
6219 ##### Example
6221 This Shape hierarchy can be rewritten using interface inheritance:
6223     class Shape {  // pure interface
6224     public:
6225         virtual Point center() const = 0;
6226         virtual Color color() const = 0;
6228         virtual void rotate(int) = 0;
6229         virtual void move(Point p) = 0;
6231         virtual void redraw() = 0;
6233         // ...
6234     };
6236 Note that a pure interface rarely have constructors: there is nothing to construct.
6238     class Circle : public Shape {
6239     public:
6240         Circle(Point c, int r, Color c) :cent{c}, rad{r}, col{c} { /* ... */ }
6242         Point center() const override { return cent; }
6243         Color color() const override { return col; }
6245         // ...
6246     private:
6247         Point cent;
6248         int rad;
6249         Color col;
6250     };
6252 The interface is now less brittle, but there is more work in implementing the member functions.
6253 For example, `center` has to be implemented by every class derived from `Shape`.
6255 ##### Example, dual hierarchy
6257 How can we gain the benefit of the stable hierarchies from implementation hierarchies and the benefit of implementation reuse from implementation inheritance.
6258 One popular technique is dual hierarchies.
6259 There are many ways of implementing the idea of dual hierarchies; here, we use a multiple-inheritance variant.
6261 First we devise a hierarchy of interface classes:
6263     class Shape {   // pure interface
6264     public:
6265         virtual Point center() const = 0;
6266         virtual Color color() const = 0;
6268         virtual void rotate(int) = 0;
6269         virtual void move(Point p) = 0;
6271         virtual void redraw() = 0;
6273         // ...
6274     };
6276     class Circle : public Shape {   // pure interface
6277     public:
6278         int radius() = 0;
6279         // ...
6280     };
6282 To make this interface useful, we must provide its implementation classes (here, named equivalently, but in the `Impl` namespace):
6284     class Impl::Shape : public Shape { // implementation
6285     public:
6286         // constructors, destructor
6287         // ...
6288         virtual Point center() const { /* ... */ }
6289         virtual Color color() const { /* ... */ }
6291         virtual void rotate(int) { /* ... */ }
6292         virtual void move(Point p) { /* ... */ }
6294         virtual void redraw() { /* ... */ }
6296         // ...
6297     };
6299 Now `Shape` is a poor example of a class with an implementation,
6300 but bear with us because this is just a simple example of a technique aimed at more complex hierarchies.
6303     class Impl::Circle : public Circle, public Impl::Shape {   // implementation
6304     public:
6305         // constructors, destructor
6307         int radius() { /* ... */ }
6308         // ...
6309     };
6311 And we could extend the hierarchies by adding a Smiley class (:-)):
6313     class Smiley : public Circle { // pure interface
6314     public:
6315         // ...
6316     };
6318     class Impl::Smiley : Public Smiley, public Impl::Circle {   // implementation
6319     public:
6320         // constructors, destructor
6321         // ...
6322     }
6324 There are now two hierarchies:
6326 * interface: Smiley -> Circle -> Shape
6327 * implementation: Impl::Smiley -> Impl::Circle -> Impl::Shape
6329 Since each implementation derived from its interface as well as its implementation base class we get a lattice (DAG):
6331     Smiley     ->         Circle     ->  Shape
6332       ^                     ^               ^
6333       |                     |               |
6334     Impl::Smiley -> Impl::Circle -> Impl::Shape
6336 As mentioned, this is just one way to construct a dual hierarchy.
6338 Another (related) technique for separating interface and implementation is [PIMPL](#???).
6340 ##### Note
6342 There is often a choice between offering common functionality as (implemented) base class functions and free-standing functions
6343 (in an implementation namespace).
6344 Base classes gives a shorter notation and easier access to shared data (in the base)
6345 at the cost of the functionality being available only to users of the hierarchy.
6347 ##### Enforcement
6349 * Flag a derived to base conversion to a base with both data and virtual functions
6350 (except for calls from a derived class member to a base class member)
6351 * ???
6354 ### <a name="Rh-copy"></a>C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead
6356 ##### Reason
6358 Copying a base is usually slicing. 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).
6360 ##### Example
6362     class Base {
6363     public:
6364         virtual owner<Base*> clone() = 0;
6365         virtual ~Base() = 0;
6367         Base(const Base&) = delete;
6368         Base& operator=(const Base&) = delete;
6369     };
6371     class Derived : public Base {
6372     public:
6373         owner<Derived*> clone() override;
6374         virtual ~Derived() override;
6375     };
6377 Note that because of language rules, the covariant return type cannot be a smart pointer. See also [C.67](#Rc-copy-virtual).
6379 ##### Enforcement
6381 * Flag a class with a virtual function and a non-user-defined copy operation.
6382 * Flag an assignment of base class objects (objects of a class from which another has been derived).
6384 ### <a name="Rh-get"></a>C.131: Avoid trivial getters and setters
6386 ##### Reason
6388 A trivial getter or setter adds no semantic value; the data item could just as well be `public`.
6390 ##### Example
6392     class Point {
6393         int x;
6394         int y;
6395     public:
6396         Point(int xx, int yy) : x{xx}, y{yy} { }
6397         int get_x() { return x; }
6398         void set_x(int xx) { x = xx; }
6399         int get_y() { return y; }
6400         void set_y(int yy) { y = yy; }
6401         // no behavioral member functions
6402     };
6404 Consider making such a class a `struct` -- that is, a behaviorless bunch of variables, all public data and no member functions.
6406     struct Point {
6407         int x = 0;
6408         int y = 0;
6409     };
6411 ##### Note
6413 A getter or a setter that converts from an internal type to an interface type is not trivial (it provides a form of information hiding).
6415 ##### Enforcement
6417 Flag multiple `get` and `set` member functions that simply access a member without additional semantics.
6419 ### <a name="Rh-virtual"></a>C.132: Don't make a function `virtual` without reason
6421 ##### Reason
6423 Redundant `virtual` increases run-time and object-code size.
6424 A virtual function can be overridden and is thus open to mistakes in a derived class.
6425 A virtual function ensures code replication in a templated hierarchy.
6427 ##### Example, bad
6429     template<class T>
6430     class Vector {
6431     public:
6432         // ...
6433         virtual int size() const { return sz; }   // bad: what good could a derived class do?
6434     private:
6435         T* elem;   // the elements
6436         int sz;    // number of elements
6437     };
6439 This kind of "vector" isn't meant to be used as a base class at all.
6441 ##### Enforcement
6443 * Flag a class with virtual functions but no derived classes.
6444 * Flag a class where all member functions are virtual and have implementations.
6446 ### <a name="Rh-protected"></a>C.133: Avoid `protected` data
6448 ##### Reason
6450 `protected` data is a source of complexity and errors.
6451 `protected` data complicated the statement of invariants.
6452 `protected` data inherently violates the guidance against putting data in base classes, which usually leads to having to deal virtual inheritance as well.
6454 ##### Example
6456     ???
6458 ##### Note
6460 Protected member function can be just fine.
6462 ##### Enforcement
6464 Flag classes with `protected` data.
6466 ### <a name="Rh-public"></a>C.134: Ensure all non-`const` data members have the same access level
6468 ##### Reason
6470 Prevention of logical confusion leading to errors.
6471 If the non-`const` data members don't have the same access level, the type is confused about what it's trying to do.
6472 Is it a type that maintains an invariant or simply a collection of values?
6474 ##### Discussion
6476 The core question is: What code is responsible for maintaining a meaningful/correct value for that variable?
6478 There are exactly two kinds of data members:
6480 * A: Ones that don't participate in the object's invariant. Any combination of values for these members is valid.
6481 * 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.
6483 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.
6485 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.
6487 Most classes are either all A or all B:
6489 * *All public*: If you're writing an aggregate bundle-of-variables without an invariant across those variables, then all the variables should be `public`.
6490   [By convention, declare such classes `struct` rather than `class`](#Rc-struct)
6491 * *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.
6493 ##### Exception
6495 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`).
6497 ##### Enforcement
6499 Flag any class that has non-`const` data members with different access levels.
6501 ### <a name="Rh-mi-interface"></a>C.135: Use multiple inheritance to represent multiple distinct interfaces
6503 ##### Reason
6505 Not all classes will necessarily support all interfaces, and not all callers will necessarily want to deal with all operations. Especially to break apart monolithic interfaces into "aspects" of behavior supported by a given derived class.
6507 ##### Example
6509     ???
6511 ##### Note
6513 This is a very common use of inheritance because the need for multiple different interfaces to an implementation is common
6514 and such interfaces are often not easily or naturally organized into a single-rooted hierarchy.
6516 ##### Note
6518 Such interfaces are typically abstract classes.
6520 ##### Enforcement
6524 ### <a name="Rh-mi-implementation"></a>C.136: Use multiple inheritance to represent the union of implementation attributes
6526 ##### Reason
6528  ??? Herb: Here's the second mention of implementation inheritance. I'm very skeptical, even of single implementation inheritance, never mind multiple implementation inheritance which just seems frightening -- I don't think that even policy-based design really needs to inherit from the policy types. Am I missing some good examples, or could we consider discouraging this as an anti-pattern?
6530 ##### Example
6532     ???
6534 ##### Note
6536 This a relatively rare use because implementation can often be organized into a single-rooted hierarchy.
6538 ##### Enforcement
6540 ??? Herb: How about opposite enforcement: Flag any type that inherits from more than one non-empty base class?
6542 ### <a name="Rh-vbase"></a>C.137: Use `virtual` bases to avoid overly general base classes
6544 ##### Reason
6546  ???
6548 ##### Example
6550     ???
6552 ##### Note
6556 ##### Enforcement
6560 ### <a name="Rh-using"></a>C.138: Create an overload set for a derived class and its bases with `using`
6562 ##### Reason
6566 ##### Example
6568     ???
6570 ### <a name="Rh-final"></a>C.139: Use `final` sparingly
6572 ##### Reason
6574 Capping a hierarchy with `final` is rarely needed for logical reasons and can be damaging to the extensibility of a hierarchy.
6575 Capping an individual virtual function with `final` is error-prone as that `final` can easily be overlooked when defining/overriding a set of functions.
6577 ##### Example, bad
6579     class Widget { /* ... */ };
6581     // nobody will ever want to improve My_widget (or so you thought)
6582     class My_widget final : public Widget { /* ... */ };
6584     class My_improved_widget : public My_widget { /* ... */ };  // error: can't do that
6586 ##### Example, bad
6588     struct Interface {
6589         virtual int f() = 0;
6590         virtual int g() = 0;
6591     };
6593     class My_implementation : public Interface {
6594         int f() override;
6595         int g() final;  // I want g() to be FAST!
6596         // ...
6597     };
6599     class Better_implementation : public My_implementation {
6600         int f();
6601         int g();
6602         // ...
6603     };
6605     void use(Interface* p)
6606     {
6607         int x = p->f();    // Better_implementation::f()
6608         int y = p->g();    // My_implementation::g() Surprise?
6609     }
6611     // ...
6613     use(new Better_implementation{});
6615 The problem is easy to see in a small example, but in a large hierarchy with many virtual functions, tools are required for reliably spotting such problems.
6616 Consistent use of `override` would catch this.
6618 ##### Note
6620 Claims of performance improvements from `final` should be substantiated.
6621 Too often, such claims are based on conjecture or experience with other languages.
6623 There are examples where `final` can be important for both logical and performance reasons.
6624 One example is a performance-critical AST hierarchy in a compiler or language analysis tool.
6625 New derived classes are not added every year and only by library implementers.
6626 However, misuses are (or at least have been) far more common.
6628 ##### Enforcement
6630 Flag uses of `final`.
6633 ## <a name="Rh-virtual-default-arg"></a>C.140: Do not provide different default arguments for a virtual function and an overrider
6635 ##### Reason
6637 That can cause confusion: An overrider does not inherit default arguments.
6639 ##### Example, bad
6641     class Base {
6642     public:
6643         virtual int multiply(int value, int factor = 2) = 0;
6644     };
6646     class Derived : public Base {
6647     public:
6648         int multiply(int value, int factor = 10) override;
6649     };
6651     Derived d;
6652     Base& b = d;
6654     b.multiply(10);  // these two calls will call the same function but
6655     d.multiply(10);  // with different arguments and so different results
6657 ##### Enforcement
6659 Flag default arguments on virtual functions if they differ between base and derived declarations.
6661 ## C.hier-access: Accessing objects in a hierarchy
6663 ### <a name="Rh-poly"></a>C.145: Access polymorphic objects through pointers and references
6665 ##### Reason
6667 If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.
6669 ##### Example
6671     struct B { int a; virtual int f(); };
6672     struct D : B { int b; int f() override; };
6674     void use(B b)
6675     {
6676         D d;
6677         B b2 = d;   // slice
6678         B b3 = b;
6679     }
6681     void use2()
6682     {
6683         D d;
6684         use(d);   // slice
6685     }
6687 Both `d`s are sliced.
6689 ##### Exception
6691 You can safely access a named polymorphic object in the scope of its definition, just don't slice it.
6693     void use3()
6694     {
6695         D d;
6696         d.f();   // OK
6697     }
6699 ##### Enforcement
6701 Flag all slicing.
6703 ### <a name="Rh-dynamic_cast"></a>C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable
6705 ##### Reason
6707 `dynamic_cast` is checked at run time.
6709 ##### Example
6711     struct B {   // an interface
6712         virtual void f();
6713         virtual void g();
6714     };
6716     struct D : B {   // a wider interface
6717         void f() override;
6718         virtual void h();
6719     };
6721     void user(B* pb)
6722     {
6723         if (D* pd = dynamic_cast<D*>(pb)) {
6724             // ... use D's interface ...
6725         }
6726         else {
6727             // ... make do with B's interface ...
6728         }
6729     }
6731 ##### Note
6733 Like other casts, `dynamic_cast` is overused.
6734 [Prefer virtual functions to casting](#???).
6735 Prefer [static polymorphism](#???) to hierarchy navigation where it is possible (no run-time resolution necessary)
6736 and reasonably convenient.
6738 ##### Note
6740 Some people use `dynamic_cast` where a `typeid` would have been more appropriate;
6741 `dynamic_cast` is a general "is kind of" operation for discovering the best interface to an object,
6742 whereas `typeid` is a "give me the exact type of this object" operation to discover the actual type of an object.
6743 The latter is an inherently simpler operation that ought to be faster.
6744 The latter (`typeid`) is easily hand-crafted if necessary (e.g., if working on a system where RTTI is -- for some reason -- prohibited),
6745 the former (`dynamic_cast`) is far harder to implement correctly in general.
6747 Consider:
6749     struct B {
6750         const char * name {"B"};
6751         virtual const char* id() const { return name; }
6752         // ...
6753     };
6755     struct D : B {
6756         const char * name {"D"};
6757         const char* id() const override { return name; }
6758         // ...
6759     };
6761     void use()
6762     {
6763         B* pb1 = new B;
6764         B* pb2 = new D;
6766         cout << pb1->id(); // "B"
6767         cout << pb2->id(); // "D"
6769         if (pb1->id() == pb2->id()) // *pb1 is the same type as *pb2
6770         if (pb2->id() == "D") {         // looks innocent
6771             D* pd = static_cast<D*>(pb1);
6772             // ...
6773         }
6774         // ...
6775     }
6777 The result of `pb2->id() == "D"` is actually implementation defined.
6778 We added it to warn of the dangers of home-brew RTTI.
6779 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.
6781 If you implement your own RTTI, be careful.
6783 ##### Exception
6785 If your implementation provided a really slow `dynamic_cast`, you may have to use a workaround.
6786 However, all workarounds that cannot be statically resolved involve explicit casting (typically `static_cast`) and are error-prone.
6787 You will basically be crafting your own special-purpose `dynamic_cast`.
6788 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)
6789 and that your use of `dynamic_cast` is really performance critical.
6791 We are of the opinion that current implementations of `dynamic_cast` are unnecessarily slow.
6792 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).
6793 However, compatibility makes changes difficult even if all agree that an effort to optimize is worthwhile.
6795 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.
6797 ##### Enforcement
6799 Flag all uses of `static_cast` for downcasts, including C-style casts that perform a `static_cast`.
6801 ### <a name="Rh-ptr-cast"></a>C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error
6803 ##### Reason
6805 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.
6807 ##### Example
6809     ???
6811 ##### Enforcement
6815 ### <a name="Rh-ref-cast"></a>C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative
6817 ##### Reason
6821 ##### Example
6823     ???
6825 ##### Enforcement
6829 ### <a name="Rh-smart"></a>C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`
6831 ##### Reason
6833 Avoid resource leaks.
6835 ##### Example
6837     void use(int i)
6838     {
6839         auto p = new int {7};           // bad: initialize local pointers with new
6840         auto q = make_unique<int>(9);   // ok: guarantee the release of the memory allocated for 9
6841         if (0 < i) return;              // maybe return and leak
6842         delete p;                       // too late
6843     }
6845 ##### Enforcement
6847 * Flag initialization of a naked pointer with the result of a `new`
6848 * Flag `delete` of local variable
6850 ### <a name="Rh-make_unique"></a>C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s
6852 ##### Reason
6854  `make_unique` gives a more concise statement of the construction.
6855 It also ensures exception safety in complex expressions.
6857 ##### Example
6859     unique_ptr<Foo> p {new<Foo>{7}};   // OK: but repetitive
6861     auto q = make_unique<Foo>(7);      // Better: no repetition of Foo
6863     // Not exception-safe: the compiler may interleave the computations of arguments as follows:
6864     //
6865     // 1. allocate memory for Foo,
6866     // 2. construct Foo,
6867     // 3. call bar,
6868     // 4. construct unique_ptr<Foo>.
6869     //
6870     // If bar throws, Foo will not be destroyed, and the memory allocated for it will leak.
6871     f(unique_ptr<Foo>(new Foo()), bar());
6873     // Exception-safe: calls to functions are never interleaved.
6874     f(make_unique<Foo>(), bar());
6876 ##### Enforcement
6878 * Flag the repetitive usage of template specialization list `<Foo>`
6879 * Flag variables declared to be `unique_ptr<Foo>`
6881 ### <a name="Rh-make_shared"></a>C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s
6883 ##### Reason
6885  `make_shared` gives a more concise statement of the construction.
6886 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.
6888 ##### Example
6890     // OK: but repetitive; and separate allocations for the Foo and shared_ptr's use count
6891     shared_ptr<Foo> p {new<Foo>{7}};
6893     auto q = make_shared<Foo>(7);   // Better: no repetition of Foo; one object
6895 ##### Enforcement
6897 * Flag the repetitive usage of template specialization list`<Foo>`
6898 * Flag variables declared to be `shared_ptr<Foo>`
6900 ### <a name="Rh-array"></a>C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
6902 ##### Reason
6904 Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.
6906 ##### Example
6908     struct B { int x; };
6909     struct D : B { int y; };
6911     void use(B*);
6913     D a[] = {{1, 2}, {3, 4}, {5, 6}};
6914     B* p = a;     // bad: a decays to &a[0] which is converted to a B*
6915     p[1].x = 7;   // overwrite D[0].y
6917     use(a);       // bad: a decays to &a[0] which is converted to a B*
6919 ##### Enforcement
6921 * Flag all combinations of array decay and base to derived conversions.
6922 * 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`
6924 ## <a name="SS-overload"></a>C.over: Overloading and overloaded operators
6926 You can overload ordinary functions, template functions, and operators.
6927 You cannot overload function objects.
6929 Overload rule summary:
6931 * [C.160: Define operators primarily to mimic conventional usage](#Ro-conventional)
6932 * [C.161: Use nonmember functions for symmetric operators](#Ro-symmetric)
6933 * [C.162: Overload operations that are roughly equivalent](#Ro-equivalent)
6934 * [C.163: Overload only for operations that are roughly equivalent](#Ro-equivalent-2)
6935 * [C.164: Avoid conversion operators](#Ro-conversion)
6936 * [C.165: Use `using` for customization points](#Ro-custom)
6937 * [C.166: Overload unary `&` only as part of a system of smart pointers and references](#Ro-address-of)
6938 * [C.167: Use an operator for an operation with its conventional meaning](#Ro-overload)
6939 * [C.168: Define overloaded operators in the namespace of their operands](#Ro-namespace)
6940 * [C.170: If you feel like overloading a lambda, use a generic lambda](#Ro-lambda)
6942 ### <a name="Ro-conventional"></a>C.160: Define operators primarily to mimic conventional usage
6944 ##### Reason
6946 Minimize surprises.
6948 ##### Example
6950     class X {
6951     public:
6952         // ...
6953         X& operator=(const X&); // member function defining assignment
6954         friend bool operator==(const X&, const X&); // == needs access to representation
6955                                                     // after a = b we have a == b
6956         // ...
6957     };
6959 Here, the conventional semantics is maintained: [Copies compare equal](#SS-copy).
6961 ##### Example, bad
6963     X operator+(X a, X b) { return a.v - b.v; }   // bad: makes + subtract
6965 ##### Note
6967 Non-member operators should be either friends or defined in [the same namespace as their operands](#Ro-namespace).
6968 [Binary operators should treat their operands equivalently](#Ro-symmetric).
6970 ##### Enforcement
6972 Possibly impossible.
6974 ### <a name="Ro-symmetric"></a>C.161: Use nonmember functions for symmetric operators
6976 ##### Reason
6978 If you use member functions, you need two.
6979 Unless you use a non-member function for (say) `==`, `a == b` and `b == a` will be subtly different.
6981 ##### Example
6983     bool operator==(Point a, Point b) { return a.x == b.x && a.y == b.y; }
6985 ##### Enforcement
6987 Flag member operator functions.
6989 ### <a name="Ro-equivalent"></a>C.162: Overload operations that are roughly equivalent
6991 ##### Reason
6993 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.
6995 ##### Example
6997 Consider:
6999     void print(int a);
7000     void print(int a, int base);
7001     void print(const string&);
7003 These three functions all print their arguments (appropriately). Conversely:
7005     void print_int(int a);
7006     void print_based(int a, int base);
7007     void print_string(const string&);
7009 These three functions all print their arguments (appropriately). Adding to the name just introduced verbosity and inhibits generic code.
7011 ##### Enforcement
7015 ### <a name="Ro-equivalent-2"></a>C.163: Overload only for operations that are roughly equivalent
7017 ##### Reason
7019 Having the same name for logically different functions is confusing and leads to errors when using generic programming.
7021 ##### Example
7023 Consider:
7025     void open_gate(Gate& g);   // remove obstacle from garage exit lane
7026     void fopen(const char* name, const char* mode);   // open file
7028 The two operations are fundamentally different (and unrelated) so it is good that their names differ. Conversely:
7030     void open(Gate& g);   // remove obstacle from garage exit lane
7031     void open(const char* name, const char* mode ="r");   // open file
7033 The two operations are still fundamentally different (and unrelated) but the names have been reduced to their (common) minimum, opening opportunities for confusion.
7034 Fortunately, the type system will catch many such mistakes.
7036 ##### Note
7038 Be particularly careful about common and popular names, such as `open`, `move`, `+`, and `==`.
7040 ##### Enforcement
7044 ### <a name="Ro-conversion"></a>C.164: Avoid conversion operators
7046 ##### Reason
7048 Implicit conversions can be essential (e.g., `double` to `int`) but often cause surprises (e.g., `String` to C-style string).
7050 ##### Note
7052 Prefer explicitly named conversions until a serious need is demonstrated.
7053 By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion)
7054 and frequently needed. Do not introduce implicit conversions (through conversion operators or non-`explicit` constructors)
7055 just to gain a minor convenience.
7057 ##### Example, bad
7059     class String {   // handle ownership and access to a sequence of characters
7060         // ...
7061         String(czstring p); // copy from *p to *(this->elem)
7062         // ...
7063         operator zstring() { return elem; }
7064         // ...
7065     };
7067     void user(zstring p)
7068     {
7069         if (*p == "") {
7070             String s {"Trouble ahead!"};
7071             // ...
7072             p = s;
7073         }
7074         // use p
7075     }
7077 The string allocated for `s` and assigned to `p` is destroyed before it can be used.
7079 ##### Enforcement
7081 Flag all conversion operators.
7083 ### <a name="Ro-custom"></a>C.165: Use `using` for customization points
7085 ##### Reason
7087 To find function objects and functions defined in a separate namespace to "customize" a common function.
7089 ##### Example
7091 Consider `swap`. It is a general (standard library) function with a definition that will work for just about any type.
7092 However, it is desirable to define specific `swap()`s for specific types.
7093 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.
7095     namespace N {
7096         My_type X { /* ... */ };
7097         void swap(X&, X&);   // optimized swap for N::X
7098         // ...
7099     }
7101     void f1(N::X& a, N::X& b)
7102     {
7103         std::swap(a, b);   // probably not what we wanted: calls std::swap()
7104     }
7106 The `std::swap()` in `f1()` does exactly what we asked it to do: it calls the `swap()` in namespace `std`.
7107 Unfortunately, that's probably not what we wanted.
7108 How do we get `N::X` considered?
7110     void f2(N::X& a, N::X& b)
7111     {
7112         swap(a, b);   // calls N::swap
7113     }
7115 But that may not be what we wanted for generic code.
7116 There, we typically want the specific function if it exists and the general function if not.
7117 This is done by including the general function in the lookup for the function:
7119     void f3(N::X& a, N::X& b)
7120     {
7121         using std::swap;  // make std::swap available
7122         swap(a, b);        // calls N::swap if it exists, otherwise std::swap
7123     }
7125 ##### Enforcement
7127 Unlikely, except for known customization points, such as `swap`.
7128 The problem is that the unqualified and qualified lookups both have uses.
7130 ### <a name="Ro-address-of"></a>C.166: Overload unary `&` only as part of a system of smart pointers and references
7132 ##### Reason
7134 The `&` operator is fundamental in C++.
7135 Many parts of the C++ semantics assumes its default meaning.
7137 ##### Example
7139     class Ptr { // a somewhat smart pointer
7140         Ptr(X* pp) :p(pp) { /* check */ }
7141         X* operator->() { /* check */ return p; }
7142         X operator[](int i);
7143         X operator*();
7144     private:
7145         T* p;
7146     };
7148     class X {
7149         Ptr operator&() { return Ptr{this}; }
7150         // ...
7151     };
7153 ##### Note
7155 If you "mess with" operator `&` be sure that its definition has matching meanings for `->`, `[]`, `*`, and `.` on the result type.
7156 Note that operator `.` currently cannot be overloaded so a perfect system is impossible.
7157 We hope to remedy that: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf>.
7158 Note that `std::addressof()` always yields a built-in pointer.
7160 ##### Enforcement
7162 Tricky. Warn if `&` is user-defined without also defining `->` for the result type.
7164 ### <a name="Ro-namespace"></a>C.168: Define overloaded operators in the namespace of their operands
7166 ##### Reason
7168 Readability.
7169 Ability for find operators using ADL.
7170 Avoiding inconsistent definition in different namespaces
7172 ##### Example
7174     struct S { };
7175     bool operator==(S, S);   // OK: in the same namespace as S, and even next to S
7176     S s;
7178     bool x = (s == s);
7180 This is what a default `==` would do, if we had such defaults.
7182 ##### Example
7184     namespace N {
7185         struct S { };
7186         bool operator==(S, S);   // OK: in the same namespace as S, and even next to S
7187     }
7189     N::S s;
7191     bool x = (s == s);  // finds N::operator==() by ADL
7193 ##### Example, bad
7195     struct S { };
7196     S s;
7198     namespace N {
7199         S::operator!(S a) { return true; }
7200         S not_s = !s;
7201     }
7203     namespace M {
7204         S::operator!(S a) { return false; }
7205         S not_s = !s;
7206     }
7208 Here, the meaning of `!s` differs in `N` and `M`.
7209 This can be most confusing.
7210 Remove the definition of `namespace M` and the confusion is replaced by an opportunity to make the mistake.
7212 ##### Note
7214 If a binary operator is defined for two types that are defined in different namespaces, you cannot follow this rule.
7215 For example:
7217     Vec::Vector operator*(const Vec::Vector&, const Mat::Matrix&);
7219 This may be something best avoided.
7221 ##### See also
7223 This is a special case of the rule that [helper functions should be defined in the same namespace as their class](#Rc-helper).
7225 ##### Enforcement
7227 * Flag operator definitions that are not it the namespace of their operands
7229 ### <a name="Ro-overload"></a>C.167: Use an operator for an operation with its conventional meaning
7231 ##### Reason
7233 Readability. Convention. Reusability. Support for generic code
7235 ##### Example
7237     void cout_my_class(const My_class& c) // confusing, not conventional,not generic
7238     {
7239         std::cout << /* class members here */;
7240     }
7242     std::ostream& operator<<(std::ostream& os, const my_class& c) // OK
7243     {
7244         return os << /* class members here */;
7245     }
7247 By itself, `cout_my_class` would be OK, but it is not usable/composable with code that rely on the `<<` convention for output:
7249     My_class var { /* ... */ };
7250     // ...
7251     cout << "var = " << var << '\n';
7253 ##### Note
7255 There are strong and vigorous conventions for the meaning most operators, such as
7257 * comparisons (`==`, `!=`, `<`, `<=`, `>`, and `>=`),
7258 * arithmetic operations (`+`, `-`, `*`, `/`, and `%`)
7259 * access operations (`.`, `->`, unary `*`, and `[]`)
7260 * assignment (`=`)
7262 Don't define those unconventionally and don't invent your own names for them.
7264 ##### Enforcement
7266 Tricky. Requires semantic insight.
7268 ### <a name="Ro-lambda"></a>C.170: If you feel like overloading a lambda, use a generic lambda
7270 ##### Reason
7272 You cannot overload by defining two different lambdas with the same name.
7274 ##### Example
7276     void f(int);
7277     void f(double);
7278     auto f = [](char);   // error: cannot overload variable and function
7280     auto g = [](int) { /* ... */ };
7281     auto g = [](double) { /* ... */ };   // error: cannot overload variables
7283     auto h = [](auto) { /* ... */ };   // OK
7285 ##### Enforcement
7287 The compiler catches the attempt to overload a lambda.
7289 ## <a name="SS-union"></a>C.union: Unions
7291 A `union` is a `struct` where all members start at the same address so that it can hold only one member at a time.
7292 A `union` does not keep track of which member is stored so the programmer has to get it right;
7293 this is inherently error-prone, but there are ways to compensate.
7295 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*.
7297 Union rule summary:
7299 * [C.180: Use `union`s to save Memory](#Ru-union)
7300 * [C.181: Avoid "naked" `union`s](#Ru-naked)
7301 * [C.182: Use anonymous `union`s to implement tagged unions](#Ru-anonymous)
7302 * [C.183: Don't use a `union` for type punning](#Ru-pun)
7303 * ???
7305 ### <a name="Ru-union"></a>C.180: Use `union`s to save memory
7307 ##### Reason
7309 A `union` allows a single piece of memory to be used for different types of objects at different times.
7310 Consequently, it can be used to save memory when we have several objects that are never used at the same time.
7312 ##### Example
7314     union Value {
7315         int x;
7316         double d;
7317     };
7319     Value v = { 123 };  // now v holds an int
7320     cout << v.x << '\n';    // write 123
7321     v.d = 987.654;  // now v holds a double
7322     cout << v.d << '\n';    // write 987.654
7324 But heed the warning: [Avoid "naked" `union`s](#Ru-naked)
7326 ##### Example
7328     // Short string optimization
7329     
7330     constexpr size_t buffer_size = 16; // Slightly larger than the size of a pointer
7331     
7332     class Immutable_string {
7333     public:
7334         Immutable_string(const char* str) :
7335             size(strlen(str))
7336         {
7337             if (size < buffer_size)
7338                 strcpy_s(string_buffer, buffer_size, str);
7339             else {
7340                 string_ptr = new char[size + 1];
7341                 strcpy_s(string_ptr, size + 1, str);
7342             }
7343         }
7344     
7345         ~Immutable_string()
7346         {
7347             if (size >= buffer_size)
7348                 delete string_ptr;
7349         }
7350     
7351         const char* get_str() const
7352         {
7353             return (size < buffer_size) ? string_buffer : string_ptr;
7354         }
7355     
7356     private:
7357         // If the string is short enough, we store the string itself
7358         // instead of a pointer to the string.
7359         union {
7360             char* string_ptr;
7361             char string_buffer[buffer_size];
7362         };
7363     
7364         const size_t size;
7365     };
7367 ##### Enforcement
7371 ### <a name="Ru-naked"></a>C.181: Avoid "naked" `union`s
7373 ##### Reason
7375 A *naked union* is a union without an associated indicator which member (if any) it holds,
7376 so that the programmer has to keep track.
7377 Naked unions are a source of type errors.
7379 ###### Example, bad
7381     union Value {
7382         int x;
7383         double d;
7384     };
7386     Value v;
7387     v.d = 987.654;  // v holds a double
7389 So far, so good, but we can easily misuse the `union`:
7391     cout << v.x << '\n';    // BAD, undefined behavior: v holds a double, but we read it as an int
7393 Note that the type error happened without any explicit cast.
7394 When we tested that program the last value printed was `1683627180` which it the integer value for the bit pattern for `987.654`.
7395 What we have here is an "invisible" type error that happens to give a result that could easily look innocent.
7397 And, talking about "invisible", this code produced no output:
7399     v.x = 123;
7400     cout << v.d << '\n';    // BAD: undefined behavior
7402 ###### Alternative
7404 Wrap a `union` in a class together with a type field.
7406 The soon-to-be-standard `variant` type (to be found in `<variant>`) does that for you:
7408     variant<int, double> v;
7409     v = 123;        // v holds an int
7410     int x = get<int>(v);
7411     v = 123.456;    // v holds a double
7412     w = get<double>(v);
7414 ##### Enforcement
7418 ### <a name="Ru-anonymous"></a>C.182: Use anonymous `union`s to implement tagged unions
7420 ##### Reason
7422 A well-designed tagged union is type safe.
7423 An *anonymous* union simplifies the definition of a class with a (tag, union) pair.
7425 ##### Example
7427 This example is mostly borrowed from TC++PL4 pp216-218.
7428 You can look there for an explanation.
7430 The code is somewhat elaborate.
7431 Handling a type with user-defined assignment and destructor is tricky.
7432 Saving programmers from having to write such code is one reason for including `variant` in the standard.
7434     class Value { // two alternative representations represented as a union
7435     private:
7436         enum class Tag { number, text };
7437         Tag type; // discriminant
7439         union { // representation (note: anonymous union)
7440             int i;
7441             string s; // string has default constructor, copy operations, and destructor
7442         };
7443     public:
7444         struct Bad_entry { }; // used for exceptions
7446         ~Value();
7447         Value& operator=(const Value&);   // necessary because of the string variant
7448         Value(const Value&);
7449         // ...
7450         int number() const;
7451         string text() const;
7453         void set_number(int n);
7454         void set_text(const string&);
7455         // ...
7456     };
7458     int Value::number() const
7459     {
7460         if (type != Tag::number) throw Bad_entry{};
7461         return i;
7462     }
7464     string Value::text() const
7465     {
7466         if (type != Tag::text) throw Bad_entry{};
7467         return s;
7468     }
7470     void Value::set_number(int n)
7471     {
7472         if (type == Tag::text) {
7473             s.~string();      // explicitly destroy string
7474             type = Tag::number;
7475         }
7476         i = n;
7477     }
7479     void Value::set_text(const string& ss)
7480     {
7481         if (type == Tag::text)
7482             s = ss;
7483         else {
7484             new(&s) string{ss};   // placement new: explicitly construct string
7485             type = Tag::text;
7486         }
7487     }
7489     Value& Value::operator=(const Value& e)   // necessary because of the string variant
7490     {
7491         if (type == Tag::text && e.type == Tag::text) {
7492             s = e.s;    // usual string assignment
7493             return *this;
7494         }
7496         if (type == Tag::text) s.~string(); // explicit destroy
7498         switch (e.type) {
7499         case Tag::number:
7500             i = e.i;
7501             break;
7502         case Tag::text:
7503             new(&s)(e.s);   // placement new: explicit construct
7504             type = e.type;
7505         }
7507         return *this;
7508     }
7510     Value::~Value()
7511     {
7512         if (type == Tag::text) s.~string(); // explicit destroy
7513     }
7515 ##### Enforcement
7519 ### <a name="Ru-pun"></a>C.183: Don't use a `union` for type punning
7521 ##### Reason
7523 It is undefined behavior to read a `union` member with a different type from the one with which it was written.
7524 Such punning is invisible, or at least harder to spot than using a named cast.
7525 Type punning using a `union` is a source of errors.
7527 ##### Example, bad
7529     union Pun {
7530         int x;
7531         unsigned char c[sizeof(int)];
7532     };
7534 The idea of `Pun` is to be able to look at the character representation of an `int`.
7536     void bad(Pun& u)
7537     {
7538         u.x = 'x';
7539         cout << u.c[0] << '\n';     // undefined behavior
7540     }
7542 If you wanted to see the bytes of an `int`, use a (named) cast:
7544     void if_you_must_pun(int& x)
7545     {
7546         auto p = reinterpret_cast<unsigned char*>(&x);
7547         cout << p[0] << '\n';     // undefined behavior
7548         // ...
7549     }
7551 Accessing the result of an `reinterpret_cast` to a different type from the objects declared type is still undefined behavior,
7552 but at least we can see that something tricky is going on.
7554 ##### Note
7556 Unfortunately, `union`s are commonly used for type punning.
7557 We don't consider "sometimes, it works as expected" a strong argument.
7559 ##### Enforcement
7565 # <a name="S-enum"></a>Enum: Enumerations
7567 Enumerations are used to define sets of integer values and for defining types for such sets of values.
7568 There are two kind of enumerations, "plain" `enum`s and `class enum`s.
7570 Enumeration rule summary:
7572 * [Enum.1: Prefer enumerations over macros](#Renum-macro)
7573 * [Enum.2: Use enumerations to represent sets of related named constants](#Renum-set)
7574 * [Enum.3: Prefer `enum class`es over "plain" `enum`s](#Renum-class)
7575 * [Enum.4: Define operations on enumerations for safe and simple use](#Renum-oper)
7576 * [Enum.5: Don't use `ALL_CAPS` for enumerators](#Renum-caps)
7577 * [Enum.6: Avoid unnamed enumerations](#Renum-unnamed)
7578 * [Enum.7: Specify the underlying type of an enumeration only when necessary](#Renum-underlying)
7579 * [Enum.8: Specify enumerator values only when necessary](#Renum-value)
7581 ### <a name="Renum-macro"></a>Enum.1: Prefer enumerations over macros
7583 ##### Reason
7585 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.
7587 ##### Example
7589 First some bad old code:
7591     // webcolors.h (third party header)
7592     #define RED   0xFF0000
7593     #define GREEN 0x00FF00
7594     #define BLUE  0x0000FF
7596     // productinfo.h
7597     // The following define product subtypes based on color
7598     #define RED    0
7599     #define PURPLE 1
7600     #define BLUE   2
7602     int webby = BLUE;   // webby == 2; probably not what was desired
7604 Instead use an `enum`:
7606     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
7607     enum class Product_info { red = 0, purple = 1, blue = 2 };
7609     int webby = blue;   // error: be specific
7610     Web_color webby = Web_color::blue;
7612 We used an `enum class` to avoid name clashes.
7614 ##### Enforcement
7616 Flag macros that define integer values.
7619 ### <a name="Renum-set"></a>Enum.2: Use enumerations to represent sets of related named constants
7621 ##### Reason
7623 An enumeration shows the enumerators to be related and can be a named type.
7627 ##### Example
7629     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
7632 ##### Note
7634 Switching on an enumeration is common and the compiler can warn against unusual patterns of case labels. For example:
7636     enum class Product_info { red = 0, purple = 1, blue = 2 };
7638     void print(Product_info inf)
7639     {
7640         switch (inf) {
7641         case Product_info::red: cout << "red"; break;
7642         case Product_info::purple: cout << "purple"; break;
7643         }
7644     }
7646 Such off-by-one switch`statements are often the results of an added enumerator and insufficient testing.
7648 ##### Enforcement
7650 * Flag `switch`-statements where the `case`s cover most but not all enumerators of an enumeration.
7651 * Flag `switch`-statements where the `case`s cover a few enumerators of an enumeration, but has no `default`.
7654 ### <a name="Renum-class"></a>Enum.3: Prefer class enums over "plain" enums
7656 ##### Reason
7658 To minimize surprises: traditional enums convert to int too readily.
7660 ##### Example
7662     void Print_color(int color);
7664     enum Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
7665     enum Product_info { Red = 0, Purple = 1, Blue = 2 };
7667     Web_color webby = Web_color::blue;
7669     // Clearly at least one of these calls is buggy.
7670     Print_color(webby);
7671     Print_color(Product_info::Blue);
7673 Instead use an `enum class`:
7675     void Print_color(int color);
7677     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
7678     enum class Product_info { red = 0, purple = 1, blue = 2 };
7680     Web_color webby = Web_color::blue;
7681     Print_color(webby);  // Error: cannot convert Web_color to int.
7682     Print_color(Product_info::Red);  // Error: cannot convert Product_info to int.
7684 ##### Enforcement
7686 (Simple) Warn on any non-class `enum` definition.
7688 ### <a name="Renum-oper"></a>Enum.4: Define operations on enumerations for safe and simple use
7690 ##### Reason
7692 Convenience of use and avoidance of errors.
7694 ##### Example
7696     enum class Day { mon, tue, wed, thu, fri, sat, sun };
7698     Day operator++(Day& d)
7699     {
7700         return d == Day::sun ? Day::mon : Day{++d};
7701     }
7703     Day today = Day::sat;
7704     Day tomorrow = ++today;
7706 ##### Enforcement
7708 Flag repeated expressions cast back into an enumeration.
7711 ### <a name="Renum-caps"></a>Enum.5: Don't use `ALL_CAPS` for enumerators
7713 ##### Reason
7715 Avoid clashes with macros.
7717 ##### Example, bad
7719      // webcolors.h (third party header)
7720     #define RED   0xFF0000
7721     #define GREEN 0x00FF00
7722     #define BLUE  0x0000FF
7724     // productinfo.h
7725     // The following define product subtypes based on color
7727     enum class Product_info { RED, PURPLE, BLUE };   // syntax error
7729 ##### Enforcement
7731 Flag ALL_CAPS enumerators.
7733 ### <a name="Renum-unnamed"></a>Enum.6: Avoid unnamed enumerations
7735 ##### Reason
7737 If you can't name an enumeration, the values are not related
7739 ##### Example, bad
7741     enum { red = 0xFF0000, scale = 4, is_signed = 1 };
7743 Such code is not uncommon in code written before there were convenient alternative ways of specifying integer constants.
7745 ##### Alternative
7747 Use `constexpr` values instead. For example:
7749     constexpr int red = 0xFF0000;
7750     constexpr short scale = 4;
7751     constexpr bool is_signed = true;
7753 ##### Enforcement
7755 Flag unnamed enumerations.
7758 ### <a name="Renum-underlying"></a>Enum.7: Specify the underlying type of an enumeration only when necessary
7760 ##### Reason
7762 The default is the easiest to read and write.
7763 `int` is the default integer type.
7764 `int` is compatible with C `enum`s.
7766 ##### Example
7768     enum class Direction : char { n, s, e, w,
7769                                   ne, nw, se, sw };  // underlying type saves space
7771     enum class Web_color : int { red   = 0xFF0000,
7772                                  green = 0x00FF00,
7773                                  blue  = 0x0000FF };  // underlying type is redundant
7775 ##### Note
7777 Specifying the underlying type is necessary in forward declarations of enumerations:
7779     enum Flags : char;
7781     void f(Flags);
7783     // ....
7785     enum flags : char { /* ... */ };
7788 ##### Enforcement
7790 ????
7793 ### <a name="Renum-value"></a>Enum.8: Specify enumerator values only when necessary
7795 ##### Reason
7797 It's the simplest.
7798 It avoids duplicate enumerator values.
7799 The default gives a consecutive set of values that is good for `switch`-statement implementations.
7801 ##### Example
7803     enum class Col1 { red, yellow, blue };
7804     enum class Col2 { red = 1, yellow = 2, blue = 2 }; // typo
7805     enum class Month { jan = 1, feb, mar, apr, may, jun,
7806                        jul, august, sep, oct, nov, dec }; // starting with 1 is conventional
7807     enum class Base_flag { dec = 1, oct = dec << 1, hex = dec << 2 }; // set of bits
7809 Specifying values is necessary to match conventional values (e.g., `Month`)
7810 and where consecutive values are undesirable (e.g., to get separate bits as in `Base_flag`).
7812 ##### Enforcement
7814 * Flag duplicate enumerator values
7815 * Flag explicitly specified all-consecutive enumerator values
7818 # <a name="S-resource"></a>R: Resource management
7820 This section contains rules related to resources.
7821 A resource is anything that must be acquired and (explicitly or implicitly) released, such as memory, file handles, sockets, and locks.
7822 The reason it must be released is typically that it can be in short supply, so even delayed release may do harm.
7823 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.
7824 An entity that is responsible for releasing a resource is called an owner.
7826 There are a few cases where leaks can be acceptable or even optimal:
7827 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.
7828 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.
7829 Here, we ignore such cases.
7831 * Resource management rule summary:
7833   * [R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)](#Rr-raii)
7834   * [R.2: In interfaces, use raw pointers to denote individual objects (only)](#Rr-use-ptr)
7835   * [R.3: A raw pointer (a `T*`) is non-owning](#Rr-ptr)
7836   * [R.4: A raw reference (a `T&`) is non-owning](#Rr-ref)
7837   * [R.5: Prefer scoped objects](#Rr-scoped)
7838   * [R.6: Avoid non-`const` global variables](#Rr-global)
7840 * Allocation and deallocation rule summary:
7842   * [R.10: Avoid `malloc()` and `free()`](#Rr-mallocfree)
7843   * [R.11: Avoid calling `new` and `delete` explicitly](#Rr-newdelete)
7844   * [R.12: Immediately give the result of an explicit resource allocation to a manager object](#Rr-immediate-alloc)
7845   * [R.13: Perform at most one explicit resource allocation in a single expression statement](#Rr-single-alloc)
7846   * [R.14: ??? array vs. pointer parameter](#Rr-ap)
7847   * [R.15: Always overload matched allocation/deallocation pairs](#Rr-pair)
7849 * <a name="Rr-summary-smartptrs"></a>Smart pointer rule summary:
7851   * [R.20: Use `unique_ptr` or `shared_ptr` to represent ownership](#Rr-owner)
7852   * [R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership](#Rr-unique)
7853   * [R.22: Use `make_shared()` to make `shared_ptr`s](#Rr-make_shared)
7854   * [R.23: Use `make_unique()` to make `unique_ptr`s](#Rr-make_unique)
7855   * [R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s](#Rr-weak_ptr)
7856   * [R.30: Take smart pointers as parameters only to explicitly express lifetime semantics](#Rr-smartptrparam)
7857   * [R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`](#Rr-smart)
7858   * [R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`](#Rr-uniqueptrparam)
7859   * [R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the `widget`](#Rr-reseat)
7860   * [R.34: Take a `shared_ptr<widget>` parameter to express that a function is part owner](#Rr-sharedptrparam-owner)
7861   * [R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer](#Rr-sharedptrparam)
7862   * [R.36: Take a `const shared_ptr<widget>&` parameter to express that it might retain a reference count to the object ???](#Rr-sharedptrparam-const)
7863   * [R.37: Do not pass a pointer or reference obtained from an aliased smart pointer](#Rr-smartptrget)
7865 ### <a name="Rr-raii"></a>R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)
7867 ##### Reason
7869 To avoid leaks and the complexity of manual resource management.
7870 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`.
7871 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.
7873 ##### Example, bad
7875 Consider:
7877     void send(X* x, cstring_span destination)
7878     {
7879         auto port = open_port(destination);
7880         my_mutex.lock();
7881         // ...
7882         send(port, x);
7883         // ...
7884         my_mutex.unlock();
7885         close_port(port);
7886         delete x;
7887     }
7889 In this code, you have to remember to `unlock`, `close_port`, and `delete` on all paths, and do each exactly once.
7890 Further, if any of the code marked `...` throws an exception, then `x` is leaked and `my_mutex` remains locked.
7892 ##### Example
7894 Consider:
7896     void send(unique_ptr<X> x, cstring_span destination)  // x owns the X
7897     {
7898         Port port{destination};            // port owns the PortHandle
7899         lock_guard<mutex> guard{my_mutex}; // guard owns the lock
7900         // ...
7901         send(port, x);
7902         // ...
7903     } // automatically unlocks my_mutex and deletes the pointer in x
7905 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.
7907 What is `Port`? A handy wrapper that encapsulates the resource:
7909     class Port {
7910         PortHandle port;
7911     public:
7912         Port(cstring_span destination) : port{open_port(destination)} { }
7913         ~Port() { close_port(port); }
7914         operator PortHandle() { return port; }
7916         // port handles can't usually be cloned, so disable copying and assignment if necessary
7917         Port(const Port&) = delete;
7918         Port& operator=(const Port&) = delete;
7919     };
7921 ##### Note
7923 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`](#S-gsl)
7925 **See also**: [RAII](#Rr-raii).
7927 ### <a name="Rr-use-ptr"></a>R.2: In interfaces, use raw pointers to denote individual objects (only)
7929 ##### Reason
7931 Arrays are best represented by a container type (e.g., `vector` (owning)) or a `span` (non-owning).
7932 Such containers and views hold sufficient information to do range checking.
7934 ##### Example, bad
7936     void f(int* p, int n)   // n is the number of elements in p[]
7937     {
7938         // ...
7939         p[2] = 7;   // bad: subscript raw pointer
7940         // ...
7941     }
7943 The compiler does not read comments, and without reading other code you do not know whether `p` really points to `n` elements.
7944 Use a `span` instead.
7946 ##### Example
7948     void g(int* p, int fmt)   // print *p using format #fmt
7949     {
7950         // ... uses *p and p[0] only ...
7951     }
7953 ##### Exception
7955 C-style strings are passed as single pointers to a zero-terminated sequence of characters.
7956 Use `zstring` rather than `char*` to indicate that you rely on that convention.
7958 ##### Note
7960 Many current uses of pointers to a single element could be references.
7961 However, where `nullptr` is a possible value, a reference may not be an reasonable alternative.
7963 ##### Enforcement
7965 * Flag pointer arithmetic (including `++`) on a pointer that is not part of a container, view, or iterator.
7966   This rule would generate a huge number of false positives if applied to an older code base.
7967 * Flag array names passed as simple pointers
7969 ### <a name="Rr-ptr"></a>R.3: A raw pointer (a `T*`) is non-owning
7971 ##### Reason
7973 There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning.
7974 We want owning pointers identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
7976 ##### Example
7978     void f()
7979     {
7980         int* p1 = new int{7};           // bad: raw owning pointer
7981         auto p2 = make_unique<int>(7);  // OK: the int is owned by a unique pointer
7982         // ...
7983     }
7985 The `unique_ptr` protects against leaks by guaranteeing the deletion of its object (even in the presence of exceptions). The `T*` does not.
7987 ##### Example
7989     template<typename T>
7990     class X {
7991         // ...
7992     public:
7993         T* p;   // bad: it is unclear whether p is owning or not
7994         T* q;   // bad: it is unclear whether q is owning or not
7995     };
7997 We can fix that problem by making ownership explicit:
7999     template<typename T>
8000     class X2 {
8001         // ...
8002     public:
8003         owner<T*> p;  // OK: p is owning
8004         T* q;         // OK: q is not owning
8005     };
8007 ##### Exception
8009 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.
8010 The fact that there are billions of lines of code that violate this rule against owning `T*`s cannot be ignored.
8011 We'd love to see program transformation tools turning 20-year-old "legacy" code into shiny modern code,
8012 we encourage the development, deployment and use of such tools,
8013 we hope the guidelines will help the development of such tools,
8014 and we even contributed (and contribute) to the research and development in this area.
8015 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.
8017 This code cannot all be rewritten (ever assuming good code transformation software), especially not soon.
8018 This problem cannot be solved (at scale) by transforming all owning pointers to `unique_ptr`s and `shared_ptr`s,
8019 partly because we need/use owning "raw pointers" as well as simple pointers in the implementation of our fundamental resource handles.
8020 For example, common `vector` implementations have one owning pointer and two non-owning pointers.
8021 Many ABIs (and essentially all interfaces to C code) use `T*`s, some of them owning.
8022 Some interfaces cannot be simply annotated with `owner` because they need to remain compilable as C
8023 (although this would be a rare good use for a macro, that expands to `owner` in C++ mode only).
8025 ##### Note
8027 `owner<T*>` has no default semantics beyond `T*`. It can be used without changing any code using it and without affecting ABIs.
8028 It is simply a indicator to programmers and analysis tools.
8029 For example, if an `owner<T*>` is a member of a class, that class better have a destructor that `delete`s it.
8031 ##### Example, bad
8033 Returning a (raw) pointer imposes a life-time management uncertainty on the caller; that is, who deletes the pointed-to object?
8035     Gadget* make_gadget(int n)
8036     {
8037         auto p = new Gadget{n};
8038         // ...
8039         return p;
8040     }
8042     void caller(int n)
8043     {
8044         auto p = make_gadget(n);   // remember to delete p
8045         // ...
8046         delete p;
8047     }
8049 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)):
8051     Gadget make_gadget(int n)
8052     {
8053         Gadget g{n};
8054         // ...
8055         return g;
8056     }
8058 ##### Note
8060 This rule applies to factory functions.
8062 ##### Note
8064 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."
8066 ##### Enforcement
8068 * (Simple) Warn on `delete` of a raw pointer that is not an `owner<T>`.
8069 * (Moderate) Warn on failure to either `reset` or explicitly `delete` an `owner<T>` pointer on every code path.
8070 * (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
8071 * (Simple) Warn if a function returns an object that was allocated within the function but has a move constructor.
8072   Suggest considering returning it by value instead.
8074 ### <a name="Rr-ref"></a>R.4: A raw reference (a `T&`) is non-owning
8076 ##### Reason
8078 There is nothing (in the C++ standard or in most code) to say otherwise and most raw references are non-owning.
8079 We want owners identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
8081 ##### Example
8083     void f()
8084     {
8085         int& r = *new int{7};  // bad: raw owning reference
8086         // ...
8087         delete &r;             // bad: violated the rule against deleting raw pointers
8088     }
8090 **See also**: [The raw pointer rule](#Rr-ptr)
8092 ##### Enforcement
8094 See [the raw pointer rule](#Rr-ptr)
8096 ### <a name="Rr-scoped"></a>R.5: Don't heap-allocate unnecessarily
8098 ##### Reason
8100 A scoped object is a local object, a global object, or a member.
8101 This implies that there is no separate allocation and deallocation cost in excess of that already used for the containing scope or object.
8102 The members of a scoped object are themselves scoped and the scoped object's constructor and destructor manage the members' lifetimes.
8104 ##### Example
8106 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:
8108     void f(int n)
8109     {
8110         auto p = new Gadget{n};
8111         // ...
8112         delete p;
8113     }
8115 Instead, use a local variable:
8117     void f(int n)
8118     {
8119         Gadget g{n};
8120         // ...
8121     }
8123 ##### Enforcement
8125 * (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.
8126 * (Simple) Warn if a local `Unique_ptr` or `Shared_ptr` is not moved, copied, reassigned or `reset` before its lifetime ends.
8128 ### <a name="Rr-global"></a>R.6: Avoid non-`const` global variables
8130 ##### Reason
8132 Global variables can be accessed from everywhere so they can introduce surprising dependencies between apparently unrelated objects.
8133 They are a notable source of errors.
8135 **Warning**: The initialization of global objects is not totally ordered.
8136 If you use a global object initialize it with a constant.
8137 Note that it is possible to get undefined initialization order even for `const` objects.
8139 ##### Exception
8141 A global object is often better than a singleton.
8143 ##### Exception
8145 An immutable (`const`) global does not introduce the problems we try to avoid by banning global objects.
8147 ##### Enforcement
8149 (??? NM: Obviously we can warn about non-`const` statics ... do we want to?)
8151 ## <a name="SS-alloc"></a>R.alloc: Allocation and deallocation
8153 ### <a name="Rr-mallocfree"></a>R.10: Avoid `malloc()` and `free()`
8155 ##### Reason
8157  `malloc()` and `free()` do not support construction and destruction, and do not mix well with `new` and `delete`.
8159 ##### Example
8161     class Record {
8162         int id;
8163         string name;
8164         // ...
8165     };
8167     void use()
8168     {
8169         // p1 may be nullptr
8170         // *p1 is not initialized; in particular,
8171         // that string isn't a string, but a string-sized bag of bits
8172         Record* p1 = static_cast<Record*>(malloc(sizeof(Record)));
8174         auto p2 = new Record;
8176         // unless an exception is thrown, *p2 is default initialized
8177         auto p3 = new(nothrow) Record;
8178         // p3 may be nullptr; if not, *p3 is default initialized
8180         // ...
8182         delete p1;    // error: cannot delete object allocated by malloc()
8183         free(p2);    // error: cannot free() object allocated by new
8184     }
8186 In some implementations that `delete` and that `free()` might work, or maybe they will cause run-time errors.
8188 ##### Exception
8190 There are applications and sections of code where exceptions are not acceptable.
8191 Some of the best such examples are in life-critical hard real-time code.
8192 Beware that many bans on exception use are based on superstition (bad)
8193 or by concerns for older code bases with unsystematic resource management (unfortunately, but sometimes necessary).
8194 In such cases, consider the `nothrow` versions of `new`.
8196 ##### Enforcement
8198 Flag explicit use of `malloc` and `free`.
8200 ### <a name="Rr-newdelete"></a>R.11: Avoid calling `new` and `delete` explicitly
8202 ##### Reason
8204 The pointer returned by `new` should belong to a resource handle (that can call `delete`).
8205 If the pointer returned by `new` is assigned to a plain/naked pointer, the object can be leaked.
8207 ##### Note
8209 In a large program, a naked `delete` (that is a `delete` in application code, rather than part of code devoted to resource management)
8210 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?
8211 The bug may be latent: it may emerge only during maintenance.
8212 If you have a naked `new`, you probably need a naked `delete` somewhere, so you probably have a bug.
8214 ##### Enforcement
8216 (Simple) Warn on any explicit use of `new` and `delete`. Suggest using `make_unique` instead.
8218 ### <a name="Rr-immediate-alloc"></a>R.12: Immediately give the result of an explicit resource allocation to a manager object
8220 ##### Reason
8222 If you don't, an exception or a return may lead to a leak.
8224 ##### Example, bad
8226     void f(const string& name)
8227     {
8228         FILE* f = fopen(name, "r");          // open the file
8229         vector<char> buf(1024);
8230         auto _ = finally([f] { fclose(f); })  // remember to close the file
8231         // ...
8232     }
8234 The allocation of `buf` may fail and leak the file handle.
8236 ##### Example
8238     void f(const string& name)
8239     {
8240         ifstream f{name};   // open the file
8241         vector<char> buf(1024);
8242         // ...
8243     }
8245 The use of the file handle (in `ifstream`) is simple, efficient, and safe.
8247 ##### Enforcement
8249 * Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?)
8251 ### <a name="Rr-single-alloc"></a>R.13: Perform at most one explicit resource allocation in a single expression statement
8253 ##### Reason
8255 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.
8257 ##### Example
8259     void fun(shared_ptr<Widget> sp1, shared_ptr<Widget> sp2);
8261 This `fun` can be called like this:
8263     // BAD: potential leak
8264     fun(shared_ptr<Widget>(new Widget(a, b)), shared_ptr<Widget>(new Widget(c, d)));
8266 This is exception-unsafe because the compiler may reorder the two expressions building the function's two arguments.
8267 In particular, the compiler can interleave execution of the two expressions:
8268 Memory allocation (by calling `operator new`) could be done first for both objects, followed by attempts to call the two `Widget` constructors.
8269 If one of the constructor calls throws an exception, then the other object's memory will never be released!
8271 This subtle problem has a simple solution: Never perform more than one explicit resource allocation in a single expression statement.
8272 For example:
8274     shared_ptr<Widget> sp1(new Widget(a, b)); // Better, but messy
8275     fun(sp1, new Widget(c, d));
8277 The best solution is to avoid explicit allocation entirely use factory functions that return owning objects:
8279     fun(make_shared<Widget>(a, b), make_shared<Widget>(c, d)); // Best
8281 Write your own factory wrapper if there is not one already.
8283 ##### Enforcement
8285 * Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?)
8287 ### <a name="Rr-ap"></a>R.14: ??? array vs. pointer parameter
8289 ##### Reason
8291 An array decays to a pointer, thereby losing its size, opening the opportunity for range errors.
8293 ##### Example
8295     ??? what do we recommend: f(int*[]) or f(int**) ???
8297 **Alternative**: Use `span` to preserve size information.
8299 ##### Enforcement
8301 Flag `[]` parameters.
8303 ### <a name="Rr-pair"></a>R.15: Always overload matched allocation/deallocation pairs
8305 ##### Reason
8307 Otherwise you get mismatched operations and chaos.
8309 ##### Example
8311     class X {
8312         // ...
8313         void* operator new(size_t s);
8314         void operator delete(void*);
8315         // ...
8316     };
8318 ##### Note
8320 If you want memory that cannot be deallocated, `=delete` the deallocation operation.
8321 Don't leave it undeclared.
8323 ##### Enforcement
8325 Flag incomplete pairs.
8327 ## <a name="SS-smart"></a>R.smart: Smart pointers
8329 ### <a name="Rr-owner"></a>R.20: Use `unique_ptr` or `shared_ptr` to represent ownership
8331 ##### Reason
8333 They can prevent resource leaks.
8335 ##### Example
8337 Consider:
8339     void f()
8340     {
8341         X x;
8342         X* p1 { new X };              // see also ???
8343         unique_ptr<T> p2 { new X };   // unique ownership; see also ???
8344         shared_ptr<T> p3 { new X };   // shared ownership; see also ???
8345     }
8347 This will leak the object used to initialize `p1` (only).
8349 ##### Enforcement
8351 (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
8353 ### <a name="Rr-unique"></a>R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership
8355 ##### Reason
8357 A `unique_ptr` is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count).
8359 ##### Example, bad
8361 This needlessly adds and maintains a reference count.
8363     void f()
8364     {
8365         shared_ptr<Base> base = make_shared<Derived>();
8366         // use base locally, without copying it -- refcount never exceeds 1
8367     } // destroy base
8369 ##### Example
8371 This is more efficient:
8373     void f()
8374     {
8375         unique_ptr<Base> base = make_unique<Derived>();
8376         // use base locally
8377     } // destroy base
8379 ##### Enforcement
8381 (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.
8383 ### <a name="Rr-make_shared"></a>R.22: Use `make_shared()` to make `shared_ptr`s
8385 ##### Reason
8387 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.
8389 ##### Example
8391 Consider:
8393     shared_ptr<X> p1 { new X{2} }; // bad
8394     auto p = make_shared<X>(2);    // good
8396 The `make_shared()` version mentions `X` only once, so it is usually shorter (as well as faster) than the version with the explicit `new`.
8398 ##### Enforcement
8400 (Simple) Warn if a `shared_ptr` is constructed from the result of `new` rather than `make_shared`.
8402 ### <a name="Rr-make_unique"></a>R.23: Use `make_unique()` to make `unique_ptr`s
8404 ##### Reason
8406 For convenience and consistency with `shared_ptr`.
8408 ##### Note
8410 `make_unique()` is C++14, but widely available (as well as simple to write).
8412 ##### Enforcement
8414 (Simple) Warn if a `unique_ptr` is constructed from the result of `new` rather than `make_unique`.
8416 ### <a name="Rr-weak_ptr"></a>R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s
8418 ##### Reason
8420  `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
8421 be able to destroy a cyclic structure.
8423 ##### Example
8425     ???
8427 ##### Note
8429  ??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.)
8430 ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it.
8431 You could "temporarily share ownership" simply by using another `shared_ptr`.)
8433 ##### Enforcement
8435 ??? probably impossible. If we could statically detect cycles, we wouldn't need `weak_ptr`
8437 ### <a name="Rr-smartptrparam"></a>R.30: Take smart pointers as parameters only to explicitly express lifetime semantics
8439 ##### Reason
8441 Accepting a smart pointer to a `widget` is wrong if the function just needs the `widget` itself.
8442 It should be able to accept any `widget` object, not just ones whose lifetimes are managed by a particular kind of smart pointer.
8443 A function that does not manipulate lifetime should take raw pointers or references instead.
8445 ##### Example, bad
8447     // callee
8448     void f(shared_ptr<widget>& w)
8449     {
8450         // ...
8451         use(*w); // only use of w -- the lifetime is not used at all
8452         // ...
8453     };
8455     // caller
8456     shared_ptr<widget> my_widget = /* ... */;
8457     f(my_widget);
8459     widget stack_widget;
8460     f(stack_widget); // error
8462 ##### Example, good
8464     // callee
8465     void f(widget& w)
8466     {
8467         // ...
8468         use(w);
8469         // ...
8470     };
8472     // caller
8473     shared_ptr<widget> my_widget = /* ... */;
8474     f(*my_widget);
8476     widget stack_widget;
8477     f(stack_widget); // ok -- now this works
8479 ##### Enforcement
8481 * (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()`.
8482   Suggest using a `T*` or `T&` instead.
8483 * 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.
8484   Suggest using a `T*` or `T&` instead.
8486 ### <a name="Rr-smart"></a>R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`
8488 ##### Reason
8490 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.
8491 You want the rules to work on all the smart pointers you use.
8493 Any type (including primary template or specialization) that overloads unary `*` and `->` is considered a smart pointer:
8495 * If it is copyable, it is recognized as a reference-counted `shared_ptr`.
8496 * If it is not copyable, it is recognized as a unique `unique_ptr`.
8498 ##### Example
8500     // use Boost's intrusive_ptr
8501     #include<boost/intrusive_ptr.hpp>
8502     void f(boost::intrusive_ptr<widget> p)  // error under rule 'sharedptrparam'
8503     {
8504         p->foo();
8505     }
8507     // use Microsoft's CComPtr
8508     #include<atlbase.h>
8509     void f(CComPtr<widget> p)               // error under rule 'sharedptrparam'
8510     {
8511         p->foo();
8512     }
8514 Both cases are an error under the [`sharedptrparam` guideline](#Rr-smartptrparam):
8515 `p` is a `Shared_ptr`, but nothing about its sharedness is used here and passing it by value is a silent pessimization;
8516 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&`.
8517 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.
8519 ### <a name="Rr-uniqueptrparam"></a>R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`
8521 ##### Reason
8523 Using `unique_ptr` in this way both documents and enforces the function call's ownership transfer.
8525 ##### Example
8527     void sink(unique_ptr<widget>); // consumes the widget
8529     void sink(widget*);            // just uses the widget
8531 ##### Example, bad
8533     void thinko(const unique_ptr<widget>&); // usually not what you want
8535 ##### Enforcement
8537 * (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.
8538 * (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.
8539 * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr<T>` parameter by rvalue reference. Suggest using pass by value instead.
8541 ### <a name="Rr-reseat"></a>R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the`widget`
8543 ##### Reason
8545 Using `unique_ptr` in this way both documents and enforces the function call's reseating semantics.
8547 ##### Note
8549 "reseat" means "making a reference or a smart pointer refer to a different object."
8551 ##### Example
8553     void reseat(unique_ptr<widget>&); // "will" or "might" reseat pointer
8555 ##### Example, bad
8557     void thinko(const unique_ptr<widget>&); // usually not what you want
8559 ##### Enforcement
8561 * (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.
8562 * (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.
8563 * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr<T>` parameter by rvalue reference. Suggest using pass by value instead.
8565 ### <a name="Rr-sharedptrparam-owner"></a>R.34: Take a `shared_ptr<widget>` parameter to express that a function is part owner
8567 ##### Reason
8569 This makes the function's ownership sharing explicit.
8571 ##### Example, good
8573     void share(shared_ptr<widget>);            // share -- "will" retain refcount
8575     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
8577     void may_share(const shared_ptr<widget>&); // "might" retain refcount
8579 ##### Enforcement
8581 * (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.
8582 * (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.
8583 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
8585 ### <a name="Rr-sharedptrparam"></a>R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer
8587 ##### Reason
8589 This makes the function's reseating explicit.
8591 ##### Note
8593 "reseat" means "making a reference or a smart pointer refer to a different object."
8595 ##### Example, good
8597     void share(shared_ptr<widget>);            // share -- "will" retain refcount
8599     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
8601     void may_share(const shared_ptr<widget>&); // "might" retain refcount
8603 ##### Enforcement
8605 * (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.
8606 * (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.
8607 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
8609 ### <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 ???
8611 ##### Reason
8613 This makes the function's ??? explicit.
8615 ##### Example, good
8617     void share(shared_ptr<widget>);            // share -- "will" retain refcount
8619     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
8621     void may_share(const shared_ptr<widget>&); // "might" retain refcount
8623 ##### Enforcement
8625 * (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.
8626 * (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.
8627 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
8629 ### <a name="Rr-smartptrget"></a>R.37: Do not pass a pointer or reference obtained from an aliased smart pointer
8631 ##### Reason
8633 Violating this rule is the number one cause of losing reference counts and finding yourself with a dangling pointer.
8634 Functions should prefer to pass raw pointers and references down call chains.
8635 At the top of the call tree where you obtain the raw pointer or reference from a smart pointer that keeps the object alive.
8636 You need to be sure that the smart pointer cannot inadvertently be reset or reassigned from within the call tree below.
8638 ##### Note
8640 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.
8642 ##### Example
8644 Consider this code:
8646     // global (static or heap), or aliased local ...
8647     shared_ptr<widget> g_p = ...;
8649     void f(widget& w)
8650     {
8651         g();
8652         use(w);  // A
8653     }
8655     void g()
8656     {
8657         g_p = ...; // oops, if this was the last shared_ptr to that widget, destroys the widget
8658     }
8660 The following should not pass code review:
8662     void my_code()
8663     {
8664         // BAD: passing pointer or reference obtained from a nonlocal smart pointer
8665         //      that could be inadvertently reset somewhere inside f or it callees
8666         f(*g_p);
8668         // BAD: same reason, just passing it as a "this" pointer
8669          g_p->func();
8670     }
8672 The fix is simple -- take a local copy of the pointer to "keep a ref count" for your call tree:
8674     void my_code()
8675     {
8676         // cheap: 1 increment covers this entire function and all the call trees below us
8677         auto pin = g_p;
8679         // GOOD: passing pointer or reference obtained from a local unaliased smart pointer
8680         f(*pin);
8682         // GOOD: same reason
8683         pin->func();
8684     }
8686 ##### Enforcement
8688 * (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.
8690 # <a name="S-expr"></a>ES: Expressions and Statements
8692 Expressions and statements are the lowest and most direct way of expressing actions and computation. Declarations in local scopes are statements.
8694 For naming, commenting, and indentation rules, see [NL: Naming and layout](#S-naming).
8696 General rules:
8698 * [ES.1: Prefer the standard library to other libraries and to "handcrafted code"](#Res-lib)
8699 * [ES.2: Prefer suitable abstractions to direct use of language features](#Res-abstr)
8701 Declaration rules:
8703 * [ES.5: Keep scopes small](#Res-scope)
8704 * [ES.6: Declare names in for-statement initializers and conditions to limit scope](#Res-cond)
8705 * [ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer](#Res-name-length)
8706 * [ES.8: Avoid similar-looking names](#Res-name-similar)
8707 * [ES.9: Avoid `ALL_CAPS` names](#Res-not-CAPS)
8708 * [ES.10: Declare one name (only) per declaration](#Res-name-one)
8709 * [ES.11: Use `auto` to avoid redundant repetition of type names](#Res-auto)
8710 * [ES.12: Do not reuse names in nested scopes](#Res-reuse)
8711 * [ES.20: Always initialize an object](#Res-always)
8712 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
8713 * [ES.22: Don't declare a variable until you have a value to initialize it with](#Res-init)
8714 * [ES.23: Prefer the `{}`-initializer syntax](#Res-list)
8715 * [ES.24: Use a `unique_ptr<T>` to hold pointers in code that may throw](#Res-unique)
8716 * [ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on](#Res-const)
8717 * [ES.26: Don't use a variable for two unrelated purposes](#Res-recycle)
8718 * [ES.27: Use `std::array` or `stack_array` for arrays on the stack](#Res-stack)
8719 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
8720 * [ES.30: Don't use macros for program text manipulation](#Res-macros)
8721 * [ES.31: Don't use macros for constants or "functions"](#Res-macros2)
8722 * [ES.32: Use `ALL_CAPS` for all macro names](#Res-ALL_CAPS)
8723 * [ES.33: If you must use macros, give them unique names](#Res-MACROS)
8724 * [ES.34: Don't define a (C-style) variadic function](#Res-ellipses)
8726 Expression rules:
8728 * [ES.40: Avoid complicated expressions](#Res-complicated)
8729 * [ES.41: If in doubt about operator precedence, parenthesize](#Res-parens)
8730 * [ES.42: Keep use of pointers simple and straightforward](#Res-ptr)
8731 * [ES.43: Avoid expressions with undefined order of evaluation](#Res-order)
8732 * [ES.44: Don't depend on order of evaluation of function arguments](#Res-order-fct)
8733 * [ES.45: Avoid narrowing conversions](#Res-narrowing)
8734 * [ES.46: Avoid "magic constants"; use symbolic constants](#Res-magic)
8735 * [ES.47: Use `nullptr` rather than `0` or `NULL`](#Res-nullptr)
8736 * [ES.48: Avoid casts](#Res-casts)
8737 * [ES.49: If you must use a cast, use a named cast](#Res-casts-named)
8738 * [ES.50: Don't cast away `const`](#Res-casts-const)
8739 * [ES.55: Avoid the need for range checking](#Res-range-checking)
8740 * [ES.56: Avoid `std::move()` in application code](#Res-move)
8741 * [ES.60: Avoid `new` and `delete` outside resource management functions](#Res-new)
8742 * [ES.61: Delete arrays using `delete[]` and non-arrays using `delete`](#Res-del)
8743 * [ES.62: Don't compare pointers into different arrays](#Res-arr2)
8744 * [ES.63: Don't slice](#Res-slice)
8746 Statement rules:
8748 * [ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice](#Res-switch-if)
8749 * [ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice](#Res-for-range)
8750 * [ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable](#Res-for-while)
8751 * [ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable](#Res-while-for)
8752 * [ES.74: Prefer to declare a loop variable in the initializer part of a `for`-statement](#Res-for-init)
8753 * [ES.75: Avoid `do`-statements](#Res-do)
8754 * [ES.76: Avoid `goto`](#Res-goto)
8755 * [ES.77: ??? `continue`](#Res-continue)
8756 * [ES.78: Always end a non-empty `case` with a `break`](#Res-break)
8757 * [ES.79: ??? `default`](#Res-default)
8758 * [ES.85: Make empty statements visible](#Res-empty)
8759 * [ES.86: Avoid modifying loop control variables inside the body of raw for-loops](#Res-loop-counter)
8761 Arithmetic rules:
8763 * [ES.100: Don't mix signed and unsigned arithmetic](#Res-mix)
8764 * [ES.101: Use unsigned types for bit manipulation](#Res-unsigned)
8765 * [ES.102: Use signed types for arithmetic](#Res-signed)
8766 * [ES.103: Don't overflow](#Res-overflow)
8767 * [ES.104: Don't underflow](#Res-underflow)
8768 * [ES.105: Don't divide by zero](#Res-zero)
8770 ### <a name="Res-lib"></a>ES.1: Prefer the standard library to other libraries and to "handcrafted code"
8772 ##### Reason
8774 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.
8775 The ISO C++ standard library is among the most widely known and best tested libraries.
8776 It is available as part of all C++ Implementations.
8778 ##### Example
8780     auto sum = accumulate(begin(a), end(a), 0.0);   // good
8782 a range version of `accumulate` would be even better:
8784     auto sum = accumulate(v, 0.0); // better
8786 but don't hand-code a well-known algorithm:
8788     int max = v.size();   // bad: verbose, purpose unstated
8789     double sum = 0.0;
8790     for (int i = 0; i < max; ++i)
8791         sum = sum + v[i];
8793 ##### Exception
8795 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.
8797 ##### Enforcement
8799 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
8801 ### <a name="Res-abstr"></a>ES.2: Prefer suitable abstractions to direct use of language features
8803 ##### Reason
8805 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.
8807 ##### Example
8809     vector<string> read1(istream& is)   // good
8810     {
8811         vector<string> res;
8812         for (string s; is >> s;)
8813             res.push_back(s);
8814         return res;
8815     }
8817 The more traditional and lower-level near-equivalent is longer, messier, harder to get right, and most likely slower:
8819     char** read2(istream& is, int maxelem, int maxstring, int* nread)   // bad: verbose and incomplete
8820     {
8821         auto res = new char*[maxelem];
8822         int elemcount = 0;
8823         while (is && elemcount < maxelem) {
8824             auto s = new char[maxstring];
8825             is.read(s, maxstring);
8826             res[elemcount++] = s;
8827         }
8828         nread = &elemcount;
8829         return res;
8830     }
8832 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.
8834 ##### Enforcement
8836 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
8838 ## ES.dcl: Declarations
8840 A declaration is a statement. A declaration introduces a name into a scope and may cause the construction of a named object.
8842 ### <a name="Res-scope"></a>ES.5: Keep scopes small
8844 ##### Reason
8846 Readability. Minimize resource retention. Avoid accidental misuse of value.
8848 **Alternative formulation**: Don't declare a name in an unnecessarily large scope.
8850 ##### Example
8852     void use()
8853     {
8854         int i;    // bad: i is needlessly accessible after loop
8855         for (i = 0; i < 20; ++i) { /* ... */ }
8856         // no intended use of i here
8857         for (int i = 0; i < 20; ++i) { /* ... */ }  // good: i is local to for-loop
8859         if (auto pc = dynamic_cast<Circle*>(ps)) {  // good: pc is local to if-statement
8860             // ... deal with Circle ...
8861         }
8862         else {
8863             // ... handle error ...
8864         }
8865     }
8867 ##### Example, bad
8869     void use(const string& name)
8870     {
8871         string fn = name + ".txt";
8872         ifstream is {fn};
8873         Record r;
8874         is >> r;
8875         // ... 200 lines of code without intended use of fn or is ...
8876     }
8878 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`
8879 are retained for much longer than needed and that unanticipated use of `is` and `fn` could happen later in the function.
8880 In this case, it might be a good idea to factor out the read:
8882     Record load_record(const string& name)
8883     {
8884         string fn = name + ".txt";
8885         ifstream is {fn};
8886         Record r;
8887         is >> r;
8888         return r;
8889     }
8891     void use(const string& name)
8892     {
8893         Record r = load_record(name);
8894         // ... 200 lines of code ...
8895     }
8897 ##### Enforcement
8899 * Flag loop variable declared outside a loop and not used after the loop
8900 * Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N)
8902 ### <a name="Res-cond"></a>ES.6: Declare names in for-statement initializers and conditions to limit scope
8904 ##### Reason
8906 Readability. Minimize resource retention.
8908 ##### Example
8910     void use()
8911     {
8912         for (string s; cin >> s;)
8913             v.push_back(s);
8915         for (int i = 0; i < 20; ++i) {   // good: i is local to for-loop
8916             // ...
8917         }
8919         if (auto pc = dynamic_cast<Circle*>(ps)) {   // good: pc is local to if-statement
8920             // ... deal with Circle ...
8921         }
8922         else {
8923             // ... handle error ...
8924         }
8925     }
8927 ##### Enforcement
8929 * Flag loop variables declared before the loop and not used after the loop
8930 * (hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose.
8932 ### <a name="Res-name-length"></a>ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer
8934 ##### Reason
8936 Readability. Lowering the chance of clashes between unrelated non-local names.
8938 ##### Example
8940 Conventional short, local names increase readability:
8942     template<typename T>    // good
8943     void print(ostream& os, const vector<T>& v)
8944     {
8945         for (int i = 0; i < v.size(); ++i)
8946             os << v[i] << '\n';
8947     }
8949 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
8951     template<typename Element_type>   // bad: verbose, hard to read
8952     void print(ostream& target_stream, const vector<Element_type>& current_vector)
8953     {
8954         for (int current_element_index = 0;
8955                 current_element_index < current_vector.size();
8956                 ++current_element_index
8957         )
8958         target_stream << current_vector[current_element_index] << '\n';
8959     }
8961 Yes, it is a caricature, but we have seen worse.
8963 ##### Example
8965 Unconventional and short non-local names obscure code:
8967     void use1(const string& s)
8968     {
8969         // ...
8970         tt(s);   // bad: what is tt()?
8971         // ...
8972     }
8974 Better, give non-local entities readable names:
8976     void use1(const string& s)
8977     {
8978         // ...
8979         trim_tail(s);   // better
8980         // ...
8981     }
8983 Here, there is a chance that the reader knows what `trim_tail` means and that the reader can remember it after looking it up.
8985 ##### Example, bad
8987 Argument names of large functions are de facto non-local and should be meaningful:
8989     void complicated_algorithm(vector<Record>& vr, const vector<int>& vi, map<string, int>& out)
8990     // read from events in vr (marking used Records) for the indices in
8991     // vi placing (name, index) pairs into out
8992     {
8993         // ... 500 lines of code using vr, vi, and out ...
8994     }
8996 We recommend keeping functions short, but that rule isn't universally adhered to and naming should reflect that.
8998 ##### Enforcement
9000 Check length of local and non-local names. Also take function length into account.
9002 ### <a name="Res-name-similar"></a>ES.8: Avoid similar-looking names
9004 ##### Reason
9006 Code clarity and readability. Too-similar names slow down comprehension and increase the likelihood of error.
9008 ##### Example; bad
9010     if (readable(i1 + l1 + ol + o1 + o0 + ol + o1 + I0 + l0)) surprise();
9012 ##### Example; bad
9014 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.
9016     struct foo { int n; };
9017     struct foo foo();       // BAD, foo is a type already in scope
9018     struct foo x = foo();   // requires disambiguation
9020 ##### Exception
9022 Antique header files might declare non-types and types with the same name in the same scope.
9024 ##### Enforcement
9026 * Check names against a list of known confusing letter and digit combinations.
9027 * Flag a declaration of a variable, function, or enumerator that hides a class or enumeration declared in the same scope.
9029 ### <a name="Res-not-CAPS"></a>ES.9: Avoid `ALL_CAPS` names
9031 ##### Reason
9033 Such names are commonly used for macros. Thus, `ALL_CAPS` name are vulnerable to unintended macro substitution.
9035 ##### Example
9037     // somewhere in some header:
9038     #define NE !=
9040     // somewhere else in some other header:
9041     enum Coord { N, NE, NW, S, SE, SW, E, W };
9043     // somewhere third in some poor programmer's .cpp:
9044     switch (direction) {
9045     case N:
9046         // ...
9047     case NE:
9048         // ...
9049     // ...
9050     }
9052 ##### Note
9054 Do not use `ALL_CAPS` for constants just because constants used to be macros.
9056 ##### Enforcement
9058 Flag all uses of ALL CAPS. For older code, accept ALL CAPS for macro names and flag all non-ALL-CAPS macro names.
9060 ### <a name="Res-name-one"></a>ES.10: Declare one name (only) per declaration
9062 ##### Reason
9064 One-declaration-per line increases readability and avoids mistakes related to
9065 the C/C++ grammar. It also leaves room for a more descriptive end-of-line
9066 comment.
9068 ##### Example, bad
9070     char *p, c, a[7], *pp[7], **aa[10];   // yuck!
9072 ##### Exception
9074 A function declaration can contain several function argument declarations.
9076 ##### Example
9078     template <class InputIterator, class Predicate>
9079     bool any_of(InputIterator first, InputIterator last, Predicate pred);
9081 or better using concepts:
9083     bool any_of(InputIterator first, InputIterator last, Predicate pred);
9085 ##### Example
9087     double scalbn(double x, int n);   // OK: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
9091     double scalbn(    // better: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
9092         double x,     // base value
9093         int n         // exponent
9094     );
9098     // better: base * pow(FLT_RADIX, exponent); FLT_RADIX is usually 2
9099     double scalbn(double base, int exponent);
9101 ##### Enforcement
9103 Flag non-function arguments with multiple declarators involving declarator operators (e.g., `int* p, q;`)
9105 ### <a name="Res-auto"></a>ES.11: Use `auto` to avoid redundant repetition of type names
9107 ##### Reason
9109 * Simple repetition is tedious and error prone.
9110 * When you use `auto`, the name of the declared entity is in a fixed position in the declaration, increasing readability.
9111 * In a template function declaration the return type can be a member type.
9113 ##### Example
9115 Consider:
9117     auto p = v.begin();   // vector<int>::iterator
9118     auto s = v.size();
9119     auto h = t.future();
9120     auto q = make_unique<int[]>(s);
9121     auto f = [](int x){ return x + 10; };
9123 In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.
9125 ##### Example
9127     template<class T>
9128     auto Container<T>::first() -> Iterator;   // Container<T>::Iterator
9130 ##### Exception
9132 Avoid `auto` for initializer lists and in cases where you know exactly which type you want and where an initializer might require conversion.
9134 ##### Example
9136     auto lst = { 1, 2, 3 };   // lst is an initializer list
9137     auto x{1};   // x is an int (after correction of the C++14 standard; initializer_list in C++11)
9139 ##### Note
9141 When concepts become available, we can (and should) be more specific about the type we are deducing:
9143     // ...
9144     ForwardIterator p = algo(x, y, z);
9146 ##### Enforcement
9148 Flag redundant repetition of type names in a declaration.
9150 ### <a name="Res-reuse"></a>ES.12: Do not reuse names in nested scopes
9152 ##### Reason
9154 It is easy to get confused about which variable is used.
9155 Can cause maintenance problems.
9157 ##### Example, bad
9159     int d = 0;
9160     // ...
9161     if (cond) {
9162         // ...
9163         d = 9;
9164         // ...
9165     }
9166     else {
9167         // ...
9168         int d = 7;
9169         // ...
9170         d = value_to_be_returned;
9171         // ...
9172     }
9174     return d;
9176 If this is a large `if`-statement, it is easy to overlook that a new `d` has been introduced in the inner scope.
9177 This is a known source of bugs.
9178 Sometimes such reuse of a name in an inner scope is called "shadowing".
9180 ##### Note
9182 Shadowing is primarily a problem when functions are too large and too complex.
9184 ##### Example
9186 Shadowing of function arguments in the outermost block is disallowed by the language:
9188     void f(int x)
9189     {
9190         int x = 4;  // error: reuse of function argument name
9192         if (x) {
9193             int x = 7;  // allowed, but bad
9194             // ...
9195         }
9196     }
9198 ##### Example, bad
9200 Reuse of a member name as a local variable can also be a problem:
9202     struct S {
9203         int m;
9204         void f(int x);
9205     };
9207     void S::f(int x)
9208     {
9209         m = 7;    // assign to member
9210         if (x) {
9211             int m = 9;
9212             // ...
9213             m = 99; // assign to member
9214             // ...
9215         }
9216     }
9218 ##### Exception
9220 We often reuse function names from a base class in a derived class:
9222     struct B {
9223         void f(int);
9224     };
9226     struct D : B {
9227         void f(double);
9228         using B::f;
9229     };
9231 This is error-prone.
9232 For example, had we forgotten the using declaration, a call `d.f(1)` would not have found the `int` version of `f`.
9234 ??? Do we need a specific rule about shadowing/hiding in class hierarchies?
9236 ##### Enforcement
9238 * Flag reuse of a name in nested local scopes
9239 * Flag reuse of a member name as a local variable in a member function
9240 * Flag reuse of a global name as a local variable or a member name
9241 * Flag reuse of a base class member name in a derived class (except for function names)
9243 ### <a name="Res-always"></a>ES.20: Always initialize an object
9245 ##### Reason
9247 Avoid used-before-set errors and their associated undefined behavior.
9248 Avoid problems with comprehension of complex initialization.
9249 Simplify refactoring.
9251 ##### Example
9253     void use(int arg)
9254     {
9255         int i;   // bad: uninitialized variable
9256         // ...
9257         i = 7;   // initialize i
9258     }
9260 No, `i = 7` does not initialize `i`; it assigns to it. Also, `i` can be read in the `...` part. Better:
9262     void use(int arg)   // OK
9263     {
9264         int i = 7;   // OK: initialized
9265         string s;    // OK: default initialized
9266         // ...
9267     }
9269 ##### Note
9271 The *always initialize* rule is deliberately stronger than the *an object must be set before used* language rule.
9272 The latter, more relaxed rule, catches the technical bugs, but:
9274 * It leads to less readable code
9275 * It encourages people to declare names in greater than necessary scopes
9276 * It leads to harder to read code
9277 * It leads to logic bugs by encouraging complex code
9278 * It hampers refactoring
9280 The *always initialize* rule is a style rule aimed to improve maintainability as well as a rule protecting against used-before-set errors.
9282 ##### Example
9284 Here is an example that is often considered to demonstrate the need for a more relaxed rule for initialization
9286     widget i;    // "widget" a type that's expensive to initialize, possibly a large POD
9287     widget j;
9289     if (cond) {  // bad: i and j are initialized "late"
9290         i = f1();
9291         j = f2();
9292     }
9293     else {
9294         i = f3();
9295         j = f4();
9296     }
9298 This cannot trivially be rewritten to initialize `i` and `j` with initializers.
9299 Note that for types with a default constructor, attempting to postpone initialization simply leads to a default initialization followed by an assignment.
9300 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.
9302 At the cost of repeating `cond` we could write:
9304     widget i = (cond) ? f1() : f3();
9305     widget j = (cond) ? f2() : f4();
9307 Assuming that there is a logical connection between `i` and `j`, that connection should probably be expressed in code:
9309     pair<widget, widget> make_related_widgets(bool x)
9310     {
9311         return (x) ? {f1(), f2()} : {f3(), f4() };
9312     }
9314     auto init = make_related_widgets(cond);
9315     widget i = init.first;
9316     widget j = init.second;
9318 Obviously, what we really would like is a construct that initialized n variables from a `tuple`. For example:
9320     auto {i, j} = make_related_widgets(cond);    // Not C++14
9322 Today, we might approximate that using `tie()`:
9324     widget i;       // bad: uninitialized variable
9325     widget j;
9326     tie(i, j) = make_related_widgets(cond);
9328 This may be seen as an example of the *immediately initialize from input* exception below.
9330 Creating optimal and equivalent code from all of these examples should be well within the capabilities of modern C++ compilers
9331 (but don't make performance claims without measuring; a compiler may very well not generate optimal code for every example and
9332 there may be language rules preventing some optimization that you would have liked in a particular case).
9334 ##### Note
9336 Complex initialization has been popular with clever programmers for decades.
9337 It has also been a major source of errors and complexity.
9338 Many such errors are introduced during maintenance years after the initial implementation.
9340 ##### Exception
9342 It you are declaring an object that is just about to be initialized from input, initializing it would cause a double initialization.
9343 However, beware that this may leave uninitialized data beyond the input -- and that has been a fertile source of errors and security breaches:
9345     constexpr int max = 8 * 1024;
9346     int buf[max];         // OK, but suspicious: uninitialized
9347     f.read(buf, max);
9349 The cost of initializing that array could be significant in some situations.
9350 However, such examples do tend to leave uninitialized variables accessible, so they should be treated with suspicion.
9352     constexpr int max = 8 * 1024;
9353     int buf[max] = {};   // zero all elements; better in some situations
9354     f.read(buf, max);
9356 When feasible use a library function that is known not to overflow. For example:
9358     string s;   // s is default initialized to ""
9359     cin >> s;   // s expands to hold the string
9361 Don't consider simple variables that are targets for input operations exceptions to this rule:
9363     int i;   // bad
9364     // ...
9365     cin >> i;
9367 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.
9369     int i2 = 0;   // better
9370     // ...
9371     cin >> i;
9373 A good optimizer should know about input operations and eliminate the redundant operation.
9375 ##### Example
9377 Using an `uninitialized` or sentinel value is a symptom of a problem and not a
9378 solution:
9380     widget i = uninit;  // bad
9381     widget j = uninit;
9383     // ...
9384     use(i);         // possibly used before set
9385     // ...
9387     if (cond) {     // bad: i and j are initialized "late"
9388         i = f1();
9389         j = f2();
9390     }
9391     else {
9392         i = f3();
9393         j = f4();
9394     }
9396 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?
9398 ##### Note
9400 Sometimes, a lambda can be used as an initializer to avoid an uninitialized variable:
9402     error_code ec;
9403     Value v = [&] {
9404         auto p = get_value();   // get_value() returns a pair<error_code, Value>
9405         ec = p.first;
9406         return p.second;
9407     }();
9409 or maybe:
9411     Value v = [] {
9412         auto p = get_value();   // get_value() returns a pair<error_code, Value>
9413         if (p.first) throw Bad_value{p.first};
9414         return p.second;
9415     }();
9417 **See also**: [ES.28](#Res-lambda-init)
9419 ##### Enforcement
9421 * Flag every uninitialized variable.
9422   Don't flag variables of user-defined types with default constructors.
9423 * Check that an uninitialized buffer is written into *immediately* after declaration.
9424   Passing an uninitialized variable as a reference to non-`const` argument can be assumed to be a write into the variable.
9426 ### <a name="Res-introduce"></a>ES.21: Don't introduce a variable (or constant) before you need to use it
9428 ##### Reason
9430 Readability. To limit the scope in which the variable can be used.
9432 ##### Example
9434     int x = 7;
9435     // ... no use of x here ...
9436     ++x;
9438 ##### Enforcement
9440 Flag declarations that are distant from their first use.
9442 ### <a name="Res-init"></a>ES.22: Don't declare a variable until you have a value to initialize it with
9444 ##### Reason
9446 Readability. Limit the scope in which a variable can be used. Don't risk used-before-set. Initialization is often more efficient than assignment.
9448 ##### Example, bad
9450     string s;
9451     // ... no use of s here ...
9452     s = "what a waste";
9454 ##### Example, bad
9456     SomeLargeType var;   // ugly CaMeLcAsEvArIaBlE
9458     if (cond)   // some non-trivial condition
9459         Set(&var);
9460     else if (cond2 || !cond3) {
9461         var = Set2(3.14);
9462     }
9463     else {
9464         var = 0;
9465         for (auto& e : something)
9466             var += e;
9467     }
9469     // use var; that this isn't done too early can be enforced statically with only control flow
9471 This would be fine if there was a default initialization for `SomeLargeType` that wasn't too expensive.
9472 Otherwise, a programmer might very well wonder if every possible path through the maze of conditions has been covered.
9473 If not, we have a "use before set" bug. This is a maintenance trap.
9475 For initializers of moderate complexity, including for `const` variables, consider using a lambda to express the initializer; see [ES.28](#Res-lambda-init).
9477 ##### Enforcement
9479 * Flag declarations with default initialization that are assigned to before they are first read.
9480 * Flag any complicated computation after an uninitialized variable and before its use.
9482 ### <a name="Res-list"></a>ES.23: Prefer the `{}` initializer syntax
9484 ##### Reason
9486 The rules for `{}` initialization are simpler, more general, less ambiguous, and safer than for other forms of initialization.
9488 ##### Example
9490     int x {f(99)};
9491     vector<int> v = {1, 2, 3, 4, 5, 6};
9493 ##### Exception
9495 For containers, there is a tradition for using `{...}` for a list of elements and `(...)` for sizes:
9497     vector<int> v1(10);    // vector of 10 elements with the default value 0
9498     vector<int> v2 {10};   // vector of 1 element with the value 10
9500 ##### Note
9502 `{}`-initializers do not allow narrowing conversions.
9504 ##### Example
9506     int x {7.9};   // error: narrowing
9507     int y = 7.9;   // OK: y becomes 7. Hope for a compiler warning
9509 ##### Note
9511 `{}` initialization can be used for all initialization; other forms of initialization can't:
9513     auto p = new vector<int> {1, 2, 3, 4, 5};   // initialized vector
9514     D::D(int a, int b) :m{a, b} {   // member initializer (e.g., m might be a pair)
9515         // ...
9516     };
9517     X var {};   // initialize var to be empty
9518     struct S {
9519         int m {7};   // default initializer for a member
9520         // ...
9521     };
9523 ##### Note
9525 Initialization of a variable declared using `auto` with a single value, e.g., `{v}`, had surprising results until recently:
9527     auto x1 {7};        // x1 is an int with the value 7
9528     // x2 is an initializer_list<int> with an element 7
9529     // (this will will change to "element 7" in C++17)
9530     auto x2 = {7};
9532     auto x11 {7, 8};    // error: two initializers
9533     auto x22 = {7, 8};  // x2 is an initializer_list<int> with elements 7 and 8
9535 ##### Exception
9537 Use `={...}` if you really want an `initializer_list<T>`
9539     auto fib10 = {0, 1, 2, 3, 5, 8, 13, 21, 34, 55};   // fib10 is a list
9541 ##### Note
9543 Old habits die hard, so this rule is hard to apply consistently, especially as there are so many cases where `=` is innocent.
9545 ##### Example
9547     template<typename T>
9548     void f()
9549     {
9550         T x1(1);    // T initialized with 1
9551         T x0();     // bad: function declaration (often a mistake)
9553         T y1 {1};   // T initialized with 1
9554         T y0 {};    // default initialized T
9555         // ...
9556     }
9558 **See also**: [Discussion](#???)
9560 ##### Enforcement
9562 Tricky.
9564 * Don't flag uses of `=` for simple initializers.
9565 * Look for `=` after `auto` has been seen.
9567 ### <a name="Res-unique"></a>ES.24: Use a `unique_ptr<T>` to hold pointers
9569 ##### Reason
9571 Using `std::unique_ptr` is the simplest way to avoid leaks. It is reliable, it
9572 makes the type system do much of the work to validate ownership safety, it
9573 increases readability, and it has zero or near zero runtime cost.
9575 ##### Example
9577     void use(bool leak)
9578     {
9579         auto p1 = make_unique<int>(7);   // OK
9580         int* p2 = new int{7};            // bad: might leak
9581         // ...
9582         if (leak) return;
9583         // ...
9584     }
9586 If `leak == true` the object pointed to by `p2` is leaked and the object pointed to by `p1` is not.
9588 ##### Enforcement
9590 Look for raw pointers that are targets of `new`, `malloc()`, or functions that may return such pointers.
9592 ### <a name="Res-const"></a>ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on
9594 ##### Reason
9596 That way you can't change the value by mistake. That way may offer the compiler optimization opportunities.
9598 ##### Example
9600     void f(int n)
9601     {
9602         const int bufmax = 2 * n + 2;  // good: we can't change bufmax by accident
9603         int xmax = n;                  // suspicious: is xmax intended to change?
9604         // ...
9605     }
9607 ##### Enforcement
9609 Look to see if a variable is actually mutated, and flag it if
9610 not. Unfortunately, it may be impossible to detect when a non-`const` was not
9611 *intended* to vary (vs when it merely did not vary).
9613 ### <a name="Res-recycle"></a>ES.26: Don't use a variable for two unrelated purposes
9615 ##### Reason
9617 Readability.
9619 ##### Example, bad
9621     void use()
9622     {
9623         int i;
9624         for (i = 0; i < 20; ++i) { /* ... */ }
9625         for (i = 0; i < 200; ++i) { /* ... */ } // bad: i recycled
9626     }
9628 ##### Enforcement
9630 Flag recycled variables.
9632 ### <a name="Res-stack"></a>ES.27: Use `std::array` or `stack_array` for arrays on the stack
9634 ##### Reason
9636 They are readable and don't implicitly convert to pointers.
9637 They are not confused with non-standard extensions of built-in arrays.
9639 ##### Example, bad
9641     const int n = 7;
9642     int m = 9;
9644     void f()
9645     {
9646         int a1[n];
9647         int a2[m];   // error: not ISO C++
9648         // ...
9649     }
9651 ##### Note
9653 The definition of `a1` is legal C++ and has always been.
9654 There is a lot of such code.
9655 It is error-prone, though, especially when the bound is non-local.
9656 Also, it is a "popular" source of errors (buffer overflow, pointers from array decay, etc.).
9657 The definition of `a2` is C but not C++ and is considered a security risk
9659 ##### Example
9661     const int n = 7;
9662     int m = 9;
9664     void f()
9665     {
9666         array<int, n> a1;
9667         stack_array<int> a2(m);
9668         // ...
9669     }
9671 ##### Enforcement
9673 * Flag arrays with non-constant bounds (C-style VLAs)
9674 * Flag arrays with non-local constant bounds
9676 ### <a name="Res-lambda-init"></a>ES.28: Use lambdas for complex initialization, especially of `const` variables
9678 ##### Reason
9680 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.
9682 ##### Example, bad
9684     widget x;   // should be const, but:
9685     for (auto i = 2; i <= N; ++i) {             // this could be some
9686         x += some_obj.do_something_with(i);  // arbitrarily long code
9687     }                                        // needed to initialize x
9688     // from here, x should be const, but we can't say so in code in this style
9690 ##### Example, good
9692     const widget x = [&]{
9693         widget val;                                // assume that widget has a default constructor
9694         for (auto i = 2; i <= N; ++i) {            // this could be some
9695             val += some_obj.do_something_with(i);  // arbitrarily long code
9696         }                                          // needed to initialize x
9697         return val;
9698     }();
9700 ##### Example
9702     string var = [&]{
9703         if (!in) return "";   // default
9704         string s;
9705         for (char c : in >> c)
9706             s += toupper(c);
9707         return s;
9708     }(); // note ()
9710 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.
9712 ##### Example
9714     owner<istream&> in = [&]{
9715         switch (source) {
9716         case default:       owned = false; return cin;
9717         case command_line:  owned = true;  return *new istringstream{argv[2]};
9718         case file:          owned = true;  return *new ifstream{argv[2]};
9719     }();
9721 ##### Enforcement
9723 Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it.
9725 ### <a name="Res-macros"></a>ES.30: Don't use macros for program text manipulation
9727 ##### Reason
9729 Macros are a major source of bugs.
9730 Macros don't obey the usual scope and type rules.
9731 Macros ensure that the human reader sees something different from what the compiler sees.
9732 Macros complicate tool building.
9734 ##### Example, bad
9736     #define Case break; case   /* BAD */
9738 This innocuous-looking macro makes a single lower case `c` instead of a `C` into a bad flow-control bug.
9740 ##### Note
9742 This rule does not ban the use of macros for "configuration control" use in `#ifdef`s, etc.
9744 ##### Enforcement
9746 Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`)
9748 ### <a name="Res-macros2"></a>ES.31: Don't use macros for constants or "functions"
9750 ##### Reason
9752 Macros are a major source of bugs.
9753 Macros don't obey the usual scope and type rules.
9754 Macros don't obey the usual rules for argument passing.
9755 Macros ensure that the human reader sees something different from what the compiler sees.
9756 Macros complicate tool building.
9758 ##### Example, bad
9760     #define PI 3.14
9761     #define SQUARE(a, b) (a * b)
9763 Even if we hadn't left a well-known bug in `SQUARE` there are much better behaved alternatives; for example:
9765     constexpr double pi = 3.14;
9766     template<typename T> T square(T a, T b) { return a * b; }
9768 ##### Enforcement
9770 Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`)
9772 ### <a name="Res-ALL_CAPS"></a>ES.32: Use `ALL_CAPS` for all macro names
9774 ##### Reason
9776 Convention. Readability. Distinguishing macros.
9778 ##### Example
9780     #define forever for (;;)   /* very BAD */
9782     #define FOREVER for (;;)   /* Still evil, but at least visible to humans */
9784 ##### Enforcement
9786 Scream when you see a lower case macro.
9788 ### <a name="Res-MACROS"></a>ES.33: If you must use macros, give them unique names
9790 ##### Reason
9792 Macros do not obey scope rules.
9794 ##### Example
9796     #define MYCHAR        /* BAD, will eventually clash with someone else's MYCHAR*/
9798     #define ZCORP_CHAR    /* Still evil, but less likely to clash */
9800 ##### Note
9802 Avoid macros if you can: [ES.30](#Res-macros), [ES.31](#Res-macros2), and [ES.32](#Res-ALL_CAPS).
9803 However, there are billions of lines of code littered with macros and a long tradition for using and overusing macros.
9804 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.
9806 ##### Enforcement
9808 Warn against short macro names.
9810 ### <a name="Res-ellipses"></a> ES.34: Don't define a (C-style) variadic function
9812 ##### Reason
9814 Not type safe.
9815 Requires messy cast-and-macro-laden code to get working right.
9817 ##### Example
9819     #include<cstdarg>
9821     // "severity" followed by a zero-terminated list of char*s; write the C-style strings to cerr
9822     void error(int severity ...)
9823     {
9824         va_list ap;             // a magic type for holding arguments
9825         va_start(ap, severity); // arg startup: "severity" is the first argument of error()
9827         for (;;) {
9828             // treat the next var as a char*; no checking: a cast in disguise
9829             char* p = va_arg(ap, char*);
9830             if (p == nullptr) break;
9831             cerr << p << ' ';
9832         }
9834         va_end(ap);             // arg cleanup (don't forget this)
9836         cerr << '\n';
9837         if (severity) exit(severity);
9838     }
9840     void use()
9841     {
9842         error(7, "this", "is", "an", "error", nullptr);
9843         error(7); // crash
9844         error(7, "this", "is", "an", "error");  // crash
9845         const char* is = "is";
9846         string an = "an";
9847         error(7, "this", "is", an, "error"); // crash
9848     }
9850 **Alternative**: Overloading. Templates. Variadic templates.
9852 ##### Note
9854 This is basically the way `printf` is implemented.
9856 ##### Enforcement
9858 * Flag definitions of C-style variadic functions.
9859 * Flag `#include<cstdarg>` and `#include<stdarg.h>`
9861 ## ES.stmt: Statements
9863 Statements control the flow of control (except for function calls and exception throws, which are expressions).
9865 ### <a name="Res-switch-if"></a>ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice
9867 ##### Reason
9869 * Readability.
9870 * Efficiency: A `switch` compares against constants and is usually better optimized than a series of tests in an `if`-`then`-`else` chain.
9871 * A `switch` enables some heuristic consistency checking. For example, have all values of an `enum` been covered? If not, is there a `default`?
9873 ##### Example
9875     void use(int n)
9876     {
9877         switch (n) {   // good
9878         case 0:   // ...
9879         case 7:   // ...
9880         }
9881     }
9883 rather than:
9885     void use2(int n)
9886     {
9887         if (n == 0)   // bad: if-then-else chain comparing against a set of constants
9888             // ...
9889         else if (n == 7)
9890             // ...
9891     }
9893 ##### Enforcement
9895 Flag `if`-`then`-`else` chains that check against constants (only).
9897 ### <a name="Res-for-range"></a>ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice
9899 ##### Reason
9901 Readability. Error prevention. Efficiency.
9903 ##### Example
9905     for (int i = 0; i < v.size(); ++i)   // bad
9906             cout << v[i] << '\n';
9908     for (auto p = v.begin(); p != v.end(); ++p)   // bad
9909         cout << *p << '\n';
9911     for (auto& x : v)    // OK
9912         cout << x << '\n';
9914     for (int i = 1; i < v.size(); ++i) // touches two elements: can't be a range-for
9915         cout << v[i] + v[i - 1] << '\n';
9917     for (int i = 0; i < v.size(); ++i) // possible side-effect: can't be a range-for
9918         cout << f(v, &v[i]) << '\n';
9920     for (int i = 0; i < v.size(); ++i) { // body messes with loop variable: can't be a range-for
9921         if (i % 2 == 0)
9922             continue;   // skip even elements
9923         else
9924             cout << v[i] << '\n';
9925     }
9927 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.
9929 "Messing with the loop variable" in the body of a loop is typically best avoided.
9931 ##### Note
9933 Don't use expensive copies of the loop variable of a range-`for` loop:
9935     for (string s : vs) // ...
9937 This will copy each elements of `vs` into `s`. Better:
9939     for (string& s : vs) // ...
9941 Better still, if the loop variable isn't modified or copied:
9943     for (const string& s : vs) // ...
9945 ##### Enforcement
9947 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.
9949 ### <a name="Res-for-while"></a>ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable
9951 ##### Reason
9953 Readability: the complete logic of the loop is visible "up front". The scope of the loop variable can be limited.
9955 ##### Example
9957     for (int i = 0; i < vec.size(); i++) {
9958         // do work
9959     }
9961 ##### Example, bad
9963     int i = 0;
9964     while (i < vec.size()) {
9965         // do work
9966         i++;
9967     }
9969 ##### Enforcement
9973 ### <a name="Res-while-for"></a>ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable
9975 ##### Reason
9977  ???
9979 ##### Example
9981     ???
9983 ##### Enforcement
9987 ### <a name="Res-for-init"></a>ES.74: Prefer to declare a loop variable in the initializer part of a `for`-statement
9989 ##### Reason
9991 Limit the loop variable visibility to the scope of the loop.
9992 Avoid using the loop variable for other purposes after the loop.
9994 ##### Example
9996     for (int i = 0; i < 100; ++i) {   // GOOD: i var is visible only inside the loop
9997         // ...
9998     }
10000 ##### Example, don't
10002     int j;                            // BAD: j is visible outside the loop
10003     for (j = 0; j < 100; ++j) {
10004         // ...
10005     }
10006     // j is still visible here and isn't needed
10008 **See also**: [Don't use a variable for two unrelated purposes](#Res-recycle)
10010 ##### Enforcement
10012 Warn when a variable modified inside the `for`-statement is declared outside the loop and not being used outside the loop.
10014 **Discussion**: Scoping the loop variable to the loop body also helps code optimizers greatly. Recognizing that the induction variable
10015 is only accessible in the loop body unblocks optimizations such as hoisting, strength reduction, loop-invariant code motion, etc.
10017 ### <a name="Res-do"></a>ES.75: Avoid `do`-statements
10019 ##### Reason
10021 Readability, avoidance of errors.
10022 The termination condition is at the end (where it can be overlooked) and the condition is not checked the first time through. ???
10024 ##### Example
10026     int x;
10027     do {
10028         cin >> x;
10029         // ...
10030     } while (x < 0);
10032 ##### Enforcement
10036 ### <a name="Res-goto"></a>ES.76: Avoid `goto`
10038 ##### Reason
10040 Readability, avoidance of errors. There are better control structures for humans; `goto` is for machine generated code.
10042 ##### Exception
10044 Breaking out of a nested loop. In that case, always jump forwards.
10046 ##### Example
10048     ???
10050 ##### Example
10052 There is a fair amount of use of the C goto-exit idiom:
10054     void f()
10055     {
10056         // ...
10057             goto exit;
10058         // ...
10059             goto exit;
10060         // ...
10061     exit:
10062         ... common cleanup code ...
10063     }
10065 This is an ad-hoc simulation of destructors. Declare your resources with handles with destructors that clean up.
10067 ##### Enforcement
10069 * 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.
10071 ### <a name="Res-continue"></a>ES.77: ??? `continue`
10073 ##### Reason
10075  ???
10077 ##### Example
10079     ???
10081 ##### Enforcement
10085 ### <a name="Res-break"></a>ES.78: Always end a non-empty `case` with a `break`
10087 ##### Reason
10089  Accidentally leaving out a `break` is a fairly common bug.
10090  A deliberate fallthrough is a maintenance hazard.
10092 ##### Example
10094     switch (eventType)
10095     {
10096     case Information:
10097         update_status_bar();
10098         break;
10099     case Warning:
10100         write_event_log();
10101     case Error:
10102         display_error_window(); // Bad
10103         break;
10104     }
10106 It is easy to overlook the fallthrough. Be explicit:
10108     switch (eventType)
10109     {
10110     case Information:
10111         update_status_bar();
10112         break;
10113     case Warning:
10114         write_event_log();
10115         // fallthrough
10116     case Error:
10117         display_error_window(); // Bad
10118         break;
10119     }
10121 There is a proposal for a `[[fallthrough]]` annotation.
10123 ##### Note
10125 Multiple case labels of a single statement is OK:
10127     switch (x) {
10128     case 'a':
10129     case 'b':
10130     case 'f':
10131         do_something(x);
10132         break;
10133     }
10135 ##### Enforcement
10137 Flag all fallthroughs from non-empty `case`s.
10139 ### <a name="Res-default"></a>ES.79: ??? `default`
10141 ##### Reason
10143  ???
10145 ##### Example
10147     ???
10149 ##### Enforcement
10153 ### <a name="Res-empty"></a>ES.85: Make empty statements visible
10155 ##### Reason
10157 Readability.
10159 ##### Example
10161     for (i = 0; i < max; ++i);   // BAD: the empty statement is easily overlooked
10162     v[i] = f(v[i]);
10164     for (auto x : v) {           // better
10165         // nothing
10166     }
10167     v[i] = f(v[i]);
10169 ##### Enforcement
10171 Flag empty statements that are not blocks and don't contain comments.
10173 ### <a name="Res-loop-counter"></a>ES.86: Avoid modifying loop control variables inside the body of raw for-loops
10175 ##### Reason
10177 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.
10179 ##### Example
10181     for (int i = 0; i < 10; ++i) {
10182         // no updates to i -- ok
10183     }
10185     for (int i = 0; i < 10; ++i) {
10186         //
10187         if (/* something */) ++i; // BAD
10188         //
10189     }
10191     bool skip = false;
10192     for (int i = 0; i < 10; ++i) {
10193         if (skip) { skip = false; continue; }
10194         //
10195         if (/* something */) skip = true;  // Better: using two variable for two concepts.
10196         //
10197     }
10199 ##### Enforcement
10201 Flag variables that are potentially updated (have a non-const use) in both the loop control iteration-expression and the loop body.
10203 ## ES.expr: Expressions
10205 Expressions manipulate values.
10207 ### <a name="Res-complicated"></a>ES.40: Avoid complicated expressions
10209 ##### Reason
10211 Complicated expressions are error-prone.
10213 ##### Example
10215     // bad: assignment hidden in subexpression
10216     while ((c = getc()) != -1)
10218     // bad: two non-local variables assigned in a sub-expressions
10219     while ((cin >> c1, cin >> c2), c1 == c2)
10221     // better, but possibly still too complicated
10222     for (char c1, c2; cin >> c1 >> c2 && c1 == c2;)
10224     // OK: if i and j are not aliased
10225     int x = ++i + ++j;
10227     // OK: if i != j and i != k
10228     v[i] = v[j] + v[k];
10230     // bad: multiple assignments "hidden" in subexpressions
10231     x = a + (b = f()) + (c = g()) * 7;
10233     // bad: relies on commonly misunderstood precedence rules
10234     x = a & b + c * d && e ^ f == 7;
10236     // bad: undefined behavior
10237     x = x++ + x++ + ++x;
10239 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.
10241 ##### Note
10243 A programmer should know and use the basic rules for expressions.
10245 ##### Example
10247     x = k * y + z;             // OK
10249     auto t1 = k * y;           // bad: unnecessarily verbose
10250     x = t1 + z;
10252     if (0 <= x && x < max)   // OK
10254     auto t1 = 0 <= x;        // bad: unnecessarily verbose
10255     auto t2 = x < max;
10256     if (t1 && t2)            // ...
10258 ##### Enforcement
10260 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:
10262 * 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
10263 * writes to aliased variables
10264 * more than N operators (and what should N be?)
10265 * reliance of subtle precedence rules
10266 * uses undefined behavior (can we catch all undefined behavior?)
10267 * implementation defined behavior?
10268 * ???
10270 ### <a name="Res-parens"></a>ES.41: If in doubt about operator precedence, parenthesize
10272 ##### Reason
10274 Avoid errors. Readability. Not everyone has the operator table memorized.
10276 ##### Example
10278     const unsigned int flag = 2;
10279     unsigned int a = flag;
10281     if (a & flag != 0)  // bad: means a&(flag != 0)
10283 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.
10285     if ((a & flag) != 0)  // OK: works as intended
10287 ##### Note
10289 You should know enough not to need parentheses for:
10291     if (a < 0 || a <= max) {
10292         // ...
10293     }
10295 ##### Enforcement
10297 * Flag combinations of bitwise-logical operators and other operators.
10298 * Flag assignment operators not as the leftmost operator.
10299 * ???
10301 ### <a name="Res-ptr"></a>ES.42: Keep use of pointers simple and straightforward
10303 ##### Reason
10305 Complicated pointer manipulation is a major source of errors.
10307 * Do all pointer arithmetic on a `span` (exception ++p in simple loop???)
10308 * Avoid pointers to pointers
10309 * ???
10311 ##### Example
10313     ???
10315 ##### Enforcement
10317 We need a heuristic limiting the complexity of pointer arithmetic statement.
10319 ### <a name="Res-order"></a>ES.43: Avoid expressions with undefined order of evaluation
10321 ##### Reason
10323 You have no idea what such code does. Portability.
10324 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.
10326 ##### Example
10328     v[i] = ++i;   //  the result is undefined
10330 A good rule of thumb is that you should not read a value twice in an expression where you write to it.
10332 ##### Example
10334     ???
10336 ##### Note
10338 What is safe?
10340 ##### Enforcement
10342 Can be detected by a good analyzer.
10344 ### <a name="Res-order-fct"></a>ES.44: Don't depend on order of evaluation of function arguments
10346 ##### Reason
10348 Because that order is unspecified.
10350 ##### Example
10352     int i = 0;
10353     f(++i, ++i);
10355 The call will most likely be `f(0, 1)` or `f(1, 0)`, but you don't know which. Technically, the behavior is undefined.
10357 ##### Example
10359 ??? overloaded operators can lead to order of evaluation problems (shouldn't :-()
10361     f1()->m(f2());   // m(f1(), f2())
10362     cout << f1() << f2();   // operator<<(operator<<(cout, f1()), f2())
10364 ##### Enforcement
10366 Can be detected by a good analyzer.
10368 ### <a name="Res-magic"></a>ES.45: Avoid "magic constants"; use symbolic constants
10370 ##### Reason
10372 Unnamed constants embedded in expressions are easily overlooked and often hard to understand:
10374 ##### Example
10376     for (int m = 1; m <= 12; ++m)   // don't: magic constant 12
10377         cout << month[m] << '\n';
10379 No, we don't all know that there are 12 months, numbered 1..12, in a year. Better:
10381     constexpr int month_count = 12;   // months are numbered 1..12
10383     for (int m = first_month; m <= month_count; ++m)   // better
10384         cout << month[m] << '\n';
10386 Better still, don't expose constants:
10388     for (auto m : month)
10389         cout << m << '\n';
10391 ##### Enforcement
10393 Flag literals in code. Give a pass to `0`, `1`, `nullptr`, `\n`, `""`, and others on a positive list.
10395 ### <a name="Res-narrowing"></a>ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions
10397 ##### Reason
10399 A narrowing conversion destroys information, often unexpectedly so.
10401 ##### Example, bad
10403 A key example is basic narrowing:
10405     double d = 7.9;
10406     int i = d;    // bad: narrowing: i becomes 7
10407     i = (int) d;  // bad: we're going to claim this is still not explicit enough
10409     void f(int x, long y, double d)
10410     {
10411         char c1 = x;   // bad: narrowing
10412         char c2 = y;   // bad: narrowing
10413         char c3 = d;   // bad: narrowing
10414     }
10416 ##### Note
10418 The guideline support library offers a `narrow` operation for specifying that narrowing is acceptable and a `narrow` ("narrow if") that throws an exception if a narrowing would throw away information:
10420     i = narrow_cast<int>(d);   // OK (you asked for it): narrowing: i becomes 7
10421     i = narrow<int>(d);        // OK: throws narrowing_error
10423 We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type:
10425     double d = -7.9;
10426     unsigned u = 0;
10428     u = d;                          // BAD
10429     u = narrow_cast<unsigned>(d);   // OK (you asked for it): u becomes 0
10430     u = narrow<unsigned>(d);        // OK: throws narrowing_error
10432 ##### Enforcement
10434 A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions:
10436 * flag all floating-point to integer conversions (maybe only `float`->`char` and `double`->`int`. Here be dragons! we need data)
10437 * flag all `long`->`char` (I suspect `int`->`char` is very common. Here be dragons! we need data)
10438 * consider narrowing conversions for function arguments especially suspect
10440 ### <a name="Res-nullptr"></a>ES.47: Use `nullptr` rather than `0` or `NULL`
10442 ##### Reason
10444 Readability. Minimize surprises: `nullptr` cannot be confused with an
10445 `int`. `nullptr` also has a well-specified (very restrictive) type, and thus
10446 works in more scenarios where type deduction might do the wrong thing on `NULL`
10447 or `0`.
10449 ##### Example
10451 Consider:
10453     void f(int);
10454     void f(char*);
10455     f(0);         // call f(int)
10456     f(nullptr);   // call f(char*)
10458 ##### Enforcement
10460 Flag uses of `0` and `NULL` for pointers. The transformation may be helped by simple program transformation.
10462 ### <a name="Res-casts"></a>ES.48: Avoid casts
10464 ##### Reason
10466 Casts are a well-known source of errors. Makes some optimizations unreliable.
10468 ##### Example
10470     ???
10472 ##### Note
10474 Programmer who write casts typically assumes that they know what they are doing.
10475 In fact, they often disable the general rules for using values.
10476 Overload resolution and template instantiation usually pick the right function if there is a right function to pick.
10477 If there is not, maybe there ought to be, rather than applying a local fix (cast).
10479 ##### Note
10481 Casts are necessary in a systems programming language.  For example, how else
10482 would we get the address of a device register into a pointer?  However, casts
10483 are seriously overused as well as a major source of errors.
10485 ##### Note
10487 If you feel the need for a lot of casts, there may be a fundamental design problem.
10489 ##### Enforcement
10491 * Force the elimination of C-style casts
10492 * Warn against named casts
10493 * Warn if there are many functional style casts (there is an obvious problem in quantifying 'many').
10495 ### <a name="Res-casts-named"></a>ES.49: If you must use a cast, use a named cast
10497 ##### Reason
10499 Readability. Error avoidance.
10500 Named casts are more specific than a C-style or functional cast, allowing the compiler to catch some errors.
10502 The named casts are:
10504 * `static_cast`
10505 * `const_cast`
10506 * `reinterpret_cast`
10507 * `dynamic_cast`
10508 * `std::move`         // `move(x)` is an rvalue reference to `x`
10509 * `std::forward`      // `forward(x)` is an rvalue reference to `x`
10510 * `gsl::narrow_cast`  // `narrow_cast<T>(x)` is `static_cast<T>(x)`
10511 * `gsl::narrow`       // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
10513 ##### Example
10515     ???
10517 ##### Note
10519 When converting between types with no information loss (e.g. from `float` to
10520 `double` or `int64` from `int32`), brace initialization may be used instead.
10522     double d{some_float};
10523     int64_t i{some_int32};
10525 This makes it clear that the type conversion was intended and also prevents
10526 conversions between types that might result in loss of precision. (It is a
10527 compilation error to try to initialize a `float` from a `double` in this fashion,
10528 for example.)
10530 ##### Enforcement
10532 Flag C-style and functional casts.
10534 ### <a name="Res-casts-const"></a>ES.50: Don't cast away `const`
10536 ##### Reason
10538 It makes a lie out of `const`.
10540 ##### Note
10542 Usually the reason to "cast away `const`" is to allow the updating of some transient information of an otherwise immutable object.
10543 Examples are caching, memoization, and precomputation.
10544 Such examples are often handled as well or better using `mutable` or an indirection than with a `const_cast`.
10546 ##### Example
10548 Consider keeping previously computed results around for a costly operation:
10550     int compute(int x); // compute a value for x; assume this to be costly
10552     class Cache {   // some type implementing a cache for an int->int operation
10553     public:
10554         pair<bool, int> find(int x) const;   // is there a value for x?
10555         void set(int x, int v);             // make y the value for x
10556         // ...
10557     private:
10558         // ...
10559     };
10561     class X {
10562     public:
10563         int get_val(int x)
10564         {
10565             auto p = cache.find(x);
10566             if (p.first) return p.second;
10567             int val = compute(x);
10568             cache.set(x, val); // insert value for x
10569             return val;
10570         }
10571         // ...
10572     private:
10573         Cache cache;
10574     };
10576 Here, `get_val()` is logically constant, so we would like to make it a `const` member.
10577 To do this we still need to mutate `cache`, so people sometimes resort to a `const_cast`:
10579     class X {   // Suspicious solution based on casting
10580     public:
10581         int get_val(int x) const
10582         {
10583             auto p = cache.find(x);
10584             if (p.first) return p.second;
10585             int val = compute(x);
10586             const_cast<Cache&>(cache).set(x, val);   // ugly
10587             return val;
10588         }
10589         // ...
10590     private:
10591         Cache cache;
10592     };
10594 Fortunately, there is a better solution:
10595 State that `cache` is mutable even for a `const` object:
10597     class X {   // better solution
10598     public:
10599         int get_val(int x) const
10600         {
10601             auto p = cache.find(x);
10602             if (p.first) return p.second;
10603             int val = compute(x);
10604             cache.set(x, val);
10605             return val;
10606         }
10607         // ...
10608     private:
10609         mutable Cache cache;
10610     };
10612 An alternative solution would to store a pointer to the `cache`:
10614     class X {   // OK, but slightly messier solution
10615     public:
10616         int get_val(int x) const
10617         {
10618             auto p = cache->find(x);
10619             if (p.first) return p.second;
10620             int val = compute(x);
10621             cache->set(x, val);
10622             return val;
10623         }
10624         // ...
10625     private:
10626         unique_ptr<Cache> cache;
10627     };
10629 That solution is the most flexible, but requires explicit construction and destruction of `*cache`
10630 (most likely in the constructor and destructor of `X`).
10632 In any variant, we must guard against data races on the `cache` in multithreaded code, possibly using a `std::mutex`.
10634 ##### Enforcement
10636 Flag `const_cast`s.
10638 ### <a name="Res-range-checking"></a>ES.55: Avoid the need for range checking
10640 ##### Reason
10642 Constructs that cannot overflow do not overflow (and usually run faster):
10644 ##### Example
10646     for (auto& x : v)      // print all elements of v
10647         cout << x << '\n';
10649     auto p = find(v, x);   // find x in v
10651 ##### Enforcement
10653 Look for explicit range checks and heuristically suggest alternatives.
10655 ### <a name="Res-move"></a>ES.56: Write `std::move()` only when you need to explicitly move an object to another scope
10657 ##### Reason
10659 We move, rather than copy, to avoid duplication and for improved performance.
10661 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).
10663 ##### Notes
10665 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.
10667 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`.
10669 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.
10671 ##### Example, bad
10673     void sink(X&& x);   // sink takes ownership of x
10675     void user()
10676     {
10677         X x;
10678         // error: cannot bind an lvalue to a rvalue reference
10679         sink(x);
10680         // OK: sink takes the contents of x, x must now be assumed to be empty
10681         sink(std::move(x));
10683         // ...
10685         // probably a mistake
10686         use(x);
10687     }
10689 Usually, a `std::move()` is used as an argument to a `&&` parameter.
10690 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.
10692     void f() {
10693         string s1 = "supercalifragilisticexpialidocious";
10695         string s2 = s1;             // ok, takes a copy
10696         assert(s1 == "supercalifragilisticexpialidocious");  // ok
10698         // bad, if you want to keep using s1's value
10699         string s3 = move(s1);
10701         // bad, assert will likely fail, s1 likely changed
10702         assert(s1 == "supercalifragilisticexpialidocious");
10703     }
10705 ##### Example
10707     void sink(unique_ptr<widget> p);  // pass ownership of p to sink()
10709     void f() {
10710         auto w = make_unique<widget>();
10711         // ...
10712         sink(std::move(w));               // ok, give to sink()
10713         // ...
10714         sink(w);    // Error: unique_ptr is carefully designed so that you cannot copy it
10715     }
10717 ##### Notes
10719 `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.
10720 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.
10722 Never write `std::move()` just because you've heard "it's more efficient."
10723 In general, don't believe claims of "efficiency" without data (???).
10724 In general, don't complicate your code without reason (??)
10726 ##### Example, bad
10728     vector<int> make_vector() {
10729         vector<int> result;
10730         // ... load result with data
10731         return std::move(result);       // bad; just write "return result;"
10732     }
10734 Never write `return move(local_variable);`, because the language already knows the variable is a move candidate.
10735 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.
10738 ##### Example, bad
10740     vector<int> v = std::move(make_vector());   // bad; the std::move is entirely redundant
10742 Never write `move` on a returned value such as `x = move(f());` where `f` returns by value.
10743 The language already knows that a returned value is a temporary object that can be moved from.
10745 ##### Example
10747     void mover(X&& x) {
10748         call_something(std::move(x));         // ok
10749         call_something(std::forward<X>(x));   // bad, don't std::forward an rvalue reference
10750         call_something(x);                    // suspicious, why not std::move?
10751     }
10753     template<class T>
10754     void forwarder(T&& t) {
10755         call_something(std::move(t));         // bad, don't std::move a forwarding reference
10756         call_something(std::forward<T>(t));   // ok
10757         call_something(t);                    // suspicious, why not std::forward?
10758     }
10760 ##### Enforcement
10762 * 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.
10763 * Flag functions taking an `S&&` parameter if there is no `const S&` overload to take care of lvalues.
10764 * 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.
10765 * Flag when `std::move` is applied to a forwarding reference (`T&&` where `T` is a template parameter type). Use `std::forward` instead.
10766 * 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.)
10767 * Flag when `std::forward` is applied to an rvalue reference (`X&&` where `X` is a concrete type). Use `std::move` instead.
10768 * 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.)
10769 * 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.
10771 ### <a name="Res-new"></a>ES.60: Avoid `new` and `delete` outside resource management functions
10773 ##### Reason
10775 Direct resource management in application code is error-prone and tedious.
10777 ##### Note
10779 also known as "No naked `new`!"
10781 ##### Example, bad
10783     void f(int n)
10784     {
10785         auto p = new X[n];   // n default constructed Xs
10786         // ...
10787         delete[] p;
10788     }
10790 There can be code in the `...` part that causes the `delete` never to happen.
10792 **See also**: [R: Resource management](#S-resource).
10794 ##### Enforcement
10796 Flag naked `new`s and naked `delete`s.
10798 ### <a name="Res-del"></a>ES.61: Delete arrays using `delete[]` and non-arrays using `delete`
10800 ##### Reason
10802 That's what the language requires and mistakes can lead to resource release errors and/or memory corruption.
10804 ##### Example, bad
10806     void f(int n)
10807     {
10808         auto p = new X[n];   // n default constructed Xs
10809         // ...
10810         delete p;   // error: just delete the object p, rather than delete the array p[]
10811     }
10813 ##### Note
10815 This example not only violates the [no naked `new` rule](#Res-new) as in the previous example, it has many more problems.
10817 ##### Enforcement
10819 * if the `new` and the `delete` is in the same scope, mistakes can be flagged.
10820 * if the `new` and the `delete` are in a constructor/destructor pair, mistakes can be flagged.
10822 ### <a name="Res-arr2"></a>ES.62: Don't compare pointers into different arrays
10824 ##### Reason
10826 The result of doing so is undefined.
10828 ##### Example, bad
10830     void f(int n)
10831     {
10832         int a1[7];
10833         int a2[9];
10834         if (&a1[5] < &a2[7]) {}       // bad: undefined
10835         if (0 < &a1[5] - &a2[7]) {}   // bad: undefined
10836     }
10838 ##### Note
10840 This example has many more problems.
10842 ##### Enforcement
10846 ### <a name="Res-slice"></a>ES.63: Don't slice
10848 ##### Reason
10850 Slicing -- that is, copying only part of an object using assignment or initialization -- most often leads to errors because
10851 the object was meant to be considered as a whole.
10852 In the rare cases where the slicing was deliberate the code can be surprising.
10854 ##### Example
10856     class Shape { /* ... */ };
10857     class Circle : public Shape { /* ... */ Point c; int r; };
10859     Circle c {{0, 0}, 42};
10860     Shape s {c};    // copy Shape part of Circle
10862 The result will be meaningless because the center and radius will not be copied from `c` into `s`.
10863 The first defense against this is to [define the base class `Shape` not to allow this](#Rc-copy-virtual).
10865 ##### Alternative
10867 If you mean to slice, define an explicit operation to do so.
10868 This saves readers from confusion.
10869 For example:
10871     class Smiley : public Circle {
10872         public:
10873         Circle copy_circle();
10874         // ...
10875     };
10877     Smiley sm { /* ... */ };
10878     Circle c1 {sm};  // ideally prevented by the definition of Circle
10879     Circle c2 {sm.copy_circle()};
10881 ##### Enforcement
10883 Warn against slicing.
10885 ## <a name="SS-numbers"></a>Arithmetic
10887 ### <a name="Res-mix"></a>ES.100: Don't mix signed and unsigned arithmetic
10889 ##### Reason
10891 Avoid wrong results.
10893 ##### Example
10895     int x = -3;
10896     unsigned int y = 7;
10898     cout << x - y << '\n';  // unsigned result, possibly 4294967286
10899     cout << x + y << '\n';  // unsigned result: 4
10900     cout << x * y << '\n';  // unsigned result, possibly 4294967275
10902 It is harder to spot the problem in more realistic examples.
10904 ##### Note
10906 Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts.
10907 This precludes consistency.
10909 ##### Enforcement
10911 Compilers already know and sometimes warn.
10913 ### <a name="Res-unsigned"></a>ES.101: Use unsigned types for bit manipulation
10915 ##### Reason
10917 Unsigned types support bit manipulation without surprises from sign bits.
10919 ##### Example
10921     unsigned char x = 0b1010'1010;
10922     unsigned char y = ~x;   // y == 0b0101'0101;
10924 ##### Note
10926 Unsigned types can also be useful for modulo arithmetic.
10927 However, if you want modulo arithmetic add
10928 comments as necessary noting the reliance on wraparound behavior, as such code
10929 can be surprising for many programmers.
10931 ##### Enforcement
10933 * Just about impossible in general because of the use of unsigned subscripts in the standard library
10934 * ???
10936 ### <a name="Res-signed"></a>ES.102: Use signed types for arithmetic
10938 ##### Reason
10940 Because most arithmetic is assumed to be signed;
10941 `x-y` yields a negative number when `y>x` except in the rare cases where you really want modulo arithmetic.
10943 ##### Example
10945 Unsigned arithmetic can yield surprising results if you are not expecting it.
10946 This is even more true for mixed signed and unsigned arithmetic.
10948     template<typename T, typename T2>
10949     T subtract(T x, T2 y)
10950     {
10951         return x-y;
10952     }
10954     void test()
10955     {
10956         int s = 5;
10957         unsigned int us = 5;
10958         cout << subtract(s, 7) << '\n';     // -2
10959         cout << subtract(us, 7u) << '\n';   // 4294967294
10960         cout << subtract(s, 7u) << '\n';    // -2
10961         cout << subtract(us, 7) << '\n';    // 4294967294
10962         cout << subtract(s, us+2) << '\n';  // -2
10963         cout << subtract(us, s+2) << '\n';  // 4294967294
10964     }
10966 Here we have been very explicit about what's happening,
10967 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`?
10969 ##### Exception
10971 Use unsigned types if you really want modulo arithmetic - add
10972 comments as necessary noting the reliance on overflow behavior, as such code
10973 is going to be surprising for many programmers.
10975 ##### Example
10977 The standard library uses unsigned types for subscripts.
10978 The build-in array uses signed types for subscripts.
10979 This makes surprises (and bugs) inevitable.
10981     int a[10];
10982     for (int i=0; i < 10; ++i) a[i]=i;
10983     vector<int> v(10);
10984     // compares signed to unsigned; some compilers warn
10985     for (int i=0; v.size() < 10; ++i) v[i]=i;
10987     int a2[-2];         // error: negative size
10989     // OK, but the number of ints (4294967294) is so large that we should get an exception
10990     vector<int> v2(-2);
10992 ##### Enforcement
10994 * Flag mixed signed and unsigned arithmetic
10995 * Flag results of unsigned arithmetic assigned to or printed as signed.
10996 * Flag unsigned literals (e.g. `-2`) used as container subscripts.
10998 ### <a name="Res-overflow"></a>ES.103: Don't overflow
11000 ##### Reason
11002 Overflow usually makes your numeric algorithm meaningless.
11003 Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.
11005 ##### Example, bad
11007     int a[10];
11008     a[10] = 7;   // bad
11010     int n = 0;
11011     while (n++ < 10)
11012         a[n - 1] = 9; // bad (twice)
11014 ##### Example, bad
11016     int n = numeric_limits<int>::max();
11017     int m = n + 1;   // bad
11019 ##### Example, bad
11021     int area(int h, int w) { return h * w; }
11023     auto a = area(10'000'000, 100'000'000);   // bad
11025 ##### Exception
11027 Use unsigned types if you really want modulo arithmetic.
11029 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
11031 ##### Enforcement
11035 ### <a name="Res-underflow"></a>ES.104: Don't underflow
11037 ##### Reason
11039 Decrementing a value beyond a minimum value can lead to memory corruption and undefined behavior.
11041 ##### Example, bad
11043     int a[10];
11044     a[-2] = 7;   // bad
11046     int n = 101;
11047     while (n--)
11048         a[n - 1] = 9;   // bad (twice)
11050 ##### Exception
11052 Use unsigned types if you really want modulo arithmetic.
11054 ##### Enforcement
11058 ### <a name="Res-zero"></a>ES.105: Don't divide by zero
11060 ##### Reason
11062 The result is undefined and probably a crash.
11064 ##### Note
11066 This also applies to `%`.
11068 ##### Example; bad
11070     double divide(int a, int b) {
11071         // BAD, should be checked (e.g., in a precondition)
11072         return a / b;
11073     }
11075 ##### Example; good
11077     double divide(int a, int b) {
11078         // good, address via precondition (and replace with contracts once C++ gets them)
11079         Expects(b != 0);
11080         return a / b;
11081     }
11083     double divide(int a, int b) {
11084         // good, address via check
11085         return b ? a / b : quiet_NaN<double>();
11086     }
11088 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
11090 ##### Enforcement
11092 * Flag division by an integral value that could be zero
11094 # <a name="S-performance"></a>Per: Performance
11096 ??? should this section be in the main guide???
11098 This section contains rules for people who need high performance or low-latency.
11099 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.
11100 The rules in this section are more restrictive and intrusive than what is needed for many (most) applications.
11101 Do not blindly try to follow them in general code: achieving the goals of low latency requires extra work.
11103 Performance rule summary:
11105 * [Per.1: Don't optimize without reason](#Rper-reason)
11106 * [Per.2: Don't optimize prematurely](#Rper-Knuth)
11107 * [Per.3: Don't optimize something that's not performance critical](#Rper-critical)
11108 * [Per.4: Don't assume that complicated code is necessarily faster than simple code](#Rper-simple)
11109 * [Per.5: Don't assume that low-level code is necessarily faster than high-level code](#Rper-low)
11110 * [Per.6: Don't make claims about performance without measurements](#Rper-measure)
11111 * [Per.7: Design to enable optimization](#Rper-efficiency)
11112 * [Per.10: Rely on the static type system](#Rper-type)
11113 * [Per.11: Move computation from run time to compile time](#Rper-Comp)
11114 * [Per.12: Eliminate redundant aliases](#Rper-alias)
11115 * [Per.13: Eliminate redundant indirections](#Rper-indirect)
11116 * [Per.14: Minimize the number of allocations and deallocations](#Rper-alloc)
11117 * [Per.15: Do not allocate on a critical branch](#Rper-alloc0)
11118 * [Per.16: Use compact data structures](#Rper-compact)
11119 * [Per.17: Declare the most used member of a time-critical struct first](#Rper-struct)
11120 * [Per.18: Space is time](#Rper-space)
11121 * [Per.19: Access memory predictably](#Rper-access)
11122 * [Per.30: Avoid context switches on the critical path](#Rper-context)
11124 ### <a name="Rper-reason"></a>Per.1: Don't optimize without reason
11126 ##### Reason
11128 If there is no need for optimization, the main result of the effort will be more errors and higher maintenance costs.
11130 ##### Note
11132 Some people optimize out of habit or because it's fun.
11136 ### <a name="Rper-Knuth"></a>Per.2: Don't optimize prematurely
11138 ##### Reason
11140 Elaborately optimized code is usually larger and harder to change than unoptimized code.
11144 ### <a name="Rper-critical"></a>Per.3: Don't optimize something that's not performance critical
11146 ##### Reason
11148 Optimizing a non-performance-critical part of a program has no effect on system performance.
11150 ##### Note
11152 If your program spends most of its time waiting for the web or for a human, optimization of in-memory computation is probably useless.
11154 Put another way: If your program spends 4% of its processing time doing
11155 computation A and 40% of its time doing computation B, a 50% improvement on A is
11156 only as impactful as a 5% improvement on B. (If you don't even know how much
11157 time is spent on A or B, see <a href="#Rper-reason">Per.1</a> and <a
11158 href="#Rper-Knuth">Per.2</a>.)
11160 ### <a name="Rper-simple"></a>Per.4: Don't assume that complicated code is necessarily faster than simple code
11162 ##### Reason
11164 Simple code can be very fast. Optimizers sometimes do marvels with simple code
11166 ##### Example, good
11168     // clear expression of intent, fast execution
11170     vector<uint8_t> v(100000);
11172     for (auto& c : v)
11173         c = ~c;
11175 ##### Example, bad
11177     // intended to be faster, but is actually slower
11179     vector<uint8_t> v(100000);
11181     for (size_t i = 0; i < v.size(); i += sizeof(uint64_t))
11182     {
11183         uint64_t& quad_word = *reinterpret_cast<uint64_t*>(&v[i]);
11184         quad_word = ~quad_word;
11185     }
11187 ##### Note
11193 ### <a name="Rper-low"></a>Per.5: Don't assume that low-level code is necessarily faster than high-level code
11195 ##### Reason
11197 Low-level code sometimes inhibits optimizations. Optimizers sometimes do marvels with high-level code.
11199 ##### Note
11205 ### <a name="Rper-measure"></a>Per.6: Don't make claims about performance without measurements
11207 ##### Reason
11209 The field of performance is littered with myth and bogus folklore.
11210 Modern hardware and optimizers defy naive assumptions; even experts are regularly surprised.
11212 ##### Note
11214 Getting good performance measurements can be hard and require specialized tools.
11216 ##### Note
11218 A few simple microbenchmarks using Unix `time` or the standard library `<chrono>` can help dispel the most obvious myths.
11219 If you can't measure your complete system accurately, at least try to measure a few of your key operations and algorithms.
11220 A profiler can help tell you which parts of your system are performance critical.
11221 Often, you will be surprised.
11225 ### <a name="Rper-efficiency"></a>Per.7: Design to enable optimization
11227 ##### Reason
11229 Because we often need to optimize the initial design.
11230 Because a design that ignore the possibility of later improvement is hard to change.
11232 ##### Example
11234 From the C (and C++) standard:
11236     void qsort (void* base, size_t num, size_t size, int (*compar)(const void*, const void*));
11238 When did you even want to sort memory?
11239 Really, we sort sequences of elements, typically stored in containers.
11240 A call to `qsort` throws away much useful information (e.g., the element type), forces the user to repeat information
11241 already known (e.g., the element size), and forces the user to write extra code (e.g., a function to compare `double`s).
11242 This implies added work for the programmer, is error prone, and deprives the compiler of information needed for optimization.
11244     double data[100];
11245     // ... fill a ...
11247     // 100 chunks of memory of sizeof(double) starting at
11248     // address data using the order defined by compare_doubles
11249     qsort(data, 100, sizeof(double), compare_doubles);
11251 From the point of view of interface design is that `qsort` throws away useful information.
11253 We can do better (in C++98)
11255     template<typename Iter>
11256         void sort(Iter b, Iter e);  // sort [b:e)
11258     sort(data, data + 100);
11260 Here, we use the compiler's knowledge about the size of the array, the type of elements, and how to compare `double`s.
11262 With C++11 plus [concepts](#???), we can do better still
11264     // Sortable specifies that c must be a
11265     // random-access sequence of elements comparable with <
11266     void sort(Sortable& c);
11268     sort(c);
11270 The key is to pass sufficient information for a good implementation to be chosen.
11271 In this, the `sort` interfaces shown here still have a weakness:
11272 They implicitly rely on the element type having less-than (`<`) defined.
11273 To complete the interface, we need a second version that accepts a comparison criteria:
11275     // compare elements of c using p
11276     void sort(Sortable& c, Predicate<Value_type<Sortable>> p);
11278 The standard-library specification of `sort` offers those two versions,
11279 but the semantics is expressed in English rather than code using concepts.
11281 ##### Note
11283 Premature optimization is said to be [the root of all evil](#Rper-Knuth), but that's not a reason to despise performance.
11284 It is never premature to consider what makes a design amenable to improvement, and improved performance is a commonly desired improvement.
11285 Aim to build a set of habits that by default results in efficient, maintainable, and optimizable code.
11286 In particular, when you write a function that is not a one-off implementation detail, consider
11288 * Information passing:
11289 Prefer clean [interfaces](#S-interfaces) carrying sufficient information for later improvement of implementation.
11290 Note that information flows into and out of an implementation through the interfaces we provide.
11291 * Compact data: By default, [use compact data](#Rper-compact), such as `std::vector` and [access it in a systematic fashion](#Rper-access).
11292 If you think you need a linked structure, try to craft the interface so that this structure isn't seen by users.
11293 * Function argument passing and return:
11294 Distinguish between mutable and non-mutable data.
11295 Don't impose a resource management burden on your users.
11296 Don't impose spurious run-time indirections on your users.
11297 Use [conventional ways](#Rf-conventional) of passing information through an interface;
11298 unconventional and/or "optimized" ways of passing data can seriously complicate later reimplementation.
11299 * Abstraction:
11300 Don't overgeneralize; a design that tries to cater for every possible use (and misuse) and defers every design decision for later
11301 (using compile-time or run-time indirections) is usually a complicated, bloated, hard-to-understand mess.
11302 Generalize from concrete examples, preserving performance as we generalize.
11303 Do not generalize based on mere speculation about future needs.
11304 The ideal is zero-overhead generalization.
11305 * Libraries:
11306 Use libraries with good interfaces.
11307 If no library is available build one yourself and imitate the interface style from a good library.
11308 The [standard library](#S-stdlib) is a good first place to look for inspiration.
11309 * Isolation:
11310 Isolate your code from messy and/or old style code by providing an interface of your choosing to it.
11311 This is sometimes called "providing a wrapper" for the useful/necessary but messy code.
11312 Don't let bad designs "bleed into" your code.
11314 ##### Example
11316 Consider:
11318     template <class ForwardIterator, class T>
11319     bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
11321 `binary_search(begin(c), end(c), 7)` will tell you whether `7` is in `c` or not.
11322 However, it will not tell you where that `7` is or whether there are more than one `7`.
11324 Sometimes, just passing the minimal amount of information back (here, `true` or `false`) is sufficient, but a good interface passes
11325 needed information back to the caller. Therefore, the standard library also offers
11327     template <class ForwardIterator, class T>
11328     ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val);
11330 `lower_bound` returns an iterator to the first match if any, otherwise `last`.
11332 However, `lower_bound` still doesn't return enough information for all uses, so the standard library also offers
11334     template <class ForwardIterator, class T>
11335     pair<ForwardIterator, ForwardIterator>
11336     equal_range(ForwardIterator first, ForwardIterator last, const T& val);
11338 `equal_range` returns a `pair` of iterators specifying the first and one beyond last match.
11340     auto r = equal_range(begin(c), end(c), 7);
11341     for (auto p = r.first(); p != r.second(), ++p)
11342         cout << *p << '\n';
11344 Obviously, these three interfaces are implemented by the same basic code.
11345 They are simply three ways of presenting the basic binary search algorithm to users,
11346 ranging from the simplest ("make simple things simple!")
11347 to returning complete, but not always needed, information ("don't hide useful information").
11348 Naturally, crafting such a set of interfaces requires experience and domain knowledge.
11350 ##### Note
11352 Do not simply craft the interface to match the first implementation and the first use case you think of.
11353 Once your first initial implementation is complete, review it; once you deploy it, mistakes will be hard to remedy.
11355 ##### Note
11357 A need for efficiency does not imply a need for [low-level code](#Rper-low).
11358 High-level code does not imply slow or bloated.
11360 ##### Note
11362 Things have costs.
11363 Don't be paranoid about costs (modern computers really are very fast),
11364 but have a rough idea of the order of magnitude of cost of what you use.
11365 For example, have a rough idea of the cost of
11366 a memory access,
11367 a function call,
11368 a string comparison,
11369 a system call,
11370 a disk access,
11371 and a message through a network.
11373 ##### Note
11375 If you can only think of one implementation, you probably don't have something for which you can devise a stable interface.
11376 Maybe, it is just an implementation detail - not every piece of code needs a stable interface - but pause and consider.
11377 One question that can be useful is
11378 "what interface would be needed if this operation should be implemented using multiple threads? be vectorized?"
11380 ##### Note
11382 This rule does not contradict the [Don't optimize prematurely](#Rper-Knuth) rule.
11383 It complements it encouraging developers enable later - appropriate and non-premature - optimization, if and where needed.
11385 ##### Enforcement
11387 Tricky.
11388 Maybe looking for `void*` function arguments will find examples of interfaces that hinder later optimization.
11390 ### <a name="Rper-type"></a>Per.10: Rely on the static type system
11392 ##### Reason
11394 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.
11398 ### <a name="Rper-Comp"></a>Per.11: Move computation from run time to compile time
11402 ### <a name="Rper-alias"></a>Per.12: Eliminate redundant aliases
11406 ### <a name="Rper-indirect"></a>Per.13: Eliminate redundant indirections
11410 ### <a name="Rper-alloc"></a>Per.14: Minimize the number of allocations and deallocations
11414 ### <a name="Rper-alloc0"></a>Per.15: Do not allocate on a critical branch
11418 ### <a name="Rper-compact"></a>Per.16: Use compact data structures
11420 ##### Reason
11422 Performance is typically dominated by memory access times.
11426 ### <a name="Rper-struct"></a>Per.17: Declare the most used member of a time-critical struct first
11430 ### <a name="Rper-space"></a>Per.18: Space is time
11432 ##### Reason
11434 Performance is typically dominated by memory access times.
11438 ### <a name="Rper-access"></a>Per.19: Access memory predictably
11440 ##### Reason
11442 Performance is very sensitive to cache performance and cache algorithms favor simple (usually linear) access to adjacent data.
11444 ##### Example
11446     int matrix[rows][cols];
11448     // bad
11449     for (int c = 0; c < cols; ++c)
11450         for (int r = 0; r < rows; ++r)
11451             sum += matrix[r][c];
11453     // good
11454     for (int r = 0; r < rows; ++r)
11455         for (int c = 0; c < cols; ++c)
11456             sum += matrix[r][c];
11458 ### <a name="Rper-context"></a>Per.30: Avoid context switches on the critical path
11462 # <a name="S-concurrency"></a>CP: Concurrency and Parallelism
11464 We often want our computers to do many tasks at the same time (or at least make them appear to do them at the same time).
11465 The reasons for doing so varies (e.g., wanting to wait for many events using only a single processor, processing many data streams simultaneously, or utilizing many hardware facilities)
11466 and so does the basic facilities for expressing concurrency and parallelism.
11467 Here, we articulate a few general principles and rules for using the ISO standard C++ facilities for expressing basic concurrency and parallelism.
11469 The core machine support for concurrent and parallel programming is the thread.
11470 Threads allow you to run multiple instances of your program independently, while sharing
11471 the same memory. Concurrent programming is tricky for many reasons, most
11472 importantly that it is undefined behavior to read data in one thread after it
11473 was written by another thread, if there is no proper synchronization between
11474 those threads. Making existing single-threaded code execute concurrently can be
11475 as trivial as adding `std::async` or `std::thread` strategically, or it can
11476 necessitate a full rewrite, depending on whether the original code was written
11477 in a thread-friendly way.
11479 The concurrency/parallelism rules in this document are designed with three goals
11480 in mind:
11482 * To help you write code that is amenable to being used in a threaded
11483   environment
11484 * To show clean, safe ways to use the threading primitives offered by the
11485   standard library
11486 * To offer guidance on what to do when concurrency and parallelism aren't giving
11487   you the performance gains you need
11489 It is also important to note that concurrency in C++ is an unfinished
11490 story. C++11 introduced many core concurrency primitives, C++14 improved on
11491 them, and it seems that there is much interest in making the writing of
11492 concurrent programs in C++ even easier. We expect some of the library-related
11493 guidance here to change significantly over time.
11495 This section needs a lot of work (obviously).
11496 Please note that we start with rules for relative non-experts.
11497 Real experts must wait a bit;
11498 contributions are welcome,
11499 but please think about the majority of programmers who are struggling to get their concurrent programs correct and performant.
11501 Concurrency and parallelism rule summary:
11503 * [CP.1: Assume that your code will run as part of a multi-threaded program](#Rconc-multi)
11504 * [CP.2: Avoid data races](#Rconc-races)
11505 * [CP.3: Minimize explicit sharing of writable data](#Rconc-data)
11506 * [CP.4: Think in terms of tasks, rather than threads](#Rconc-task)
11507 * [CP.8: Don't try to use `volatile` for synchronization](#Rconc-volatile)
11509 See also:
11511 * [CP.con: Concurrency](#SScp-con)
11512 * [CP.par: Parallelism](#SScp-par)
11513 * [CP.mess: Message passing](#SScp-mess)
11514 * [CP.vec: Vectorization](#SScp-vec)
11515 * [CP.free: Lock-free programming](#SScp-free)
11516 * [CP.etc: Etc. concurrency rules](#SScp-etc)
11518 ### <a name="Rconc-multi"></a>CP.1: Assume that your code will run as part of a multi-threaded program
11520 ##### Reason
11522 It is hard to be certain that concurrency isn't used now or will be sometime in the future.
11523 Code gets re-used.
11524 Libraries using threads may be used from some other part of the program.
11525 Note that this applies most urgently to library code and least urgently to stand-alone applications.
11526 However, thanks to the magic of cut-and-paste, code fragments can turn up in unexpected places.
11528 ##### Example
11530     double cached_computation(double x)
11531     {
11532         static double cached_x = 0.0;
11533         static double cached_result = COMPUTATION_OF_ZERO;
11534         double result;
11536         if (cached_x == x)
11537             return cached_result;
11538         result = computation(x);
11539         cached_x = x;
11540         cached_result = result;
11541         return result;
11542     }
11544 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.
11546 There are several ways that this example could be made safe for a multi-threaded environment:
11548 * Delegate concurrency concerns upwards to the caller.
11549 * Mark the `static` variables as `thread_local` (which might make caching less effective).
11550 * Implement concurrency control, for example, protecting the two `static` variables with a `static` lock (which might reduce performance).
11551 * Have the caller provide the memory to be used for the cache, thereby delegating both memory allocation and concurrency concerns upwards to the caller.
11552 * Refuse to build and/or run in a multi-threaded environment.
11553 * Provide two implementations, one which is used in single-threaded environments and another which is used in multi-threaded environments.
11555 ##### Exception
11557 Code that is never run in a multi-threaded environment.
11559 Be careful: there are many examples where code that was "known" to never run in a multi-threaded program
11560 was run as part of a multi-threaded program. Often years later.
11561 Typically, such programs lead to a painful effort to remove data races.
11562 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.
11564 ### <a name="Rconc-races"></a>CP.2: Avoid data races
11566 ##### Reason
11568 Unless you do, nothing is guaranteed to work and subtle errors will persist.
11570 ##### Note
11572 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.
11573 For further information of how to use synchronization well to eliminate data races, please consult a good book about concurrency.
11575 ##### Example, bad
11577 There are many examples of data races that exist, some of which are running in
11578 production software at this very moment. One very simple example:
11580     int get_id() {
11581       static int id = 1;
11582       return id++;
11583     }
11585 The increment here is an example of a data race. This can go wrong in many ways,
11586 including:
11588 * Thread A loads the value of `id`, the OS context switches A out for some
11589   period, during which other threads create hundreds of IDs. Thread A is then
11590   allowed to run again, and `id` is written back to that location as A's read of
11591   `id` plus one.
11592 * Thread A and B load `id` and increment it simultaneously.  They both get the
11593   same ID.
11595 Local static variables are a common source of data races.
11597 ##### Example, bad:
11599     void f(fstream&  fs, regex pat)
11600     {
11601         array<double, max> buf;
11602         int sz = read_vec(fs, buf, max);            // read from fs into buf
11603         gsl::span<double> s {buf};
11604         // ...
11605         auto h1 = async([&]{ sort(par, s); });     // spawn a task to sort
11606         // ...
11607         auto h2 = async([&]{ return find_all(buf, sz, pat); });   // span a task to find matches
11608         // ...
11609     }
11611 Here, we have a (nasty) data race on the elements of `buf` (`sort` will both read and write).
11612 All data races are nasty.
11613 Here, we managed to get a data race on data on the stack.
11614 Not all data races are as easy to spot as this one.
11616 ##### Example, bad:
11618     // code not controlled by a lock
11620     unsigned val;
11622     if (val < 5) {
11623         // ... other thread can change val here ...
11624         switch (val) {
11625         case 0: // ...
11626         case 1: // ...
11627         case 2: // ...
11628         case 3: // ...
11629         case 4: // ...
11630         }
11631     }
11633 Now, a compiler that does not know that `val` can change will  most likely implement that `switch` using a jump table with five entries.
11634 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.
11635 Really, "all bets are off" if you get a data race.
11636 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;
11637 this can be a security risk.
11639 ##### Enforcement
11641 Some is possible, do at least something.
11642 There are commercial and open-source tools that try to address this problem, but static tools often have many false positives and run-time tools often have a significant cost.
11643 We hope for better tools.
11645 Help the tools:
11647 * less global data
11648 * fewer `static` variables
11649 * more use of stack memory (and don't pass pointers around too much)
11650 * more immutable data (literals, `constexpr`, and `const`)
11652 ### <a name="Rconc-data"></a>CP.3: Minimize explicit sharing of writable data
11654 ##### Reason
11656 If you don't share writable data, you can't have a data race.
11657 The less sharing you do, the less chance you have to forget to synchronize access (and get data races).
11658 The less sharing you do, the less chance you have to wait on a lock (so performance can improve).
11660 ##### Example
11662     bool validate(const vector<Reading>&);
11663     Graph<Temp_node> temperature_gradiants(const vector<Reading>&);
11664     Image altitude_map(const vector<Reading>&);
11665     // ...
11667     void process_readings(istream& socket1)
11668     {
11669         vector<Reading> surface_readings;
11670         socket1 >> surface_readings;
11671         if (!socket1) throw Bad_input{};
11673         auto h1 = async([&] { if (!validate(surface_readings) throw Invalide_data{}; });
11674         auto h2 = async([&] { return temperature_gradiants(surface_readings); });
11675         auto h3 = async([&] { return altitude_map(surface_readings); });
11676         // ...
11677         auto v1 = h1.get();
11678         auto v2 = h2.get();
11679         auto v3 = h3.get();
11680         // ...
11681     }
11683 Without those `const`s, we would have to review every asynchronously invoked function for potential data races on `surface_readings`.
11685 ##### Note
11687 Immutable data can be safely and efficiently shared.
11688 No locking is needed: You can't have a data race on a constant.
11690 ##### Enforcement
11695 ### <a name="Rconc-task"></a>CP.4: Think in terms of tasks, rather than threads
11697 ##### Reason
11699 A `thread` is an implementation concept, a way of thinking about the machine.
11700 A task is an application notion, something you'd like to do, preferably concurrently with other tasks.
11701 Application concepts are easier to reason about.
11703 ##### Example
11705     ???
11707 ##### Note
11709 With the exception of `async()`, the standard-library facilities are low-level, machine-oriented, threads-and-lock level.
11710 This is a necessary foundation, but we have to try to raise the level of abstraction: for productivity, for reliability, and for performance.
11711 This is a potent argument for using higher level, more applications-oriented libraries (if possibly, built on top of standard-library facilities).
11713 ##### Enforcement
11717 ### <a name="Rconc-volatile"></a>CP.8: Don't try to use `volatile` for synchronization
11719 ##### Reason
11721 In C++, unlike some other languages, `volatile` does not provide atomicity, does not synchronize between threads,
11722 and does not prevent instruction reordering (neither compiler nor hardware).
11723 It simply has nothing to do with concurrency.
11725 ##### Example, bad:
11727     int free_slots = max_slots; // current source of memory for objects
11729     Pool* use()
11730     {
11731         if (int n = free_slots--) return &pool[n];
11732     }
11734 Here we have a problem:
11735 This is perfectly good code in a single-threaded program, but have two treads execute this and
11736 there is a race condition on `free_slots` so that two threads might get the same value and `free_slots`.
11737 That's (obviously) a bad data race, so people trained in other languages may try to fix it like this:
11739     volatile int free_slots = max_slots; // current source of memory for objects
11741     Pool* use()
11742     {
11743         if (int n = free_slots--) return &pool[n];
11744     }
11746 This has no effect on synchronization: The data race is still there!
11748 The C++ mechanism for this is `atomic` types:
11750     atomic<int> free_slots = max_slots; // current source of memory for objects
11752     Pool* use()
11753     {
11754         if (int n = free_slots--) return &pool[n];
11755     }
11757 Now the `--` operation is atomic,
11758 rather than a read-increment-write sequence where another thread might get in-between the individual operations.
11760 ##### Alternative
11762 Use `atomic` types where you might have used `volatile` in some other language.
11763 Use a `mutex` for more complicated examples.
11765 ##### See also
11767 [(rare) proper uses of `volatile`](#Rconc-volatile2)
11769 ## <a name="SScp-con"></a>CP.con: Concurrency
11771 This section focuses on relatively ad-hoc uses of multiple threads communicating through shared data.
11773 * For parallel algorithms, see [parallelism](#SScp-par)
11774 * For inter-task communication without explicit sharing, see [messaging](#SScp-mess)
11775 * For vector parallel code, see [vectorization](#SScp-vec)
11776 * For lock-free programming, see [lock free](#SScp-free)
11778 Concurrency rule summary:
11780 * [CP.20: Use RAII, never plain `lock()`/`unlock()`](#Rconc-raii)
11781 * [CP.21: Use `std::lock()` to acquire multiple `mutex`es](#Rconc-lock)
11782 * [CP.22: Never call unknown code while holding a lock (e.g., a callback)](#Rconc-unknown)
11783 * [CP.23: Think of a joining `thread` as a scoped container](#Rconc-join)
11784 * [CP.24: Think of a detached `thread` as a global container](#Rconc-detach)
11785 * [CP.25: Prefer `gsl::raii_thread` over `std::thread` unless you plan to `detach()`](#Rconc-raii_thread)
11786 * [CP.26: Prefer `gsl::detached_thread` over `std::thread` if you plan to `detach()`](#Rconc-detached_thread)
11787 * [CP.27: Use plain `std::thread` for `thread`s that detach based on a run-time condition (only)](#Rconc-thread)
11788 * [CP.28: Remember to join scoped `thread`s that are not `detach()`ed](#Rconc-join-undetached)
11789 * [CP.30: Do not pass pointers to local variables to non-`raii_thread`s](#Rconc-pass)
11790 * [CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer](#Rconc-data-by-value)
11791 * [CP.32: To share ownership between unrelated `thread`s use `shared_ptr`](#Rconc-shared)
11792 * [CP.40: Minimize context switching](#Rconc-switch)
11793 * [CP.41: Minimize thread creation and destruction](#Rconc-create)
11794 * [CP.42: Don't `wait` without a condition](#Rconc-wait)
11795 * [CP.43: Minimize time spent in a critical section](#Rconc-time)
11796 * [CP.44: Remember to name your `lock_guard`s and `unique_lock`s](#Rconc-name)
11797 * [CP.50: Define a `mutex` together with the data it protects](#Rconc-mutex)
11798 * ??? when to use a spinlock
11799 * ??? when to use `try_lock()`
11800 * ??? when to prefer `lock_guard` over `unique_lock`
11801 * ??? Time multiplexing
11802 * ??? when/how to use `new thread`
11804 ### <a name="Rconc-raii"></a>CP.20: Use RAII, never plain `lock()`/`unlock()`
11806 ##### Reason
11808 Avoids nasty errors from unreleased locks.
11810 ##### Example, bad
11812     mutex mtx;
11814     void do_stuff()
11815     {
11816         mtx.lock();
11817         // ... do stuff ...
11818         mtx.unlock();
11819     }
11821 Sooner or later, someone will forget the `mtx.unlock()`, place a `return` in the `... do stuff ...`, throw an exception, or something.
11823     mutex mtx;
11825     void do_stuff()
11826     {
11827         unique_lock<mutex> lck {mtx};
11828         // ... do stuff ...
11829     }
11831 ##### Enforcement
11833 Flag calls of member `lock()` and `unlock()`.  ???
11836 ### <a name="Rconc-lock"></a>CP.21: Use `std::lock()` to acquire multiple `mutex`es
11838 ##### Reason
11840 To avoid deadlocks on multiple `mutex`s
11842 ##### Example
11844 This is asking for deadlock:
11846     // thread 1
11847     lock_guard<mutex> lck1(m1);
11848     lock_guard<mutex> lck2(m2);
11850     // thread 2
11851     lock_guard<mutex> lck2(m2);
11852     lock_guard<mutex> lck1(m1);
11854 Instead, use `lock()`:
11856     // thread 1
11857     lock_guard<mutex> lck1(m1, defer_lock);
11858     lock_guard<mutex> lck2(m2, defer_lock);
11859     lock(lck1, lck2);
11861     // thread 2
11862     lock_guard<mutex> lck2(m2, defer_lock);
11863     lock_guard<mutex> lck1(m1, defer_lock);
11864     lock(lck2, lck1);
11866 Here, the writers of `thread1` and `thread2` are still not agreeing on the order of the `mutex`es, but order no longer matters.
11868 ##### Note
11870 In real code, `mutex`es are rarely named to conveniently remind the programmer of an intended relation and intended order of acquisition.
11871 In real code, `mutex`es are not always conveniently acquired on consecutive lines.
11873 I'm really looking forward to be able to write plain
11875     lock_guard lck1(m1, defer_lock);
11877 and have the `mutex` type deduced.
11879 ##### Enforcement
11881 Detect the acquisition of multiple `mutex`es.
11882 This is undecidable in general, but catching common simple examples (like the one above) is easy.
11885 ### <a name="Rconc-unknown"></a>CP.22: Never call unknown code while holding a lock (e.g., a callback)
11887 ##### Reason
11889 If you don't know what a piece of code does, you are risking deadlock.
11891 ##### Example
11893     void do_this(Foo* p)
11894     {
11895         lock_guard<mutex> lck {my_mutex};
11896         // ... do something ...
11897         p->act(my_data);
11898         // ...
11899     }
11901 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),
11902 it may call `do_this` (recursively) and cause a deadlock on `my_mutex`.
11903 Maybe it will lock on a different mutex and not return in a reasonable time, causing delays to any code calling `do_this`.
11905 ##### Example
11907 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.
11908 Such problem can often be solved by using a `recursive_mutex`. For example:
11910     recursive_mutex my_mutex;
11912     template<typename Action>
11913     void do_something(Action f)
11914     {
11915         unique_lock<recursive_mutex> lck {my_mutex};
11916         // ... do something ...
11917         f(this);    // f will do something to *this
11918         // ...
11919     }
11921 If, as it is likely, `f()` invokes operations on `*this`, we must make sure that the object's invariant holds before the call.
11923 ##### Enforcement
11925 * Flag calling a virtual function with a non-recursive `mutex` held
11926 * Flag calling a callback with a non-recursive `mutex` held
11929 ### <a name="Rconc-join"></a>CP.23: Think of a joining `thread` as a scoped container
11931 ##### Reason
11933 To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a `thread`.
11934 If a `thread` joins, we can safely pass pointers to objects in the scope of the `thread` and its enclosing scopes.
11936 ##### Example
11938     void f(int * p)
11939     {
11940         // ...
11941         *p = 99;
11942         // ...
11943     }
11944     int glob = 33;
11946     void some_fct(int* p)
11947     {
11948         int x = 77;
11949         raii_thread t0(f, &x);           // OK
11950         raii_thread t1(f, p);            // OK
11951         raii_thread t2(f, &glob);        // OK
11952         auto q = make_unique<int>(99);
11953         raii_thread t3(f, q.get());      // OK
11954         // ...
11955     }
11957 An `raii_thread` is a `std::thread` with a destructor that joined and cannot be `detached()`.
11958 By "OK" we mean that the object will be in scope ("live") for as long as a `thread` can use the pointer to it.
11959 The fact that `thread`s run concurrently doesn't affect the lifetime or ownership issues here;
11960 these `thread`s can be seen as just a function object called from `some_fct`.
11962 ##### Enforcement
11964 Ensure that `raii_thread`s don't `detach()`.
11965 After that, the usual lifetime and ownership (for local objects) enforcement applies.
11968 ### <a name="Rconc-detach"></a>CP.24: Think of a detached `thread` as a global container
11970 ##### Reason
11972 To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a `thread`.
11973 If a `thread` is detached, we can safely pass pointers to static and free store objects (only).
11975 ##### Example
11977     void f(int * p)
11978     {
11979         // ...
11980         *p = 99;
11981         // ...
11982     }
11984     int glob = 33;
11986     void some_fct(int* p)
11987     {
11988         int x = 77;
11989         std::thread t0(f, &x);           // bad
11990         std::thread t1(f, p);            // bad
11991         std::thread t2(f, &glob);        // OK
11992         auto q = make_unique<int>(99);
11993         std::thread t3(f, q.get());      // bad
11994         // ...
11995         t0.detach();
11996         t1.detach();
11997         t2.detach();
11998         t3.detach();
11999         // ...
12000     }
12002 By "OK" we mean that the object will be in scope ("live") for as long as a `thread` can use the pointers to it.
12003 By "bad" we mean that a `thread` may use a pointer after the pointed-to object is destroyed.
12004 The fact that `thread`s run concurrently doesn't affect the lifetime or ownership issues here;
12005 these `thread`s can be seen as just a function object called from `some_fct`.
12007 ##### Enforcement
12009 In general, it is undecidable whether a `detach()` is executed for a `thread`, but simple common cases are easily detected.
12010 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;
12011 After that, the usual lifetime and ownership (for global objects) enforcement applies.
12014 ### <a name="Rconc-raii_thread"></a>CP.25: Prefer `gsl::raii_thread` over `std::thread` unless you plan to `detach()`
12016 ##### Reason
12018 An `raii_thread` is a thread that joins at the end of its scope.
12020 Detached threads are hard to monitor.
12022 ??? Place all "immortal threads" on the free store rather than `detach()`?
12024 ##### Example
12026     ???
12028 ##### Enforcement
12032 ### <a name="Rconc-detached_thread"></a>CP.26: Prefer `gsl::detached_thread` over `std::thread` if you plan to `detach()`
12034 ##### Reason
12036 Often, the need to `detach` is inherent in the `thread`s task.
12037 Documenting that aids comprehension and helps static analysis.
12039 ##### Example
12041     void heartbeat();
12043     void use()
12044     {
12045         gsl::detached_thread t1(heartbeat);    // obviously need not be joined
12046         std::thread t2(heartbeat);             // do we need to join? (read the code for heartbeat())
12047         // ...
12048     }
12050 Flag unconditional `detach` on a plain `thread`
12053 ### <a name="Rconc-thread"></a>CP.27: Use plain `std::thread` for `thread`s that detach based on a run-time condition (only)
12055 ##### Reason
12057 `thread`s that are supposed to unconditionally `join` or unconditionally `detach` can be clearly identified as such.
12058 The plain `thread`s should be assumed to use the full generality of `std::thread`.
12060 ##### Example
12062     void tricky(thread* t, int n)
12063     {
12064         // ...
12065         if (is_odd(n))
12066             t->detach();
12067         // ...
12068     }
12070     void use(int n)
12071     {
12072         thread t { tricky, this, n };
12073         // ...
12074         // ... should I join here? ...
12075     }
12077 ##### Enforcement
12083 ### <a name="Rconc-join-undetached"></a>CP.28: Remember to join scoped `thread`s that are not `detach()`ed
12085 ##### Reason
12087 A `thread` that has not been `detach()`ed when it is destroyed terminates the program.
12089 ##### Example, bad
12091     void f() { std::cout << "Hello "; }
12093     struct F {
12094         void operator()() { std::cout << "parallel world "; }
12095     };
12097     int main()
12098     {
12099         std::thread t1{f};      // f() executes in separate thread
12100         std::thread t2{F()};    // F()() executes in separate thread
12101     }  // spot the bugs
12103 ##### Example
12105     void f() { std::cout << "Hello "; }
12107     struct F {
12108         void operator()() { std::cout << "parallel world "; }
12109     };
12111     int main()
12112     {
12113         std::thread t1{f};      // f() executes in separate thread
12114         std::thread t2{F()};    // F()() executes in separate thread
12116         t1.join();
12117         t2.join();
12118     }  // one bad bug left
12120 ??? Is `cout` synchronized?
12122 ##### Enforcement
12124 * Flag `join`s for `raii_thread`s ???
12125 * Flag `detach`s for `detached_thread`s
12128 ### <a name="RRconc-pass"></a>CP.30: Do not pass pointers to local variables to non-`raii_thread`s
12130 ##### Reason
12132 In general, you cannot know whether a non-`raii_thread` will outlive the scope of the variables, so that those pointers will become invalid.
12134 ##### Example, bad
12136     void use()
12137     {
12138         int x = 7;
12139         thread t0 { f, ref(x) };
12140         // ...
12141         t0.detach();
12142     }
12144 The `detach` may not be so easy to spot.
12145 Use a `raii_thread` or don't pass the pointer.
12147 ##### Example, bad
12149     ??? put pointer to a local on a queue that is read by a longer-lived thread ???
12151 ##### Enforcement
12153 Flag pointers to locals passed in the constructor of a plain `thread`.
12156 ### <a name="Rconc-data-by-value"></a>CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer
12158 ##### Reason
12160 Copying a small amount of data is cheaper to copy and access than to share it using some locking mechanism.
12161 Copying naturally gives unique ownership (simplifies code) and eliminates the possibility of data races.
12163 ##### Note
12165 Defining "small amount" precisely is impossible.
12167 ##### Example
12169     string modify1(string);
12170     void modify2(shared_ptr<string>);
12172     void fct(string& s)
12173     {
12174         auto res = async(modify1, s);
12175         async(modify2, &s);
12176     }
12178 The call of `modify1` involves copying two `string` values; the call of `modify2` does not.
12179 On the other hand, the implementation of `modify1` is exactly as we would have written it for single-threaded code,
12180 whereas the implementation of `modify2` will need some form of locking to avoid data races.
12181 If the string is short (say 10 characters), the call of `modify1` can be surprisingly fast;
12182 essentially all the cost is in the `thread` switch. If the string is long (say 1,000,000 characters), copying it twice
12183 is probably not a good idea.
12185 Note that this argument has nothing to do with `sync` as such. It applies equally to considerations about whether to use
12186 message passing or shared memory.
12188 ##### Enforcement
12193 ### <a name="Rconc-shared"></a>[CP.32: To share ownership between unrelated `thread`s use `shared_ptr`
12195 ##### Reason
12197 If threads are unrelated (that is, not known to be in the same scope or one within the lifetime of the other)
12198 and they need to share free store memory that needs to be deleted, a `shared_ptr` (or equivalent) is the only
12199 safe way to ensure proper deletion.
12201 ##### Example
12203     ???
12205 ##### Note
12207 * A static object (e.g. a global) can be shared because it is not owned in the sense that some thread is responsible for it's deletion.
12208 * An object on free store that is never to be deleted can be shared.
12209 * An object owned by one thread can be safely shared with another as long as that second thread doesn't outlive the owner.
12211 ##### Enforcement
12216 ### <a name="Rconc-switch"></a>CP.40: Minimize context switching
12218 ##### Reason
12220 Context switches are expensive.
12222 ##### Example
12224     ???
12226 ##### Enforcement
12231 ### <a name="Rconc-create"></a>CP.41: Minimize thread creation and destruction
12233 ##### Reason
12235 Thread creation is expensive.
12237 ##### Example
12239     void worker(Message m)
12240     {
12241         // process
12242     }
12244     void master(istream& is)
12245     {
12246         for (Message m; is >> m; )
12247             run_list.push_back(new thread(worker, m));
12248     }
12250 This spawns a `thread` per message, and the `run_list` is presumably managed to destroy those tasks once they are finished.
12252 Instead, we could have a set of pre-created worker threads processing the messages
12254     Sync_queue<Message> work;
12256     void master(istream& is)
12257     {
12258         for (Message m; is >> m; )
12259             work.put(m);
12260     }
12262     void worker()
12263     {
12264         for (Message m; m = work.get(); ) {
12265             // process
12266         }
12267     }
12269     void workers()  // set up worker threads (specifically 4 worker threads)
12270     {
12271         raii_thread w1 {worker};
12272         raii_thread w2 {worker};
12273         raii_thread w3 {worker};
12274         raii_thread w4 {worker};
12275     }
12277 ##### Note
12279 If your system has a good thread pool, use it.
12280 If your system has a good message queue, use it.
12282 ##### Enforcement
12287 ### <a name="Rconc-wait"></a>CP.42: Don't `wait` without a condition
12289 ##### Reason
12291 A `wait` without a condition can miss a wakeup or wake up simply to find that there is no work to do.
12293 ##### Example, bad
12295     std::condition_variable cv;
12296     std::mutex mx;
12298     void thread1()
12299     {
12300         while (true) {
12301             // do some work ...
12302             std::unique_lock<std::mutex> lock(mx);
12303             cv.notify_one();    // wake other thread
12304         }
12305     }
12307     void thread2()
12308     {
12309         while (true) {
12310             std::unique_lock<std::mutex> lock(mx);
12311             cv.wait(lock);    // might block forever
12312             // do work ...
12313         }
12314     }
12316 Here, if some other `thread` consumes `thread1`'s notification, `thread2` can wait forever.
12318 ##### Example
12320     template<typename T>
12321     class Sync_queue {
12322     public:
12323         void put(const T& val);
12324         void put(T&& val);
12325         void get(T& val);
12326     private:
12327         mutex mtx;
12328         condition_variable cond;    // this controls access
12329         list<T> q;
12330     };
12332     template<typename T>
12333     void Sync_queue<T>::put(const T& val)
12334     {
12335         lock_guard<mutex> lck(mtx);
12336         q.push_back(val);
12337         cond.notify_one();
12338     }
12340     template<typename T>
12341     void Sync_queue<T>::get(T& val)
12342     {
12343         unique_lock<mutex> lck(mtx);
12344         cond.wait(lck, [this]{ return !q.empty(); });    // prevent spurious wakeup
12345         val = q.front();
12346         q.pop_front();
12347     }
12349 Now if the queue is empty when a thread executing `get()` wakes up (e.g., because another thread has gotten to `get()` before it),
12350 it will immediately go back to sleep, waiting.
12352 ##### Enforcement
12354 Flag all `wait`s without conditions.
12357 ### <a name="Rconc-time"></a>CP.43: Minimize time spent in a critical section
12359 ##### Reason
12361 The less time is spent with a `mutex` taken, the less chance that another `thread` has to wait,
12362 and `thread` suspension and resumption are expensive.
12364 ##### Example
12366     void do_something() // bad
12367     {
12368         unique_lock<mutex> lck(my_lock);
12369         do0();  // preparation: does not need lock
12370         do1();  // transaction: needs locking
12371         do2();  // cleanup: does not need locking
12372     }
12374 Here, we are holding the lock for longer than necessary:
12375 We should not have taken the lock before we needed it and should have released it again before starting the cleanup.
12376 We could rewrite this to
12378     void do_something() // bad
12379     {
12380         do0();  // preparation: does not need lock
12381         my_lock.lock();
12382         do1();  // transaction: needs locking
12383         my_lock.unlock();
12384         do2();  // cleanup: does not need locking
12385     }
12387 But that compromises safety and violates the [use RAII](#Rconc-raii) rule.
12388 Instead, add a block for the critical section:
12390     void do_something() // OK
12391     {
12392         do0();  // preparation: does not need lock
12393         {
12394             unique_lock<mutex> lck(my_lock);
12395             do1();  // transaction: needs locking
12396         }
12397         do2();  // cleanup: does not need locking
12398     }
12400 ##### Enforcement
12402 Impossible in general.
12403 Flag "naked" `lock()` and `unlock()`.
12406 ### <a name="Rconc-name"></a>CP.44: Remember to name your `lock_guard`s and `unique_lock`s
12408 ##### Reason
12410 An unnamed local objects is a temporary that immediately goes out of scope.
12412 ##### Example
12414     unique_lock<mutex>(m1);
12415     lock_guard<mutex> {m2};
12416     lock(m1, m2);
12418 This looks innocent enough, but it isn't.
12420 ##### Enforcement
12422 Flag all unnamed `lock_guard`s and `unique_lock`s.
12426 ### <a name="Rconc-mutex"></a>P.50: Define a `mutex` together with the data it guards
12428 ##### Reason
12430 It should be obvious to a reader that the data is to be guarded and how.
12432 ##### Example
12434     struct Record {
12435         std::mutex m;   // take this mutex before accessing other members
12436         // ...
12437     };
12439 ##### Enforcement
12441 ??? Possible?
12444 ## <a name="SScp-par"></a>CP.par: Parallelism
12446 By "parallelism" we refer to performing a task (more or less) simultaneously ("in parallel with") on many data items.
12448 Parallelism rule summary:
12450 * ???
12451 * ???
12452 * Where appropriate, prefer the standard-library parallel algorithms
12453 * Use algorithms that are designed for parallelism, not algorithms with unnecessary dependency on linear evaluation
12457 ## <a name="SScp-mess"></a>CP.mess: Message passing
12459 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.
12460 Most people shouldn't work at this level: it's error-prone and development is slow.
12461 If possible, use a higher level facility: messaging libraries, parallel algorithms, and vectorization.
12462 This section looks at passing messages so that a programmer doesn't have to do explicit synchronization.
12464 Message passing rules summary:
12466 * [CP.60: Use a `future` to return a value from a concurrent task](#Rconc-future)
12467 * [CP.61: Use a `async()` to spawn a concurrent task](#Rconc-async)
12468 * message queues
12469 * messaging libraries
12471 ???? should there be a "use X rather than `std::async`" where X is something that would use a better specified thread pool?
12473 ??? 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?
12476 ### <a name="Rconc-future"></a>CP.60: Use a `future` to return a value from a concurrent task
12478 ##### Reason
12480 A `future` preserves the usual function call return semantics for asynchronous tasks.
12481 The is no explicit locking and both correct (value) return and error (exception) return are handled simply.
12483 ##### Example
12485     ???
12487 ##### Note
12491 ##### Enforcement
12495 ### <a name="Rconc-async"></a>CP.61: Use a `async()` to spawn a concurrent task
12497 ##### Reason
12499 A `future` preserves the usual function call return semantics for asynchronous tasks.
12500 The is no explicit locking and both correct (value) return and error (exception) return are handled simply.
12502 ##### Example
12504     ???
12506 ##### Note
12508 Unfortunately, `async()` is not perfect.
12509 For example, there is no guarantee that a thread pool is used to minimize thread construction.
12510 In fact, most current `async()` implementations don't.
12511 However, `async()` is simple and logically correct so until something better comes along
12512 and unless you really need to optimize for many asynchronous tasks, stick with `async()`.
12514 ##### Enforcement
12519 ## <a name="SScp-vec"></a>CP.vec: Vectorization
12521 Vectorization is a technique for executing a number of tasks concurrently without introducing explicit synchronization.
12522 An operation is simply applied to elements of a data structure (a vector, an array, etc.) in parallel.
12523 Vectorization has the interesting property of often requiring no non-local changes to a program.
12524 However, vectorization works best with simple data structures and with algorithms specifically crafted to enable it.
12526 Vectorization rule summary:
12528 * ???
12529 * ???
12531 ## <a name="SScp-free"></a>CP.free: Lock-free programming
12533 Synchronization using `mutex`es and `condition_variable`s can be relatively expensive.
12534 Furthermore, it can lead to deadlock.
12535 For performance and to eliminate the possibility of deadlock, we sometimes have to use the tricky low-level "lock-free" facilities
12536 that rely on briefly gaining exclusive ("atomic") access to memory.
12537 Lock free programming is also used to implement higher-level concurrency mechanisms, such as `thread`s and `mutex`es.
12539 Lock-free programming rule summary:
12541 * [CP.100: Don't use lock-free programming unless you absolutely have to](#Rconc-lockfree)
12542 * [CP.101: Distrust your hardware/compiler combination](#Rconc-distrust)
12543 * [CP.102: Carefully study the literature](#Rconc-literature)
12544 * how/when to use atomics
12545 * avoid starvation
12546 * use a lock free data structure rather than hand-crafting specific lock-free access
12547 * [CP.110: Do not write your own double-checked locking for initialization](#Rconc-double)
12548 * [CP.111: Use a conventional pattern if you really need double-checked locking](#Rconc-double-pattern)
12549 * how/when to compare and swap
12552 ### <a name="Rconc-lockfree"></a>CP.100: Don't use lock-free programming unless you absolutely have to
12554 ##### Reason
12556 It's error-prone and requires expert level knowledge of language features, machine architecture, and data structures.
12558 ##### Example, bad
12560     extern atomic<Link*> head;        // the shared head of a linked list
12562     Link* nh = new Link(data, nullptr);    // make a link ready for insertion
12563     Link* h = head.load();                 // read the shared head of the list
12565     do {
12566         if (h->data <= data) break;        // if so, insert elsewhere
12567         nh->next = h;                      // next element is the previous head
12568     } while (!head.compare_exchange_weak(h, nh));    // write nh to head or to h
12570 Spot the bug.
12571 It would be really hard to find through testing.
12572 Read up on the ABA problem.
12574 ##### Exception
12576 [Atomic variables](#???) can be used simply and safely.
12578 ##### Note
12580 Higher-level concurrency mechanisms, such as `thread`s and `mutex`es are implemented using lock-free programming.
12582 **Alternative**: Use lock-free data structures implemented by others as part of some library.
12585 ### <a name="Rconc-distrust"></a>CP.101: Distrust your hardware/compiler combination
12587 ##### Reason
12589 The low-level hardware interfaces used by lock-free programming are among the hardest to implement well and among
12590 the areas where the most subtle portability problems occur.
12591 If you are doing lock-free programming for performance, you need to check for regressions.
12593 ##### Note
12595 Instruction reordering (static and dynamic) makes it hard for us to think effectively at this level (especially if you use relaxed memory models).
12596 Experience, (semi)formal models and model checking can be useful.
12597 Testing - often to an extreme extent - is essential.
12598 "Don't fly too close to the sun."
12600 ##### Enforcement
12602 Have strong rules for re-testing in place that covers any change in hardware, operating system, compiler, and libraries.
12605 ### <a name="Rconc-literature"></a>CP.102: Carefully study the literature
12607 ##### Reason
12609 With the exception of atomics and a few use standard patterns, lock-free programming is really an expert-only topic.
12610 Become an expert before shipping lock-free code for others to use.
12612 ##### References
12614 * Anthony Williams: C++ concurrency in action. Manning Publications.
12615 * Boehm, Adve, You Don't Know Jack About Shared Variables or Memory Models , Communications of the ACM, Feb 2012.
12616 * Boehm, "Threads Basics", HPL TR 2009-259.
12617 * Adve, Boehm, "Memory Models: A Case for Rethinking Parallel Languages and Hardware", Communications of the ACM, August 2010.
12618 * Boehm, Adve, "Foundations of the C++ Concurrency Memory Model", PLDI 08.
12619 * Mark Batty, Scott Owens, Susmit Sarkar, Peter Sewell, and Tjark Weber, "Mathematizing C++ Concurrency", POPL 2011.
12620 * 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.
12621 * Damian Dechev and Bjarne Stroustrup: Scalable Non-blocking Concurrent Objects for Mission Critical Code. ACM OOPSLA'09. October 2009
12622 * 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.
12625 ### <a name="Rconc-double"></a>CP.110: Do not write your own double-checked locking for initialization
12627 ##### Reason
12629 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.
12631 ##### Example
12633 Example with std::call_once.
12635     void f()
12636     {
12637         static std::once_flag my_once_flag;
12638         std::call_once(my_once_flag, []()
12639         {
12640             // do this only once
12641         });
12642         // ...
12643     }
12645 Example with thread-safe static local variables of C++11.
12647     void f()
12648     {
12649         // Assuming the compiler is compliant with C++11
12650         static My_class my_object; // Constructor called only once
12651         // ...
12652     }
12653     
12654     class My_class
12655     {
12656     public:
12657         My_class()
12658         {
12659             // ...
12660         }
12661     };
12663 ##### Enforcement
12665 ??? Is it possible to detect the idiom?
12668 ### <a name="Rconc-double-pattern"></a>CP.111: Use a conventional pattern if you really need double-checked locking
12670 ##### Reason
12672 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.
12674 ##### Example, bad
12676 Even if the following example works correctly on most hardware platforms, it is not guaranteed to work by the C++ standard. The x_init.load(memory_order_relaxed) call may see a value from outside of the lock guard. 
12678     atomic<bool> x_init;
12680     if (!x_init.load(memory_order_acquire)) {
12681         lock_guard<mutex> lck(x_mutex);
12682         if (!x_init.load(memory_order_relaxed)) {
12683             // ... initialize x ...
12684             x_init.store(true, memory_order_release);
12685         }
12686     }
12688 ##### Example, good
12690 One of the conventional patterns is below.
12692     std::atomic<int> state;
12693     
12694     // If state == SOME_ACTION_NEEDED maybe an action is needed, maybe not, we need to
12695     // check again in a lock. However, if state != SOME_ACTION_NEEDED, then we can be
12696     // sure that an action is not needed. This is the basic assumption of double-checked
12697     // locking.
12698     
12699     if (state == SOME_ACTION_NEEDED)
12700     {
12701         std::lock_guard<std::mutex> lock(mutex);
12702         if (state == SOME_ACTION_NEEDED)
12703         {
12704             // do something
12705             state = NO_ACTION_NEEDED;
12706         }
12707     }
12709 In the example above (state == SOME_ACTION_NEEDED) could be any condition. It doesn't necessarily needs to be equality comparison. For example, it could as well be (size > MIN_SIZE_TO_TAKE_ACTION).
12711 ##### Enforcement
12713 ??? Is it possible to detect the idiom?
12716 ## <a name="SScp-etc"></a>CP.etc: Etc. concurrency rules
12718 These rules defy simple categorization:
12720 * [CP.200: Use `volatile` only to talk to non-C++ memory](#Rconc-volatile2)
12721 * [CP.201: ??? Signals](#Rconc-signal)
12723 ### <a name="Rconc-volatile2"></a>CP.200: Use `volatile` only to talk to non-C++ memory
12725 ##### Reason
12727 `volatile` is used to refer to objects that are shared with "non-C++" code or hardware that does not follow the C++ memory model.
12729 ##### Example
12731     const volatile long clock;
12733 This describes a register constantly updated by a clock circuit.
12734 `clock` is `volatile` because its value will change without any action from the C++ program that uses it.
12735 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:
12737     long t1 = clock;
12738     // ... no use of clock here ...
12739     long t2 = clock;
12741 `clock` is `const` because the program should not try to write to `clock`.
12743 ##### Note
12745 Unless you are writing the lowest level code manipulating hardware directly, consider `volatile` an esoteric feature that is best avoided.
12747 ##### Example
12749 Usually C++ code receives `volatile` memory that is owned Elsewhere (hardware or another language):
12751     int volatile* vi = get_hardware_memory_location();
12752         // note: we get a pointer to someone else's memory here
12753         // volatile says "treat this with extra respect"
12755 Sometimes C++ code allocates the `volatile` memory and shares it with "elsewhere" (hardware or another language) by deliberately escaping a pointer:
12757     static volatile long vl;
12758     please_use_this(&vl);   // escape a reference to this to "elsewhere" (not C++)
12760 ##### Example; bad
12762 `volatile` local variables are nearly always wrong -- how can they be shared with other languages or hardware if they're ephemeral?
12763 The same applies almost as strongly to member variables, for the same reason.
12765     void f() {
12766         volatile int i = 0; // bad, volatile local variable
12767         // etc.
12768     }
12770     class My_type {
12771         volatile int i = 0; // suspicious, volatile member variable
12772         // etc.
12773     };
12775 ##### Note
12777 In C++, unlike in some other languages, `volatile` has [nothing to do with synchronization](#Rconc-volatile).
12779 ##### Enforcement
12781 * Flag `volatile T` local and member variables; almost certainly you intended to use `atomic<T>` instead.
12782 * ???
12784 ### <a name="Rconc-signal"></a>CP.201: ??? Signals
12786 ???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")
12789 # <a name="S-errors"></a>E: Error handling
12791 Error handling involves:
12793 * Detecting an error
12794 * Transmitting information about an error to some handler code
12795 * Preserve the state of a program in a valid state
12796 * Avoid resource leaks
12798 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.
12800 The rules are designed to help avoid several kinds of errors:
12802 * Type violations (e.g., misuse of `union`s and casts)
12803 * Resource leaks (including memory leaks)
12804 * Bounds errors
12805 * Lifetime errors (e.g., accessing an object after is has been `delete`d)
12806 * Complexity errors (logical errors make likely by overly complex expression of ideas)
12807 * Interface errors (e.g., an unexpected value is passed through an interface)
12809 Error-handling rule summary:
12811 * [E.1: Develop an error-handling strategy early in a design](#Re-design)
12812 * [E.2: Throw an exception to signal that a function can't perform its assigned task](#Re-throw)
12813 * [E.3: Use exceptions for error handling only](#Re-errors)
12814 * [E.4: Design your error-handling strategy around invariants](#Re-design-invariants)
12815 * [E.5: Let a constructor establish an invariant, and throw if it cannot](#Re-invariant)
12816 * [E.6: Use RAII to prevent leaks](#Re-raii)
12817 * [E.7: State your preconditions](#Re-precondition)
12818 * [E.8: State your postconditions](#Re-postcondition)
12820 * [E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable](#Re-noexcept)
12821 * [E.13: Never throw while being the direct owner of an object](#Re-never-throw)
12822 * [E.14: Use purpose-designed user-defined types as exceptions (not built-in types)](#Re-exception-types)
12823 * [E.15: Catch exceptions from a hierarchy by reference](#Re-exception-ref)
12824 * [E.16: Destructors, deallocation, and `swap` must never fail](#Re-never-fail)
12825 * [E.17: Don't try to catch every exception in every function](#Re-not-always)
12826 * [E.18: Minimize the use of explicit `try`/`catch`](#Re-catch)
12827 * [E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available](#Re-finally)
12829 * [E.25: If you can't throw exceptions, simulate RAII for resource management](#Re-no-throw-raii)
12830 * [E.26: If you can't throw exceptions, consider failing fast](#Re-no-throw-crash)
12831 * [E.27: If you can't throw exceptions, use error codes systematically](#Re-no-throw-codes)
12832 * [E.28: Avoid error handling based on global state (e.g. `errno`)](#Re-no-throw)
12834 ### <a name="Re-design"></a>E.1: Develop an error-handling strategy early in a design
12836 ##### Reason
12838 A consistent and complete strategy for handling errors and resource leaks is hard to retrofit into a system.
12840 ### <a name="Re-throw"></a>E.2: Throw an exception to signal that a function can't perform its assigned task
12842 ##### Reason
12844 To make error handling systematic, robust, and non-repetitive.
12846 ##### Example
12848     struct Foo {
12849         vector<Thing> v;
12850         File_handle f;
12851         string s;
12852     };
12854     void use()
12855     {
12856         Foo bar {{Thing{1}, Thing{2}, Thing{monkey}}, {"my_file", "r"}, "Here we go!"};
12857         // ...
12858     }
12860 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.
12861 In each case, they throw an exception for `use()`'s caller to handle.
12862 If `use()` could handle the failure to construct `bar` it can take control using `try`/`catch`.
12863 In either case, `Foo`'s constructor correctly destroys constructed members before passing control to whatever tried to create a `Foo`.
12864 Note that there is no return value that could contain an error code.
12866 The `File_handle` constructor might be defined like this:
12868     File_handle::File_handle(const string& name, const string& mode)
12869         :f{fopen(name.c_str(), mode.c_str())}
12870     {
12871         if (!f)
12872             throw runtime_error{"File_handle: could not open " + name + " as " + mode};
12873     }
12875 ##### Note
12877 It is often said that exceptions are meant to signal exceptional events and failures.
12878 However, that's a bit circular because "what is exceptional?"
12879 Examples:
12881 * A precondition that cannot be met
12882 * A constructor that cannot construct an object (failure to establish its class's [invariant](#Rc-struct))
12883 * An out-of-range error (e.g., `v[v.size()] = 7`)
12884 * Inability to acquire a resource (e.g., the network is down)
12886 In contrast, termination of an ordinary loop is not exceptional.
12887 Unless the loop was meant to be infinite, termination is normal and expected.
12889 ##### Note
12891 Don't use a `throw` as simply an alternative way of returning a value from a function.
12893 ##### Exception
12895 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`.
12897 **See also**: [RAII](#Re-raii)
12899 **See also**: [discussion](#Sd-noexcept)
12901 ##### Note
12903 Before deciding that you cannot afford or don't like exception-based error handling, have a look at the [alternatives](#Re-no-throw-raii);
12904 they have their own complexities and problems.
12905 Also, as far as possible, measure before making claims about efficiency.
12907 ### <a name="Re-errors"></a>E.3: Use exceptions for error handling only
12909 ##### Reason
12911 To keep error handling separated from "ordinary code."
12912 C++ implementations tend to be optimized based on the assumption that exceptions are rare.
12914 ##### Example, don't
12916     // don't: exception not used for error handling
12917     int find_index(vector<string>& vec, const string& x)
12918     {
12919         try {
12920             for (int i = 0; i < vec.size(); ++i)
12921                 if (vec[i] == x) throw i;  // found x
12922         } catch (int i) {
12923             return i;
12924         }
12925         return -1;   // not found
12926     }
12928 This is more complicated and most likely runs much slower than the obvious alternative.
12929 There is nothing exceptional about finding a value in a `vector`.
12931 ##### Enforcement
12933 Would need to be heuristic.
12934 Look for exception values "leaked" out of `catch` clauses.
12936 ### <a name="Re-design-invariants"></a>E.4: Design your error-handling strategy around invariants
12938 ##### Reason
12940 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.
12942 ##### Note
12944 An [invariant](#Rc-struct) is logical condition for the members of an object that a constructor must establish for the public member functions to assume.
12946 ##### Enforcement
12950 ### <a name="Re-invariant"></a>E.5: Let a constructor establish an invariant, and throw if it cannot
12952 ##### Reason
12954 Leaving an object without its invariant established is asking for trouble.
12955 Not all member functions can be called.
12957 ##### Example
12959     class Vector {  // very simplified vector of doubles
12960         // if elem != nullptr then elem points to sz doubles
12961     public:
12962         Vector() : elem{nullptr}, sz{0}{}
12963         Vector(int s) : elem{new double}, sz{s} { /* initialize elements */ }
12964         ~Vector() { delete elem; }
12965         double& operator[](int s) { return elem[s]; }
12966         // ...
12967     private:
12968         owner<double*> elem;
12969         int sz;
12970     };
12972 The class invariant - here stated as a comment - is established by the constructors.
12973 `new` throws if it cannot allocate the required memory.
12974 The operators, notably the subscript operator, relies on the invariant.
12976 **See also**: [If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
12978 ##### Enforcement
12980 Flag classes with `private` state without a constructor (public, protected, or private).
12982 ### <a name="Re-raii"></a>E.6: Use RAII to prevent leaks
12984 ##### Reason
12986 Leaks are typically unacceptable. RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks.
12988 ##### Example
12990     void f1(int i)   // Bad: possibly leak
12991     {
12992         int* p = new int[12];
12993         // ...
12994         if (i < 17) throw Bad {"in f()", i};
12995         // ...
12996     }
12998 We could carefully release the resource before the throw:
13000     void f2(int i)   // Clumsy: explicit release
13001     {
13002         int* p = new int[12];
13003         // ...
13004         if (i < 17) {
13005             delete[] p;
13006             throw Bad {"in f()", i};
13007         }
13008         // ...
13009     }
13011 This is verbose. In larger code with multiple possible `throw`s explicit releases become repetitive and error-prone.
13013     void f3(int i)   // OK: resource management done by a handle
13014     {
13015         auto p = make_unique<int[]>(12);
13016         // ...
13017         if (i < 17) throw Bad {"in f()", i};
13018         // ...
13019     }
13021 Note that this works even when the `throw` is implicit because it happened in a called function:
13023     void f4(int i)   // OK: resource management done by a handle
13024     {
13025         auto p = make_unique<int[]>(12);
13026         // ...
13027         helper(i);   // may throw
13028         // ...
13029     }
13031 Unless you really need pointer semantics, use a local resource object:
13033     void f5(int i)   // OK: resource management done by local object
13034     {
13035         vector<int> v(12);
13036         // ...
13037         helper(i);   // may throw
13038         // ...
13039     }
13041 ##### Note
13043 If there is no obvious resource handle, cleanup actions can be represented by a [`final_action` object](#Re-finally)
13045 ##### Note
13047 But what do we do if we are writing a program where exceptions cannot be used?
13048 First challenge that assumption; there are many anti-exceptions myths around.
13049 We know of only a few good reasons:
13051 * We are on a system so small that the exception support would eat up most of our 2K memory.
13052 * 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.
13053 * We are in a system with tons of legacy code using lots of pointers in difficult-to-understand ways
13054   (in particular without a recognizable ownership strategy) so that exceptions could cause leaks.
13055 * Our implementation of the C++ exception mechanisms is unreasonably poor
13056 (slow, memory consuming, failing to work correctly for dynamically linked libraries, etc.).
13057 Complain to your implementation purveyor; if no user complains, no improvement will happen.
13058 * We get fired if we challenge our manager's ancient wisdom.
13060 Only the first of these reasons is fundamental, so whenever possible, use exceptions to implement RAII, or design your RAII objects to never fail.
13061 When exceptions cannot be used, simulate RAII.
13062 That is, systematically check that objects are valid after construction and still release all resources in the destructor.
13063 One strategy is to add a `valid()` operation to every resource handle:
13065     void f()
13066     {
13067         vector<string> vs(100);   // not std::vector: valid() added
13068         if (!vs.valid()) {
13069             // handle error or exit
13070         }
13072         ifstream fs("foo");   // not std::ifstream: valid() added
13073         if (!fs.valid()) {
13074             // handle error or exit
13075         }
13077         // ...
13078     } // destructors clean up as usual
13080 Obviously, this increases the size of the code, doesn't allow for implicit propagation of "exceptions" (`valid()` checks), and `valid()` checks can be forgotten.
13081 Prefer to use exceptions.
13083 **See also**: [Use of `noexcept`](#Se-noexcept).
13085 ##### Enforcement
13089 ### <a name="Re-precondition"></a>E.7: State your preconditions
13091 ##### Reason
13093 To avoid interface errors.
13095 **See also**: [precondition rule](#Ri-pre).
13097 ### <a name="Re-postcondition"></a>E.8: State your postconditions
13099 ##### Reason
13101 To avoid interface errors.
13103 **See also**: [postcondition rule](#Ri-post).
13105 ### <a name="Re-noexcept"></a>E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable
13107 ##### Reason
13109 To make error handling systematic, robust, and efficient.
13111 ##### Example
13113     double compute(double d) noexcept
13114     {
13115         return log(sqrt(d <= 0 ? 1 : d));
13116     }
13118 Here, we know that `compute` will not throw because it is composed out of operations that don't throw.
13119 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`.
13121 ##### Note
13123 Many standard library functions are `noexcept` including all the standard library functions "inherited" from the C standard library.
13125 ##### Example
13127     vector<double> munge(const vector<double>& v) noexcept
13128     {
13129         vector<double> v2(v.size());
13130         // ... do something ...
13131     }
13133 The `noexcept` here states that I am not willing or able to handle the situation where I cannot construct the local `vector`. 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.
13135 **See also**: [discussion](#Sd-noexcept).
13137 ### <a name="Re-never-throw"></a>E.13: Never throw while being the direct owner of an object
13139 ##### Reason
13141 That would be a leak.
13143 ##### Example
13145     void leak(int x)   // don't: may leak
13146     {
13147         auto p = new int{7};
13148         if (x < 0) throw Get_me_out_of_here{};  // may leak *p
13149         // ...
13150         delete p;   // we may never get here
13151     }
13153 One way of avoiding such problems is to use resource handles consistently:
13155     void no_leak(int x)
13156     {
13157         auto p = make_unique<int>(7);
13158         if (x < 0) throw Get_me_out_of_here{};  // will delete *p if necessary
13159         // ...
13160         // no need for delete p
13161     }
13163 Another solution (often better) would be to use a local variable to eliminate explicit use of pointers:
13165     void no_leak_simplified(int x)
13166     {
13167         vector<int> v(7);
13168         // ...
13169     }
13171 **See also**: ???resource rule ???
13173 ### <a name="Re-exception-types"></a>E.14: Use purpose-designed user-defined types as exceptions (not built-in types)
13175 ##### Reason
13177 A user-defined type is unlikely to clash with other people's exceptions.
13179 ##### Example
13181     void my_code()
13182     {
13183         // ...
13184         throw Moonphase_error{};
13185         // ...
13186     }
13188     void your_code()
13189     {
13190         try {
13191             // ...
13192             my_code();
13193             // ...
13194         }
13195         catch(Bufferpool_exhausted) {
13196             // ...
13197         }
13198     }
13200 ##### Example, don't
13202     void my_code()     // Don't
13203     {
13204         // ...
13205         throw 7;       // 7 means "moon in the 4th quarter"
13206         // ...
13207     }
13209     void your_code()   // Don't
13210     {
13211         try {
13212             // ...
13213             my_code();
13214             // ...
13215         }
13216         catch(int i) {  // i == 7 means "input buffer too small"
13217             // ...
13218         }
13219     }
13221 ##### Note
13223 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.
13225 ##### Example, don't
13227     void my_code()   // Don't
13228     {
13229         // ...
13230         throw runtime_error{"moon in the 4th quarter"};
13231         // ...
13232     }
13234     void your_code()   // Don't
13235     {
13236         try {
13237             // ...
13238             my_code();
13239             // ...
13240         }
13241         catch(runtime_error) {   // runtime_error means "input buffer too small"
13242             // ...
13243         }
13244     }
13246 **See also**: [Discussion](#Sd-???)
13248 ##### Enforcement
13250 Catch `throw` and `catch` of a built-in type. Maybe warn about `throw` and `catch` using an standard-library `exception` type. Obviously, exceptions derived from the `std::exception` hierarchy is fine.
13252 ### <a name="Re-exception-ref"></a>E.15: Catch exceptions from a hierarchy by reference
13254 ##### Reason
13256 To prevent slicing.
13258 ##### Example
13260     void f()
13261     try {
13262         // ...
13263     }
13264     catch (exception e) {   // don't: may slice
13265         // ...
13266     }
13268 Instead, use:
13270     catch (exception& e) { /* ... */ }
13272 ##### Enforcement
13274 Flag by-value exceptions if their types are part of a hierarchy (could require whole-program analysis to be perfect).
13276 ### <a name="Re-never-fail"></a>E.16: Destructors, deallocation, and `swap` must never fail
13278 ##### Reason
13280 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.
13282 ##### Example, don't
13284     class Connection {
13285         // ...
13286     public:
13287         ~Connection()   // Don't: very bad destructor
13288         {
13289             if (cannot_disconnect()) throw I_give_up{information};
13290             // ...
13291         }
13292     };
13294 ##### Note
13296 Many have tried to write reliable code violating this rule for examples, such as a network connection that "refuses to close".
13297 To the best of our knowledge nobody has found a general way of doing this.
13298 Occasionally, for very specific examples, you can get away with setting some state for future cleanup.
13299 For example, we might put a socket that does not want to close on a "bad socket" list,
13300 to be examined by a regular sweep of the system state.
13301 Every example we have seen of this is error-prone, specialized, and often buggy.
13303 ##### Note
13305 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.
13307 ##### Note
13309 Deallocation functions, including `operator delete`, must be `noexcept`. `swap` functions must be `noexcept`.
13310 Most destructors are implicitly `noexcept` by default.
13311 Also, [make move operations `noexcept`](##Rc-move-noexcept).
13313 ##### Enforcement
13315 Catch destructors, deallocation operations, and `swap`s that `throw`.
13316 Catch such operations that are not `noexcept`.
13318 **See also**: [discussion](#Sd-never-fail)
13320 ### <a name="Re-not-always"></a>E.17: Don't try to catch every exception in every function
13322 ##### Reason
13324 Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste.
13325 Let an exception propagate until it reaches a function that can handle it.
13326 Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii).
13328 ##### Example, don't
13330     void f()   // bad
13331     {
13332         try {
13333             // ...
13334         }
13335         catch (...) {
13336             // no action
13337             throw;   // propagate exception
13338         }
13339     }
13341 ##### Enforcement
13343 * Flag nested try-blocks.
13344 * Flag source code files with a too high ratio of try-blocks to functions. (??? Problem: define "too high")
13346 ### <a name="Re-catch"></a>E.18: Minimize the use of explicit `try`/`catch`
13348 ##### Reason
13350  `try`/`catch` is verbose and non-trivial uses error-prone.
13351  `try`/`catch` can be a sign of unsystematic and/or low-level resource management or error handling.
13353 ##### Example, Bad
13355     void f(zstring s)
13356     {
13357         Gadget* p;
13358         try {
13359             p = new Gadget(s);
13360             // ...
13361             delete p;
13362         }
13363         catch (Gadget_construction_failure) {
13364             delete p;
13365             throw;
13366         }
13367     }
13369 This code is messy.
13370 There could be a leak from the naked pointer in the `try` block.
13371 Not all exceptions are handled.
13372 `deleting` an object that failed to construct is almost certainly a mistake.
13373 Better:
13375     void f2(zstring s)
13376     {
13377         Gadget g {s};
13378     }
13380 ##### Alternatives
13382 * proper resource handles and [RAII](#Re-raii)
13383 * [`finally`](#Re-finally)
13385 ##### Enforcement
13387 ??? hard, needs a heuristic
13389 ### <a name="Re-finally"></a>E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available
13391 ##### Reason
13393 `finally` is less verbose and harder to get wrong than `try`/`catch`.
13395 ##### Example
13397     void f(int n)
13398     {
13399         void* p = malloc(1, n);
13400         auto _ = finally([p] { free(p); });
13401         // ...
13402     }
13404 ##### Note
13406 `finally` is not as messy as `try`/`catch`, but it is still ad-hoc.
13407 Prefer [proper resource management objects](#Re-raii).
13409 ##### Note
13411 Use of `finally` is a systematic and reasonably clean alternative to the old [`goto exit;` technique](##Re-no-throw-codes)
13412 for dealing with cleanup where resource management is not systematic.
13414 ##### Enforcement
13416 Heuristic: Detect `goto exit;`
13418 ### <a name="Re-no-throw-raii"></a>E.25: If you can't throw exceptions, simulate RAII for resource management
13420 ##### Reason
13422 Even without exceptions, [RAII](#Re-raii) is usually the best and most systematic way of dealing with resources.
13424 ##### Note
13426 Error handling using exceptions is the only complete and systematic way of handling non-local errors in C++.
13427 In particular, non-intrusively signaling failure to construct an object requires an exception.
13428 Signaling errors in a way that cannot be ignored requires exceptions.
13429 If you can't use exceptions, simulate their use as best you can.
13431 A lot of fear of exceptions is misguided.
13432 When used for exceptional circumstances in code that is not littered with pointers and complicated control structures,
13433 exception handling is almost always affordable (in time and space) and almost always leads to better code.
13434 This, of course, assumes a good implementation of the exception handling mechanisms, which is not available on all systems.
13435 There are also cases where the problems above do not apply, but exceptions cannot be used for other reasons.
13436 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.
13437 In the absence of appropriate time estimation tools, this is hard to guarantee for exceptions.
13438 Such systems (e.g. flight control software) typically also ban the use of dynamic (heap) memory.
13440 So, the primary guideline for error handling is "use exceptions and [RAII](#Re-raii)."
13441 This section deals with the cases where you either do not have an efficient implementation of exceptions,
13442 or have such a rat's nest of old-style code
13443 (e.g., lots of pointers, ill-defined ownership, and lots of unsystematic error handling based on tests of error codes)
13444 that it is infeasible to introduce simple and systematic exception handling.
13446 Before condemning exceptions or complaining too much about their cost, consider examples of the use of [error codes](#Re-no-throw-codes).
13447 Consider the cost and complexity of the use of error codes.
13448 If performance is your worry, measure.
13450 ##### Example
13452 Assume you wanted to write
13454     void func(zstring arg)
13455     {
13456         Gadget g {arg};
13457         // ...
13458     }
13460 If the `gadget` isn't correctly constructed, `func` exits with an exception.
13461 If we cannot throw an exception, we can simulate this RAII style of resource handling by adding a `valid()` member function to `Gadget`:
13463     error_indicator func(zstring arg)
13464     {
13465         Gadget g {arg};
13466         if (!g.valid()) return gadget_construction_error;
13467         // ...
13468         return 0;   // zero indicates "good"
13469     }
13471 The problem is of course that the caller now has to remember to test the return value.
13473 **See also**: [Discussion](#Sd-???).
13475 ##### Enforcement
13477 Possible (only) for specific versions of this idea: e.g., test for systematic test of `valid()` after resource handle construction
13479 ### <a name="Re-no-throw-crash"></a>E.26: If you can't throw exceptions, consider failing fast
13481 ##### Reason
13483 If you can't do a good job at recovering, at least you can get out before too much consequential damage is done.
13485 See also [Simulating RAII](#Re-no-throw-raii).
13487 ##### Note
13489 If you cannot be systematic about error handling, consider "crashing" as a response to any error that cannot be handled locally.
13490 That is, if you cannot recover from an error in the context of the function that detected it, call `abort()`, `quick_exit()`,
13491 or a similar function that will trigger some sort of system restart.
13493 In systems where you have lots of processes and/or lots of computers, you need to expect and handle fatal crashes anyway,
13494 say from hardware failures.
13495 In such cases, "crashing" is simply leaving error handling to the next level of the system.
13497 ##### Example
13499     void f(int n)
13500     {
13501         // ...
13502         p = static_cast<X*>(malloc(n, X));
13503         if (p == nullptr) abort();     // abort if memory is exhausted
13504         // ...
13505     }
13507 Most programs cannot handle memory exhaustion gracefully anyway. This is roughly equivalent to
13509     void f(int n)
13510     {
13511         // ...
13512         p = new X[n];    // throw if memory is exhausted (by default, terminate)
13513         // ...
13514     }
13516 Typically, it is a good idea to log the reason for the "crash" before exiting.
13518 ##### Enforcement
13520 Awkward
13522 ### <a name="Re-no-throw-codes"></a>E.27: If you can't throw exceptions, use error codes systematically
13524 ##### Reason
13526 Systematic use of any error-handling strategy minimizes the chance of forgetting to handle an error.
13528 See also [Simulating RAII](#Re-no-throw-raii).
13530 ##### Note
13532 There are several issues to be addressed:
13534 * how do you transmit an error indicator from out of a function?
13535 * how do you release all resources from a function before doing an error exit?
13536 * What do you use as an error indicator?
13538 In general, returning an error indicator implies returning two values: The result and an error indicator.
13539 The error indicator can be part of the object, e.g. an object can have a `valid()` indicator
13540 or a pair of values can be returned.
13542 ##### Example
13544     Gadget make_gadget(int n)
13545     {
13546         // ...
13547     }
13549     void user()
13550     {
13551         Gadget g = make_gadget(17);
13552         if (!g.valid()) {
13553                 // error handling
13554         }
13555         // ...
13556     }
13558 This approach fits with [simulated RAII resource management](#Re-no-throw-raii).
13559 The `valid()` function could return an `error_indicator` (e.g. a member of an `error_indicator` enumeration).
13561 ##### Example
13563 What if we cannot or do not want to modify the `Gadget` type?
13564 In that case, we must return a pair of values.
13565 For example:
13567     std::pair<Gadget, error_indicator> make_gadget(int n)
13568     {
13569         // ...
13570     }
13572     void user()
13573     {
13574         auto r = make_gadget(17);
13575         if (!r.second) {
13576                 // error handling
13577         }
13578         Gadget& g = r.first;
13579         // ...
13580     }
13582 As shown, `std::pair` is a possible return type.
13583 Some people prefer a specific type.
13584 For example:
13586     Gval make_gadget(int n)
13587     {
13588         // ...
13589     }
13591     void user()
13592     {
13593         auto r = make_gadget(17);
13594         if (!r.err) {
13595                 // error handling
13596         }
13597         Gadget& g = r.val;
13598         // ...
13599     }
13601 One reason to prefer a specific return type is to have names for its members, rather than the somewhat cryptic `first` and `second`
13602 and to avoid confusion with other uses of `std::pair`.
13604 ##### Example
13606 In general, you must clean up before an error exit.
13607 This can be messy:
13609     std::pair<int, error_indicator> user()
13610     {
13611         Gadget g1 = make_gadget(17);
13612         if (!g1.valid()) {
13613                 return {0, g1_error};
13614         }
13616         Gadget g2 = make_gadget(17);
13617         if (!g2.valid()) {
13618                 cleanup(g1);
13619                 return {0, g2_error};
13620         }
13622         // ...
13624         if (all_foobar(g1, g2)) {
13625             cleanup(g1);
13626             cleanup(g2);
13627             return {0, foobar_error};
13628         // ...
13630         cleanup(g1);
13631         cleanup(g2);
13632         return {res, 0};
13633     }
13635 Simulating RAII can be non-trivial, especially in functions with multiple resources and multiple possible errors.
13636 A not uncommon technique is to gather cleanup at the end of the function to avoid repetition:
13638     std::pair<int, error_indicator> user()
13639     {
13640         error_indicator err = 0;
13642         Gadget g1 = make_gadget(17);
13643         if (!g1.valid()) {
13644                 err = g1_error;
13645                 goto exit;
13646         }
13648         Gadget g2 = make_gadget(17);
13649         if (!g2.valid()) {
13650                 err = g2_error;
13651                 goto exit;
13652         }
13654         if (all_foobar(g1, g2)) {
13655             err = foobar_error;
13656             goto exit;
13657         }
13658         // ...
13660     exit:
13661       if (g1.valid()) cleanup(g1);
13662       if (g2.valid()) cleanup(g2);
13663       return {res, err};
13664     }
13666 The larger the function, the more tempting this technique becomes.
13667 `finally` can [ease the pain a bit](#Re-finally).
13668 Also, the larger the program becomes the harder it is to apply an error-indicator-based error handling strategy systematically.
13670 We [prefer exception-based error handling](#Re-throw) and recommend [keeping functions short](#Rf-single).
13672 **See also**: [Discussion](#Sd-???).
13674 **See also**: [Returning multiple values](#Rf-out-multi).
13676 ##### Enforcement
13678 Awkward.
13680 ### <a name="Re-no-throw"></a>E.28: Avoid error handling based on global state (e.g. `errno`)
13682 ##### Reason
13684 Global state is hard to manage and it is easy to forget to check it.
13685 When did you last test the return value of `printf()`?
13687 See also [Simulating RAII](#Re-no-throw-raii).
13689 ##### Example, bad
13691     ???
13693 ##### Note
13695 C-style error handling is based on the global variable `errno`, so it is essentially impossible to avoid this style completely.
13697 ##### Enforcement
13699 Awkward.
13701 # <a name="S-const"></a>Con: Constants and Immutability
13703 You can't have a race condition on a constant.
13704 It is easier to reason about a program when many of the objects cannot change their values.
13705 Interfaces that promises "no change" of objects passed as arguments greatly increase readability.
13707 Constant rule summary:
13709 * [Con.1: By default, make objects immutable](#Rconst-immutable)
13710 * [Con.2: By default, make member functions `const`](#Rconst-fct)
13711 * [Con.3: By default, pass pointers and references to `const`s](#Rconst-ref)
13712 * [Con.4: Use `const` to define objects with values that do not change after construction](#Rconst-const)
13713 * [Con.5: Use `constexpr` for values that can be computed at compile time](#Rconst-constexpr)
13715 ### <a name="Rconst-immutable"></a>Con.1: By default, make objects immutable
13717 ##### Reason
13719 Immutable objects are easier to reason about, so make objects non-`const` only when there is a need to change their value.
13720 Prevents accidental or hard-to-notice change of value.
13722 ##### Example
13724     for (const string& s : c) cout << s << '\n';    // just reading: const
13726     for (string& s : c) cout << s << '\n';    // BAD: just reading
13728     for (string& s : c) cin >> s;  // needs to write: non-const
13730 ##### Exception
13732 Function arguments are rarely mutated, but also rarely declared const.
13733 To avoid confusion and lots of false positives, don't enforce this rule for function arguments.
13735     void f(const char* const p); // pedantic
13736     void g(const int i);        // pedantic
13738 Note that function parameter is a local variable so changes to it are local.
13740 ##### Enforcement
13742 * Flag non-const variables that are not modified (except for parameters to avoid many false positives)
13744 ### <a name="Rconst-fct"></a>Con.2: By default, make member functions `const`
13746 ##### Reason
13748 A member function should be marked `const` unless it changes the object's observable state.
13749 This gives a more precise statement of design intent, better readability, more errors caught by the compiler, and sometimes more optimization opportunities.
13751 ##### Example; bad
13753     class Point {
13754         int x, y;
13755     public:
13756         int getx() { return x; }    // BAD, should be const as it doesn't modify the object's state
13757         // ...
13758     };
13760     void f(const Point& pt) {
13761         int x = pt.getx();          // ERROR, doesn't compile because getx was not marked const
13762     }
13764 ##### Note
13766 [Do not cast away `const`](#Res-casts-const).
13768 ##### Enforcement
13770 * Flag a member function that is not marked `const`, but that does not perform a non-`const` operation on any member variable.
13772 ### <a name="Rconst-ref"></a>Con.3: By default, pass pointers and references to `const`s
13774 ##### Reason
13776  To avoid a called function unexpectedly changing the value.
13777  It's far easier to reason about programs when called functions don't modify state.
13779 ##### Example
13781     void f(char* p);        // does f modify *p? (assume it does)
13782     void g(const char* p);  // g does not modify *p
13784 ##### Note
13786 It is not inherently bad to pass a pointer or reference to non-const,
13787 but that should be done only when the called function is supposed to modify the object.
13789 ##### Note
13791 [Do not cast away `const`](#Res-casts-const).
13793 ##### Enforcement
13795 * Flag function that does not modify an object passed by  pointer or reference to non-`const`
13796 * Flag a function that (using a cast) modifies an object passed by pointer or reference to `const`
13798 ### <a name="Rconst-const"></a>Con.4: Use `const` to define objects with values that do not change after construction
13800 ##### Reason
13802  Prevent surprises from unexpectedly changed object values.
13804 ##### Example
13806     void f()
13807     {
13808         int x = 7;
13809         const int y = 9;
13811         for (;;) {
13812             // ...
13813         }
13814         // ...
13815     }
13817 As `x` is not `const`, we must assume that it is modified somewhere in the loop.
13819 ##### Enforcement
13821 * Flag unmodified non-`const` variables.
13823 ### <a name="Rconst-constexpr"></a>Con.5: Use `constexpr` for values that can be computed at compile time
13825 ##### Reason
13827 Better performance, better compile-time checking, guaranteed compile-time evaluation, no possibility of race conditions.
13829 ##### Example
13831     double x = f(2);            // possible run-time evaluation
13832     const double y = f(2);      // possible run-time evaluation
13833     constexpr double z = f(2);  // error unless f(2) can be evaluated at compile time
13835 ##### Note
13837 See F.4.
13839 ##### Enforcement
13841 * Flag `const` definitions with constant expression initializers.
13843 # <a name="S-templates"></a>T: Templates and generic programming
13845 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
13846 In C++, generic programming is supported by the `template` language mechanisms.
13848 Arguments to generic functions are characterized by sets of requirements on the argument types and values involved.
13849 In C++, these requirements are expressed by compile-time predicates called concepts.
13851 Templates can also be used for meta-programming; that is, programs that compose code at compile time.
13853 A central notion in generic programming is "concepts"; that is, requirements on template arguments presented as compile-time predicates.
13854 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
13855 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)
13856 Currently (July 2016), concepts are supported only in GCC 6.1.
13857 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
13858 If you use GCC 6.1, you can uncomment them.
13860 Template use rule summary:
13862 * [T.1: Use templates to raise the level of abstraction of code](#Rt-raise)
13863 * [T.2: Use templates to express algorithms that apply to many argument types](#Rt-algo)
13864 * [T.3: Use templates to express containers and ranges](#Rt-cont)
13865 * [T.4: Use templates to express syntax tree manipulation](#Rt-expr)
13866 * [T.5: Combine generic and OO techniques to amplify their strengths, not their costs](#Rt-generic-oo)
13868 Concept use rule summary:
13870 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
13871 * [T.11: Whenever possible use standard concepts](#Rt-std-concepts)
13872 * [T.12: Prefer concept names over `auto` for local variables](#Rt-auto)
13873 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
13874 * ???
13876 Concept definition rule summary:
13878 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
13879 * [T.21: Require a complete set of operations for a concept](#Rt-complete)
13880 * [T.22: Specify axioms for concepts](#Rt-axiom)
13881 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
13882 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
13883 * [T.25: Avoid complementary constraints](#Rt-not)
13884 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
13885 * [T.30: Use concept negation (`!C<T>`) sparingly to express a minor difference](#Rt-not)
13886 * [T.31: Use concept disjunction (`C1<T> || C2<T>`) sparingly to express alternatives](#Rt-or)
13887 * ???
13889 Template interface rule summary:
13891 * [T.40: Use function objects to pass operations to algorithms](#Rt-fo)
13892 * [T.41: Require only essential properties in a template's concepts](#Rt-essential)
13893 * [T.42: Use template aliases to simplify notation and hide implementation details](#Rt-alias)
13894 * [T.43: Prefer `using` over `typedef` for defining aliases](#Rt-using)
13895 * [T.44: Use function templates to deduce class template argument types (where feasible)](#Rt-deduce)
13896 * [T.46: Require template arguments to be at least `Regular` or `SemiRegular`](#Rt-regular)
13897 * [T.47: Avoid highly visible unconstrained templates with common names](#Rt-visible)
13898 * [T.48: If your compiler does not support concepts, fake them with `enable_if`](#Rt-concept-def)
13899 * [T.49: Where possible, avoid type-erasure](#Rt-erasure)
13901 Template definition rule summary:
13903 * [T.60: Minimize a template's context dependencies](#Rt-depend)
13904 * [T.61: Do not over-parameterize members (SCARY)](#Rt-scary)
13905 * [T.62: Place non-dependent class template members in a non-templated base class](#Rt-nondependent)
13906 * [T.64: Use specialization to provide alternative implementations of class templates](#Rt-specialization)
13907 * [T.65: Use tag dispatch to provide alternative implementations of functions](#Rt-tag-dispatch)
13908 * [T.67: Use specialization to provide alternative implementations for irregular types](#Rt-specialization2)
13909 * [T.68: Use `{}` rather than `()` within templates to avoid ambiguities](#Rt-cast)
13910 * [T.69: Inside a template, don't make an unqualified nonmember function call unless you intend it to be a customization point](#Rt-customization)
13912 Template and hierarchy rule summary:
13914 * [T.80: Do not naively templatize a class hierarchy](#Rt-hier)
13915 * [T.81: Do not mix hierarchies and arrays](#Rt-array) // ??? somewhere in "hierarchies"
13916 * [T.82: Linearize a hierarchy when virtual functions are undesirable](#Rt-linear)
13917 * [T.83: Do not declare a member function template virtual](#Rt-virtual)
13918 * [T.84: Use a non-template core implementation to provide an ABI-stable interface](#Rt-abi)
13919 * [T.??: ????](#Rt-???)
13921 Variadic template rule summary:
13923 * [T.100: Use variadic templates when you need a function that takes a variable number of arguments of a variety of types](#Rt-variadic)
13924 * [T.101: ??? How to pass arguments to a variadic template ???](#Rt-variadic-pass)
13925 * [T.102: ??? How to process arguments to a variadic template ???](#Rt-variadic-process)
13926 * [T.103: Don't use variadic templates for homogeneous argument lists](#Rt-variadic-not)
13927 * [T.??: ????](#Rt-???)
13929 Metaprogramming rule summary:
13931 * [T.120: Use template metaprogramming only when you really need to](#Rt-metameta)
13932 * [T.121: Use template metaprogramming primarily to emulate concepts](#Rt-emulate)
13933 * [T.122: Use templates (usually template aliases) to compute types at compile time](#Rt-tmp)
13934 * [T.123: Use `constexpr` functions to compute values at compile time](#Rt-fct)
13935 * [T.124: Prefer to use standard-library TMP facilities](#Rt-std-tmp)
13936 * [T.125: If you need to go beyond the standard-library TMP facilities, use an existing library](#Rt-lib)
13937 * [T.??: ????](#Rt-???)
13939 Other template rules summary:
13941 * [T.140: Name all operations with potential for reuse](#Rt-name)
13942 * [T.141: Use an unnamed lambda if you need a simple function object in one place only](#Rt-lambda)
13943 * [T.142: Use template variables to simplify notation](#Rt-var)
13944 * [T.143: Don't write unintentionally nongeneric code](#Rt-nongeneric)
13945 * [T.144: Don't specialize function templates](#Rt-specialize-function)
13946 * [T.150: Check that a class matches a concept using `static_assert`](#Rt-check-class)
13947 * [T.??: ????](#Rt-???)
13949 ## <a name="SS-GP"></a>T.gp: Generic programming
13951 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
13953 ### <a name="Rt-raise"></a>T.1: Use templates to raise the level of abstraction of code
13955 ##### Reason
13957 Generality. Re-use. Efficiency. Encourages consistent definition of user types.
13959 ##### Example, bad
13961 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":
13963     template<typename T>
13964         // requires Incrementable<T>
13965     T sum1(vector<T>& v, T s)
13966     {
13967         for (auto x : v) s += x;
13968         return s;
13969     }
13971     template<typename T>
13972         // requires Simple_number<T>
13973     T sum2(vector<T>& v, T s)
13974     {
13975         for (auto x : v) s = s + x;
13976         return s;
13977     }
13979 Assuming that `Incrementable` does not support `+` and `Simple_number` does not support `+=`, we have overconstrained implementers of `sum1` and `sum2`.
13980 And, in this case, missed an opportunity for a generalization.
13982 ##### Example
13984     template<typename T>
13985         // requires Arithmetic<T>
13986     T sum(vector<T>& v, T s)
13987     {
13988         for (auto x : v) s += x;
13989         return s;
13990     }
13992 Assuming that `Arithmetic` requires both `+` and `+=`, we have constrained the user of `sum` to provide a complete arithmetic type.
13993 That is not a minimal requirement, but it gives the implementer of algorithms much needed freedom and ensures that any `Arithmetic` type
13994 can be used for a wide variety of algorithms.
13996 For additional generality and reusability, we could also use a more general `Container` or `Range` concept instead of committing to only one container, `vector`.
13998 ##### Note
14000 If we define a template to require exactly the operations required for a single implementation of a single algorithm
14001 (e.g., requiring just `+=` rather than also `=` and `+`) and only those, we have overconstrained maintainers.
14002 We aim to minimize requirements on template arguments, but the absolutely minimal requirements of an implementation is rarely a meaningful concept.
14004 ##### Note
14006 Templates can be used to express essentially everything (they are Turing complete), but the aim of generic programming (as expressed using templates)
14007 is to efficiently generalize operations/algorithms over a set of types with similar semantic properties.
14009 ##### Note
14011 The `requires` in the comments are uses of `concepts`.
14012 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
14013 Currently (July 2016), concepts are supported only in GCC 6.1.
14014 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
14015 If you use GCC 6.1, you can uncomment them.
14017 ##### Enforcement
14019 * Flag algorithms with "overly simple" requirements, such as direct use of specific operators without a concept.
14020 * Do not flag the definition of the "overly simple" concepts themselves; they may simply be building blocks for more useful concepts.
14022 ### <a name="Rt-algo"></a>T.2: Use templates to express algorithms that apply to many argument types
14024 ##### Reason
14026 Generality. Minimizing the amount of source code. Interoperability. Re-use.
14028 ##### Example
14030 That's the foundation of the STL. A single `find` algorithm easily works with any kind of input range:
14032     template<typename Iter, typename Val>
14033         // requires Input_iterator<Iter>
14034         //       && Equality_comparable<Value_type<Iter>, Val>
14035     Iter find(Iter b, Iter e, Val v)
14036     {
14037         // ...
14038     }
14040 ##### Note
14042 Don't use a template unless you have a realistic need for more than one template argument type.
14043 Don't overabstract.
14045 ##### Enforcement
14047 ??? tough, probably needs a human
14049 ### <a name="Rt-cont"></a>T.3: Use templates to express containers and ranges
14051 ##### Reason
14053 Containers need an element type, and expressing that as a template argument is general, reusable, and type safe.
14054 It also avoids brittle or inefficient workarounds. Convention: That's the way the STL does it.
14056 ##### Example
14058     template<typename T>
14059         // requires Regular<T>
14060     class Vector {
14061         // ...
14062         T* elem;   // points to sz Ts
14063         int sz;
14064     };
14066     Vector<double> v(10);
14067     v[7] = 9.9;
14069 ##### Example, bad
14071     class Container {
14072         // ...
14073         void* elem;   // points to size elements of some type
14074         int sz;
14075     };
14077     Container c(10, sizeof(double));
14078     ((double*) c.elem)[] = 9.9;
14080 This doesn't directly express the intent of the programmer and hides the structure of the program from the type system and optimizer.
14082 Hiding the `void*` behind macros simply obscures the problems and introduces new opportunities for confusion.
14084 **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.
14085 See [Stable base](#Rt-abi).
14087 ##### Enforcement
14089 * Flag uses of `void*`s and casts outside low-level implementation code
14091 ### <a name="Rt-expr"></a>T.4: Use templates to express syntax tree manipulation
14093 ##### Reason
14095  ???
14097 ##### Example
14099     ???
14101 **Exceptions**: ???
14103 ### <a name="Rt-generic-oo"></a>T.5: Combine generic and OO techniques to amplify their strengths, not their costs
14105 ##### Reason
14107 Generic and OO techniques are complementary.
14109 ##### Example
14111 Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces.
14113     class Command {
14114         // pure virtual functions
14115     };
14117     // implementations
14118     template</*...*/>
14119     class ConcreteCommand : public Command {
14120         // implement virtuals
14121     };
14123 ##### Example
14125 Dynamic helps static: Offer a generic, comfortable, statically bound interface, but internally dispatch dynamically, so you offer a uniform object layout.
14126 Examples include type erasure as with `std::shared_ptr`'s deleter (but [don't overuse type erasure](#Rt-erasure)).
14128 ##### Note
14130 In a class template, nonvirtual functions are only instantiated if they're used -- but virtual functions are instantiated every time.
14131 This can bloat code size, and may overconstrain a generic type by instantiating functionality that is never needed.
14132 Avoid this, even though the standard-library facets made this mistake.
14134 ##### See also
14136 * ref ???
14137 * ref ???
14138 * ref ???
14140 ##### Enforcement
14142 See the reference to more specific rules.
14144 ## <a name="SS-concepts"></a>T.concepts: Concept rules
14146 Concepts is a facility for specifying requirements for template arguments.
14147 It is an [ISO technical specification](#Ref-conceptsTS), but currently supported only by GCC.
14148 Concepts are, however, crucial in the thinking about generic programming and the basis of much work on future C++ libraries
14149 (standard and other).
14151 This section assumes concept support
14153 Concept use rule summary:
14155 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
14156 * [T.11: Whenever possible use standard concepts](#Rt-std-concepts)
14157 * [T.12: Prefer concept names over `auto`](#Rt-auto)
14158 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
14159 * ???
14161 Concept definition rule summary:
14163 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
14164 * [T.21: Require a complete set of operations for a concept](#Rt-complete)
14165 * [T.22: Specify axioms for concepts](#Rt-axiom)
14166 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
14167 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
14168 * [T.25: Avoid complimentary constraints](#Rt-not)
14169 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
14170 * ???
14172 ## <a name="SS-concept-use"></a>T.con-use: Concept use
14174 ### <a name="Rt-concepts"></a>T.10: Specify concepts for all template arguments
14176 ##### Reason
14178 Correctness and readability.
14179 The assumed meaning (syntax and semantics) of a template argument is fundamental to the interface of a template.
14180 A concept dramatically improves documentation and error handling for the template.
14181 Specifying concepts for template arguments is a powerful design tool.
14183 ##### Example
14185     template<typename Iter, typename Val>
14186     //    requires Input_iterator<Iter>
14187     //             && Equality_comparable<Value_type<Iter>, Val>
14188     Iter find(Iter b, Iter e, Val v)
14189     {
14190         // ...
14191     }
14193 or equivalently and more succinctly:
14195     template<Input_iterator Iter, typename Val>
14196     //    requires Equality_comparable<Value_type<Iter>, Val>
14197     Iter find(Iter b, Iter e, Val v)
14198     {
14199         // ...
14200     }
14202 ##### Note
14204 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
14205 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)
14206 Currently (July 2016), concepts are supported only in GCC 6.1.
14207 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
14208 If you use GCC 6.1, you can uncomment them:
14210     template<typename Iter, typename Val>
14211         requires Input_iterator<Iter>
14212                && Equality_comparable<Value_type<Iter>, Val>
14213     Iter find(Iter b, Iter e, Val v)
14214     {
14215         // ...
14216     }
14218 ##### Note
14220 Plain `typename` (or `auto`) is the least constraining concept.
14221 It should be used only rarely when nothing more than "it's a type" can be assumed.
14222 This is typically only needed when (as part of template metaprogramming code) we manipulate pure expression trees, postponing type checking.
14224 **References**: TC++PL4, Palo Alto TR, Sutton
14226 ##### Enforcement
14228 Flag template type arguments without concepts
14230 ### <a name="Rt-std-concepts"></a>T.11: Whenever possible use standard concepts
14232 ##### Reason
14234  "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)
14235 saves us the work of thinking up our own concepts, are better thought out than we can manage to do in a hurry, and improves interoperability.
14237 ##### Note
14239 Unless you are creating a new generic library, most of the concepts you need will already be defined by the standard library.
14241 ##### Example (using TS concepts)
14243     template<typename T>
14244         // don't define this: Sortable is in the GSL
14245     concept Ordered_container = Sequence<T> && Random_access<Iterator<T>> && Ordered<Value_type<T>>;
14247     void sort(Ordered_container& s);
14249 This `Ordered_container` is quite plausible, but it is very similar to the `Sortable` concept in the GSL (and the Range TS).
14250 Is it better? Is it right? Does it accurately reflect the standard's requirements for `sort`?
14251 It is better and simpler just to use `Sortable`:
14253     void sort(Sortable& s);   // better
14255 ##### Note
14257 The set of "standard" concepts is evolving as we approach an ISO standard including concepts.
14259 ##### Note
14261 Designing a useful concept is challenging.
14263 ##### Enforcement
14265 Hard.
14267 * Look for unconstrained arguments, templates that use "unusual"/non-standard concepts, templates that use "homebrew" concepts without axioms.
14268 * Develop a concept-discovery tool (e.g., see [an early experiment](http://www.stroustrup.com/sle2010_webversion.pdf)).
14270 ### <a name="Rt-auto"></a>T.12: Prefer concept names over `auto` for local variables
14272 ##### Reason
14274  `auto` is the weakest concept. Concept names convey more meaning than just `auto`.
14276 ##### Example (using TS concepts)
14278     vector<string> v;
14279     auto& x = v.front();     // bad
14280     String& s = v.begin();   // good (String is a GSL concept)
14282 ##### Enforcement
14284 * ???
14286 ### <a name="Rt-shorthand"></a>T.13: Prefer the shorthand notation for simple, single-type argument concepts
14288 ##### Reason
14290 Readability. Direct expression of an idea.
14292 ##### Example (using TS concepts)
14294 To say "`T` is `Sortable`":
14296     template<typename T>       // Correct but verbose: "The parameter is
14297     //    requires Sortable<T>   // of type T which is the name of a type
14298     void sort(T&);             // that is Sortable"
14300     template<Sortable T>       // Better (assuming support for concepts): "The parameter is of type T
14301     void sort(T&);             // which is Sortable"
14303     void sort(Sortable&);      // Best (assuming support for concepts): "The parameter is Sortable"
14305 The shorter versions better match the way we speak. Note that many templates don't need to use the `template` keyword.
14307 ##### Note
14309 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
14310 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)
14311 Currently (July 2016), concepts are supported only in GCC 6.1.
14312 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
14313 If you use a compiler that supports concepts (e.g., GCC 6.1), you can remove the `//`.
14315 ##### Enforcement
14317 * Not feasible in the short term when people convert from the `<typename T>` and `<class T`> notation.
14318 * Later, flag declarations that first introduces a typename and then constrains it with a simple, single-type-argument concept.
14320 ## <a name="SS-concepts-def"></a>T.concepts.def: Concept definition rules
14322 Defining good concepts is non-trivial.
14323 Concepts are meant to represent fundamental concepts in an application domain (hence the name "concepts").
14324 Similarly throwing together a set of syntactic constraints to be used for a the arguments for a single class or algorithm is not what concepts were designed for
14325 and will not give the full benefits of the mechanism.
14327 Obviously, defining concepts will be most useful for code that can use an implementation (e.g., GCC 6.1),
14328 but defining concepts is in itself a useful design technique and help catch conceptual errors and clean up the concepts (sic!) of an implementation.
14330 ### <a name="Rt-low"></a>T.20: Avoid "concepts" without meaningful semantics
14332 ##### Reason
14334 Concepts are meant to express semantic notions, such as "a number", "a range" of elements, and "totally ordered."
14335 Simple constraints, such as "has a `+` operator" and "has a `>` operator" cannot be meaningfully specified in isolation
14336 and should be used only as building blocks for meaningful concepts, rather than in user code.
14338 ##### Example, bad (using TS concepts)
14340     template<typename T>
14341     concept Addable = has_plus<T>;    // bad; insufficient
14343     template<Addable N> auto algo(const N& a, const N& b) // use two numbers
14344     {
14345         // ...
14346         return a + b;
14347     }
14349     int x = 7;
14350     int y = 9;
14351     auto z = plus(x, y);   // z = 16
14353     string xx = "7";
14354     string yy = "9";
14355     auto zz = plus(xx, yy);   // zz = "79"
14357 Maybe the concatenation was expected. More likely, it was an accident. Defining minus equivalently would give dramatically different sets of accepted types.
14358 This `Addable` violates the mathematical rule that addition is supposed to be commutative: `a+b == b+a`.
14360 ##### Note
14362 The ability to specify a meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint.
14364 ##### Example (using TS concepts)
14366     template<typename T>
14367     // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
14368     concept Number = has_plus<T>
14369                      && has_minus<T>
14370                      && has_multiply<T>
14371                      && has_divide<T>;
14373     template<Number N> auto algo(const N& a, const N& b) // use two numbers
14374     {
14375         // ...
14376         return a + b;
14377     }
14379     int x = 7;
14380     int y = 9;
14381     auto z = plus(x, y);   // z = 18
14383     string xx = "7";
14384     string yy = "9";
14385     auto zz = plus(xx, yy);   // error: string is not a Number
14387 ##### Note
14389 Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept.
14391 ##### Enforcement
14393 * Flag single-operation `concepts` when used outside the definition of other `concepts`.
14394 * Flag uses of `enable_if` that appears to simulate single-operation `concepts`.
14397 ### <a name="ations"></a>T.21: Require a complete set of operations for a concept
14399 ##### Reason
14401 Ease of comprehension.
14402 Improved interoperability.
14403 Helps implementers and maintainers.
14405 ##### Note
14407 This is a specific variant of the general rule that [a concept must make semantic sense](#Rt-low).
14409 ##### Example, bad (using TS concepts)
14411     template<typename T> concept Subtractable = requires(T a, T, b) { a-b; };
14413 This makes no semantic sense.
14414 You need at least `+` to make `-` meaningful and useful.
14416 Examples of complete sets are
14418 * `Arithmetic`: `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`
14419 * `Comparable`: `<`, `>`, `<=`, `>=`, `==`, `!=`
14421 ##### Note
14423 This rule applies whether we use direct language support for concepts or not.
14424 It is a general design rule that even applies to non-templates:
14426     class Minimal {
14427         // ...
14428     };
14430     bool operator==(const Minimal&, const Minimal&);
14431     bool operator<(const Minimal&, const Minimal&);
14433     Minimal operator+(const Minimal&, const Minimal&);
14434     // no other operators
14436     void f(const Minimal& x, const Minimal& y)
14437     {
14438         if (!(x == y) { /* ... */ }     // OK
14439         if (x != y) { /* ... */ }       // surprise! error
14441         while (!(x < y)) { /* ... */ }  // OK
14442         while (x >= y) { /* ... */ }    // surprise! error
14444         x = x + y;        // OK
14445         x += y;             // surprise! error
14446     }
14448 This is minimal, but surprising and constraining for users.
14449 It could even be less efficient.
14451 The rule supports the view that a concept should reflect a (mathematically) coherent set of operations.
14453 ##### Example
14455     class Convenient {
14456         // ...
14457     };
14459     bool operator==(const Convenient&, const Convenient&);
14460     bool operator<(const Convenient&, const Convenient&);
14461     // ... and the other comparison operators ...
14463     Minimal operator+(const Convenient&, const Convenient&);
14464     // .. and the other arithmetic operators ...
14466     void f(const Convenient& x, const Convenient& y)
14467     {
14468         if (!(x == y) { /* ... */ }     // OK
14469         if (x != y) { /* ... */ }       // OK
14471         while (!(x < y)) { /* ... */ }  // OK
14472         while (x >= y) { /* ... */ }    // OK
14474         x = x + y;     // OK
14475         x += y;      // OK
14476     }
14478 It can be a nuisance to define all operators, but not hard.
14479 Ideally, that rule should be language supported by giving you comparison operators by default.
14481 ##### Enforcement
14483 * Flag classes the support "odd" subsets of a set of operators, e.g., `==` but not `!=` or `+` but not `-`.
14484   Yes, `std::string` is "odd", but it's too late to change that.
14487 ### <a name="Rt-axiom"></a>T.22: Specify axioms for concepts
14489 ##### Reason
14491 A meaningful/useful concept has a semantic meaning.
14492 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.
14493 Specifying semantics is a powerful design tool.
14495 ##### Example (using TS concepts)
14497     template<typename T>
14498         // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
14499         // axiom(T a, T b) { a + b == b + a; a - a == 0; a * (b + c) == a * b + a * c; /*...*/ }
14500         concept Number = requires(T a, T b) {
14501             {a + b} -> T;   // the result of a + b is convertible to T
14502             {a - b} -> T;
14503             {a * b} -> T;
14504             {a / b} -> T;
14505         }
14507 ##### Note
14509 This is an axiom in the mathematical sense: something that may be assumed without proof.
14510 In general, axioms are not provable, and when they are the proof is often beyond the capability of a compiler.
14511 An axiom may not be general, but the template writer may assume that it holds for all inputs actually used (similar to a precondition).
14513 ##### Note
14515 In this context axioms are Boolean expressions.
14516 See the [Palo Alto TR](#S-references) for examples.
14517 Currently, C++ does not support axioms (even the ISO Concepts TS), so we have to make do with comments for a longish while.
14518 Once language support is available, the `//` in front of the axiom can be removed
14520 ##### Note
14522 The GSL concepts have well defined semantics; see the Palo Alto TR and the Ranges TS.
14524 ##### Exception (using TS concepts)
14526 Early versions of a new "concept" still under development will often just define simple sets of constraints without a well-specified semantics.
14527 Finding good semantics can take effort and time.
14528 An incomplete set of constraints can still be very useful:
14530     // balancer for a generic binary tree
14531     template<typename Node> concept bool Balancer = requires(Node* p) {
14532         add_fixup(p);
14533         touch(p);
14534         detach(p);
14535     }
14537 So a `Balancer` must supply at least thee operations on a tree `Node`,
14538 but we are not yet ready to specify detailed semantics because a new kind of balanced tree might require more operations
14539 and the precise general semantics for all nodes is hard to pin down in the early stages of design.
14541 A "concept" that is incomplete or without a well-specified semantics can still be useful.
14542 For example, it allows for some checking during initial experimentation.
14543 However, it should not be assumed to be stable.
14544 Each new use case may require such an incomplete concepts to be improved.
14546 ##### Enforcement
14548 * Look for the word "axiom" in concept definition comments
14550 ### <a name="Rt-refine"></a>T.23: Differentiate a refined concept from its more general case by adding new use patterns.
14552 ##### Reason
14554 Otherwise they cannot be distinguished automatically by the compiler.
14556 ##### Example (using TS concepts)
14558     template<typename I>
14559     concept bool Input_iter = requires(I iter) { ++iter; };
14561     template<typename I>
14562     concept bool Fwd_iter = Input_iter<I> && requires(I iter) { iter++; }
14564 The compiler can determine refinement based on the sets of required operations (here, suffix `++`).
14565 This decreases the burden on implementers of these types since
14566 they do not need any special declarations to "hook into the concept".
14567 If two concepts have exactly the same requirements, they are logically equivalent (there is no refinement).
14569 ##### Enforcement
14571 * Flag a concept that has exactly the same requirements as another already-seen concept (neither is more refined).
14572 To disambiguate them, see [T.24](#Rt-tag).
14574 ### <a name="Rt-tag"></a>T.24: Use tag classes or traits to differentiate concepts that differ only in semantics.
14576 ##### Reason
14578 Two concepts requiring the same syntax but having different semantics leads to ambiguity unless the programmer differentiates them.
14580 ##### Example (using TS concepts)
14582     template<typename I>    // iterator providing random access
14583     concept bool RA_iter = ...;
14585     template<typename I>    // iterator providing random access to contiguous data
14586     concept bool Contiguous_iter =
14587         RA_iter<I> && is_contiguous<I>::value;  // using is_contiguous trait
14589 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
14591 Wrapping a tag class into a concept leads to a simpler expression of this idea:
14593     template<typename I> concept Contiguous = is_contiguous<I>::value;
14595     template<typename I>
14596     concept bool Contiguous_iter = RA_iter<I> && Contiguous<I>;
14598 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
14600 ##### Note
14602 Traits can be trait classes or type traits.
14603 These can be user-defined or standard-library ones.
14604 Prefer the standard-library ones.
14606 ##### Enforcement
14608 * The compiler flags ambiguous use of identical concepts.
14609 * Flag the definition of identical concepts.
14611 ### <a name="Rt-not"></a>T.25: Avoid complementary constraints
14613 ##### Reason
14615 Clarity. Maintainability.
14616 Functions with complementary requirements expressed using negation are brittle.
14618 ##### Example (using TS concepts)
14620 Initially, people will try to define functions with complementary requirements:
14622     template<typename T>
14623         requires !C<T>    // bad
14624     void f();
14626     template<typename T>
14627         requires C<T>
14628     void f();
14630 This is better:
14632     template<typename T>   // general template
14633         void f();
14635     template<typename T>   // specialization by concept
14636         requires C<T>
14637     void f();
14639 The compiler will choose the unconstrained template only when `C<T>` is
14640 unsatisfied. If you do not want to (or cannot) define an unconstrained
14641 version of `f()`, then delete it.
14643     template<typename T>
14644     void f() = delete;
14646 The compiler will select the overload and emit an appropriate error.
14648 ##### Note
14650 Complementary constraints are unfortunately common in `enable_if` code:
14652     template<typename T>
14653     enable_if<!C<T>, void>   // bad
14654     f();
14656     template<typename T>
14657     enable_if<C<T>, void>
14658     f();
14661 ##### Note
14663 Complementary requirements on one requirements is sometimes (wrongly) considered manageable.
14664 However, for two or more requirements the number of definitions needs can go up exponentially (2,4,9,16,...):
14666     C1<T> && C2<T>
14667     !C1<T> && C2<T>
14668     C1<T> && !C2<T>
14669     !C1<T> && !C2<T>
14671 Now the opportunities for errors multiply.
14673 ##### Enforcement
14675 * Flag pairs of functions with `C<T>` and `!C<T>` constraints
14677 ### <a name="Rt-use"></a>T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax
14679 ##### Reason
14681 The definition is more readable and corresponds directly to what a user has to write.
14682 Conversions are taken into account. You don't have to remember the names of all the type traits.
14684 ##### Example (using TS concepts)
14686 You might be tempted to define a concept `Equality` like this:
14688     template<typename T> concept Equality = has_equal<T> && has_not_equal<T>;
14690 Obviously, it would be better and easier just to use the standard `EqualityComparable`,
14691 but - just as an example - if you had to define such a concept, prefer:
14693     template<typename T> concept Equality = requires(T a, T b) {
14694         bool == { a == b }
14695         bool == { a != b }
14696         // axiom { !(a == b) == (a != b) }
14697         // axiom { a = b; => a == b }  // => means "implies"
14698     }
14700 as opposed to defining two meaningless concepts `has_equal` and `has_not_equal` just as helpers in the definition of `Equality`.
14701 By "meaningless" we mean that we cannot specify the semantics of `has_equal` in isolation.
14703 ##### Enforcement
14707 ## <a name="SS-temp-interface"></a>Template interfaces
14709 Over the years, programming with templates have suffered from a weak distinction between the interface of a template
14710 and its implementation.
14711 Before concepts, that distinction had no direct language support.
14712 However, the interface to a template is a critical concept - a contract between a user and an implementer - and should be carefully designed.
14714 ### <a name="Rt-fo"></a>T.40: Use function objects to pass operations to algorithms
14716 ##### Reason
14718 Function objects can carry more information through an interface than a "plain" pointer to function.
14719 In general, passing function objects gives better performance than passing pointers to functions.
14721 ##### Example (using TS concepts)
14723     bool greater(double x, double y) { return x > y; }
14724     sort(v, greater);                                    // pointer to function: potentially slow
14725     sort(v, [](double x, double y) { return x > y; });   // function object
14726     sort(v, std::greater<>);                             // function object
14728     bool greater_than_7(double x) { return x > 7; }
14729     auto x = find_if(v, greater_than_7);                 // pointer to function: inflexible
14730     auto y = find_if(v, [](double x) { return x > 7; }); // function object: carries the needed data
14731     auto z = find_if(v, Greater_than<double>(7));        // function object: carries the needed data
14733 You can, of course, generalize those functions using `auto` or (when and where available) concepts. For example:
14735     auto y1 = find_if(v, [](Ordered x) { return x > 7; }); // require an ordered type
14736     auto z1 = find_if(v, [](auto x) { return x > 7; });    // hope that the type has a >
14738 ##### Note
14740 Lambdas generate function objects.
14742 ##### Note
14744 The performance argument depends on compiler and optimizer technology.
14746 ##### Enforcement
14748 * Flag pointer to function template arguments.
14749 * Flag pointers to functions passed as arguments to a template (risk of false positives).
14752 ### <a name="Rt-essential"></a>T.41: Require only essential properties in a template's concepts
14754 ##### Reason
14756 Keep interfaces simple and stable.
14758 ##### Example (using TS concepts)
14760 Consider, a `sort` instrumented with (oversimplified) simple debug support:
14762     void sort(Sortable& s)  // sort sequence s
14763     {
14764         if (debug) cerr << "enter sort( " << s <<  ")\n";
14765         // ...
14766         if (debug) cerr << "exit sort( " << s <<  ")\n";
14767     }
14769 Should this be rewritten to:
14771     template<Sortable S>
14772         requires Streamable<S>
14773     void sort(S& s)  // sort sequence s
14774     {
14775         if (debug) cerr << "enter sort( " << s <<  ")\n";
14776         // ...
14777         if (debug) cerr << "exit sort( " << s <<  ")\n";
14778     }
14780 After all, there is nothing in `Sortable` that requires `iostream` support.
14781 On the other hand, there is nothing in the fundamental idea of sorting that says anything about debugging.
14783 ##### Note
14785 If we require every operation used to be listed among the requirements, the interface becomes unstable:
14786 Every time we change the debug facilities, the usage data gathering, testing support, error reporting, etc.
14787 The definition of the template would need change and every use of the template would have to be recompiled.
14788 This is cumbersome, and in some environments infeasible.
14790 Conversely, if we use an operation in the implementation that is not guaranteed by concept checking,
14791 we may get a late compile-time error.
14793 By not using concept checking for properties of a template argument that is not considered essential,
14794 we delay checking until instantiation time.
14795 We consider this a worthwhile tradeoff.
14797 Note that using non-local, non-dependent names (such as `debug` and `cerr`) also introduces context dependencies that may lead to "mysterious" errors.
14799 ##### Note
14801 It can be hard to decide which properties of a type is essential and which are not.
14803 ##### Enforcement
14807 ### <a name="Rt-alias"></a>T.42: Use template aliases to simplify notation and hide implementation details
14809 ##### Reason
14811 Improved readability.
14812 Implementation hiding.
14813 Note that template aliases replace many uses of traits to compute a type.
14814 They can also be used to wrap a trait.
14816 ##### Example
14818     template<typename T, size_t N>
14819     class Matrix {
14820         // ...
14821         using Iterator = typename std::vector<T>::iterator;
14822         // ...
14823     };
14825 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>::`.
14827 ##### Example
14829     template<typename T>
14830     void user(T& c)
14831     {
14832         // ...
14833         typename container_traits<T>::value_type x; // bad, verbose
14834         // ...
14835     }
14837     template<typename T>
14838     using Value_type = typename container_traits<T>::value_type;
14841 This saves the user of `Value_type` from having to know the technique used to implement `value_type`s.
14843     template<typename T>
14844     void user2(T& c)
14845     {
14846         // ...
14847         Value_type<T> x;
14848         // ...
14849     }
14851 ##### Note
14853 A simple, common use could be expressed: "Wrap traits!"
14855 ##### Enforcement
14857 * Flag use of `typename` as a disambiguator outside `using` declarations.
14858 * ???
14860 ### <a name="Rt-using"></a>T.43: Prefer `using` over `typedef` for defining aliases
14862 ##### Reason
14864 Improved readability: With `using`, the new name comes first rather than being embedded somewhere in a declaration.
14865 Generality: `using` can be used for template aliases, whereas `typedef`s can't easily be templates.
14866 Uniformity: `using` is syntactically similar to `auto`.
14868 ##### Example
14870     typedef int (*PFI)(int);   // OK, but convoluted
14872     using PFI2 = int (*)(int);   // OK, preferred
14874     template<typename T>
14875     typedef int (*PFT)(T);      // error
14877     template<typename T>
14878     using PFT2 = int (*)(T);   // OK
14880 ##### Enforcement
14882 * Flag uses of `typedef`. This will give a lot of "hits" :-(
14884 ### <a name="Rt-deduce"></a>T.44: Use function templates to deduce class template argument types (where feasible)
14886 ##### Reason
14888 Writing the template argument types explicitly can be tedious and unnecessarily verbose.
14890 ##### Example
14892     tuple<int, string, double> t1 = {1, "Hamlet", 3.14};   // explicit type
14893     auto t2 = make_tuple(1, "Ophelia"s, 3.14);         // better; deduced type
14895 Note the use of the `s` suffix to ensure that the string is a `std::string`, rather than a C-style string.
14897 ##### Note
14899 Since you can trivially write a `make_T` function, so could the compiler. Thus, `make_T` functions may become redundant in the future.
14901 ##### Exception
14903 Sometimes there isn't a good way of getting the template arguments deduced and sometimes, you want to specify the arguments explicitly:
14905     vector<double> v = { 1, 2, 3, 7.9, 15.99 };
14906     list<Record*> lst;
14908 ##### Note
14910 Note that C++17 will make this rule redundant by allowing the template arguments to be deduced directly from constructor arguments:
14911 [Template parameter deduction for constructors (Rev. 3)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r1.html).
14912 For example:
14914     tuple t1 = {1, "Hamlet"s, 3.14}; // deduced: tuple<int, string, double>
14916 ##### Enforcement
14918 Flag uses where an explicitly specialized type exactly matches the types of the arguments used.
14920 ### <a name="Rt-regular"></a>T.46: Require template arguments to be at least `Regular` or `SemiRegular`
14922 ##### Reason
14924  Readability.
14925  Preventing surprises and errors.
14926  Most uses support that anyway.
14928 ##### Example
14930     class X {
14931             // ...
14932     public:
14933         explicit X(int);
14934         X(const X&);            // copy
14935         X operator=(const X&);
14936         X(X&&);                 // move
14937         X& operator=(X&&);
14938         ~X();
14939         // ... no more constructors ...
14940     };
14942     X x {1};    // fine
14943     X y = x;      // fine
14944     std::vector<X> v(10); // error: no default constructor
14946 ##### Note
14948 Semiregular requires default constructible.
14950 ##### Enforcement
14952 * Flag types that are not at least `SemiRegular`.
14954 ### <a name="Rt-visible"></a>T.47: Avoid highly visible unconstrained templates with common names
14956 ##### Reason
14958  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.
14959  This is particularly annoying/dangerous when ADL is used.
14960  Common names make this problem more likely.
14962 ##### Example
14964     namespace Bad {
14965         struct S { int m; };
14966         template<typename T1, typename T2>
14967         bool operator==(T1, T2) { cout << "Bad\n"; return true; }
14968     }
14970     namespace T0 {
14971         bool operator==(int, Bad::S) { cout << "T0\n"; return true; }  // compare to int
14973         void test()
14974         {
14975             Bad::S bad{ 1 };
14976             vector<int> v(10);
14977             bool b = 1 == bad;
14978             bool b2 = v.size() == bad;
14979         }
14980     }
14982 This prints `T0` and `Bad`.
14984 Now the `==` in `Bad` was designed to cause trouble, but would you have spotted the problem in real code?
14985 The problem is that `v.size()` returns an `unsigned` integer so that a conversion is needed to call the local `==`;
14986 the `==` in `Bad` requires no conversions.
14987 Realistic types, such as the standard library iterators can be made to exhibit similar anti-social tendencies.
14989 ##### Note
14991 If an unconstrained template is defined in the same namespace as a type,
14992 that unconstrained template can be found by ADL (as happened in the example).
14993 That is, it is highly visible.
14995 ##### Note
14997 This rule should not be necessary, but the committee cannot agree to exclude unconstrained templated from ADL.
14999 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`.
15002 ##### Enforcement
15004 Flag templates defined in a namespace where concrete types are also defined (maybe not feasible until we have concepts).
15007 ### <a name="Rt-concept-def"></a>T.48: If your compiler does not support concepts, fake them with `enable_if`
15009 ##### Reason
15011 Because that's the best we can do without direct concept support.
15012 `enable_if` can be used to conditionally define functions and to select among a set of functions.
15014 ##### Example
15016     enable_if<???>
15018 ##### Note
15020 Beware of [complementary constraints](# T.25).
15021 Faking concept overloading using `enable_if` sometimes forces us to use that error-prone design technique.
15023 ##### Enforcement
15027 ### <a name="Rt-erasure"></a>T.49: Where possible, avoid type-erasure
15029 ##### Reason
15031 Type erasure incurs an extra level of indirection by hiding type information behind a separate compilation boundary.
15033 ##### Example
15035     ???
15037 **Exceptions**: Type erasure is sometimes appropriate, such as for `std::function`.
15039 ##### Enforcement
15044 ##### Note
15047 ## <a name="SS-temp-def"></a>T.def: Template definitions
15049 A template definition (class or function) can contain arbitrary code, so only a comprehensive review of C++ programming techniques would cover this topic.
15050 However, this section focuses on what is specific to template implementation.
15051 In particular, it focuses on a template definition's dependence on its context.
15053 ### <a name="Rt-depend"></a>T.60: Minimize a template's context dependencies
15055 ##### Reason
15057 Eases understanding.
15058 Minimizes errors from unexpected dependencies.
15059 Eases tool creation.
15061 ##### Example
15063     template<typename C>
15064     void sort(C& c)
15065     {
15066         std::sort(begin(c), end(c)); // necessary and useful dependency
15067     }
15069     template<typename Iter>
15070     Iter algo(Iter first, Iter last) {
15071         for (; first != last; ++first) {
15072             auto x = sqrt(*first); // potentially surprising dependency: which sqrt()?
15073             helper(first, x);      // potentially surprising dependency:
15074                                    // helper is chosen based on first and x
15075             TT var = 7;            // potentially surprising dependency: which TT?
15076         }
15077     }
15079 ##### Note
15081 Templates typically appear in header files so their context dependencies are more vulnerable to `#include` order dependencies than functions in `.cpp` files.
15083 ##### Note
15085 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.
15086 For example, an algorithm usually uses other algorithms and invoke operations that does not exclusively operate on arguments.
15087 And don't get us started on macros!
15088 See also [T.69](#Rt-customization)
15090 ##### Enforcement
15092 ??? Tricky
15094 ### <a name="Rt-scary"></a>T.61: Do not over-parameterize members (SCARY)
15096 ##### Reason
15098 A member that does not depend on a template parameter cannot be used except for a specific template argument.
15099 This limits use and typically increases code size.
15101 ##### Example, bad
15103     template<typename T, typename A = std::allocator{}>
15104         // requires Regular<T> && Allocator<A>
15105     class List {
15106     public:
15107         struct Link {   // does not depend on A
15108             T elem;
15109             T* pre;
15110             T* suc;
15111         };
15113         using iterator = Link*;
15115         iterator first() const { return head; }
15117         // ...
15118     private:
15119         Link* head;
15120     };
15122     List<int> lst1;
15123     List<int, My_allocator> lst2;
15125     ???
15127 This looks innocent enough, but ???
15129     template<typename T>
15130     struct Link {
15131         T elem;
15132         T* pre;
15133         T* suc;
15134     };
15136     template<typename T, typename A = std::allocator{}>
15137         // requires Regular<T> && Allocator<A>
15138     class List2 {
15139     public:
15140         using iterator = Link<T>*;
15142         iterator first() const { return head; }
15144         // ...
15145     private:
15146         Link* head;
15147     };
15149     List<int> lst1;
15150     List<int, My_allocator> lst2;
15152     ???
15154 ##### Enforcement
15156 * Flag member types that do not depend on every template argument
15157 * Flag member functions that do not depend on every template argument
15159 ### <a name="Rt-nondependent"></a>T.62: Place non-dependent class template members in a non-templated base class
15161 ##### Reason
15163  Allow the base class members to be used without specifying template arguments and without template instantiation.
15165 ##### Example
15167     template<typename T>
15168     class Foo {
15169     public:
15170         enum { v1, v2 };
15171         // ...
15172     };
15176     struct Foo_base {
15177         enum { v1, v2 };
15178         // ...
15179     };
15181     template<typename T>
15182     class Foo : public Foo_base {
15183     public:
15184         // ...
15185     };
15187 ##### Note
15189 A more general version of this rule would be
15190 "If a template class member depends on only N template parameters out of M, place it in a base class with only N parameters."
15191 For N == 1, we have a choice of a base class of a class in the surrounding scope as in [T.61](#Rt-scary).
15193 ??? What about constants? class statics?
15195 ##### Enforcement
15197 * Flag ???
15199 ### <a name="Rt-specialization"></a>T.64: Use specialization to provide alternative implementations of class templates
15201 ##### Reason
15203 A template defines a general interface.
15204 Specialization offers a powerful mechanism for providing alternative implementations of that interface.
15206 ##### Example
15208     ??? string specialization (==)
15210     ??? representation specialization ?
15212 ##### Note
15216 ##### Enforcement
15220 ### <a name="Rt-tag-dispatch"></a>T.65: Use tag dispatch to provide alternative implementations of a function
15222 ##### Reason
15224 * A template defines a general interface.
15225 * Tag dispatch allows us to select implementations based on specific properties of an argument type.
15226 * Performance.
15228 ##### Example
15230 This is a simplified version of `std::copy` (ignoring the possibility of non-contiguous sequences)
15232     struct pod_tag {};
15233     struct non_pod_tag {};
15235     template<class T> struct copy_trait { using tag = non_pod_tag; };   // T is not "plain old data"
15237     template<> struct copy_trait<int> { using tag = pod_tag; };         // int is "plain old data"
15239     template<class Iter>
15240     Out copy_helper(Iter first, Iter last, Iter out, pod_tag)
15241     {
15242         // use memmove
15243     }
15245     template<class Iter>
15246     Out copy_helper(Iter first, Iter last, Iter out, non_pod_tag)
15247     {
15248         // use loop calling copy constructors
15249     }
15251     template<class Itert>
15252     Out copy(Iter first, Iter last, Iter out)
15253     {
15254         return copy_helper(first, last, out, typename copy_trait<Iter>::tag{})
15255     }
15257     void use(vector<int>& vi, vector<int>& vi2, vector<string>& vs, vector<string>& vs2)
15258     {
15259         copy(vi.begin(), vi.end(), vi2.begin()); // uses memmove
15260         copy(vs.begin(), vs.end(), vs2.begin()); // uses a loop calling copy constructors
15261     }
15263 This is a general and powerful technique for compile-time algorithm selection.
15265 ##### Note
15267 When `concept`s become widely available such alternatives can be distinguished directly:
15269     template<class Iter>
15270         requires Pod<Value_type<iter>>
15271     Out copy_helper(In, first, In last, Out out)
15272     {
15273         // use memmove
15274     }
15276     template<class Iter>
15277     Out copy_helper(In, first, In last, Out out)
15278     {
15279         // use loop calling copy constructors
15280     }
15282 ##### Enforcement
15287 ### <a name="Rt-specialization2"></a>T.67: Use specialization to provide alternative implementations for irregular types
15289 ##### Reason
15291  ???
15293 ##### Example
15295     ???
15297 ##### Enforcement
15301 ### <a name="Rt-cast"></a>T.68: Use `{}` rather than `()` within templates to avoid ambiguities
15303 ##### Reason
15305  `()` is vulnerable to grammar ambiguities.
15307 ##### Example
15309     template<typename T, typename U>
15310     void f(T t, U u)
15311     {
15312         T v1(x);    // is v1 a function of a variable?
15313         T v2 {x};   // variable
15314         auto x = T(u);  // construction or cast?
15315     }
15317     f(1, "asdf"); // bad: cast from const char* to int
15319 ##### Enforcement
15321 * flag `()` initializers
15322 * flag function-style casts
15325 ### <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
15327 ##### Reason
15329 * Provide only intended flexibility.
15330 * Avoid vulnerability to accidental environmental changes.
15332 ##### Example
15334 There are three major ways to let calling code customize a template.
15336     template<class T>
15337         // Call a member function
15338     void test1(T t)
15339     {
15340         t.f();    // require T to provide f()
15341     }
15343     template<class T>
15344     void test2(T t)
15345         // Call a nonmember function without qualification
15346     {
15347         f(t);  // require f(/*T*/) be available in caller's scope or in T's namespace
15348     }
15350     template<class T>
15351     void test3(T t)
15352         // Invoke a "trait"
15353     {
15354         test_traits<T>::f(t); // require customizing test_traits<>
15355                               // to get non-default functions/types
15356     }
15358 A trait is usually a type alias to compute a type,
15359 a `constexpr` function to compute a value,
15360 or a traditional traits template to be specialized on the user's type.
15362 ##### Note
15364 If you intend to call your own helper function `helper(t)` with a value `t` that depends on a template type parameter,
15365 put it in a `::detail` namespace and qualify the call as `detail::helper(t);`.
15366 An unqualified call becomes a customization point where any function `helper` in the namespace of `t`'s type can be invoked;
15367 this can cause problems like [unintentionally invoking unconstrained function templates](#Rt-unconstrained-adl).
15370 ##### Enforcement
15372 * 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.
15375 ## <a name="SS-temp-hier"></a>T.temp-hier: Template and hierarchy rules:
15377 Templates are the backbone of C++'s support for generic programming and class hierarchies the backbone of its support
15378 for object-oriented programming.
15379 The two language mechanisms can be used effectively in combination, but a few design pitfalls must be avoided.
15381 ### <a name="Rt-hier"></a>T.80: Do not naively templatize a class hierarchy
15383 ##### Reason
15385 Templating a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat.
15387 ##### Example, bad
15389     template<typename T>
15390     struct Container {         // an interface
15391         virtual T* get(int i);
15392         virtual T* first();
15393         virtual T* next();
15394         virtual void sort();
15395     };
15397     template<typename T>
15398     class Vector : public Container<T> {
15399     public:
15400         // ...
15401     };
15403     vector<int> vi;
15404     vector<string> vs;
15406 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.
15408 Given this, the compiler cannot know if `vector<int>::sort()` is called, so it must generate code for it.
15409 Similar for `vector<string>::sort()`.
15410 Unless those two functions are called that's code bloat.
15411 Imagine what this would do to a class hierarchy with dozens of member functions and dozens of derived classes with many instantiations.
15413 ##### Note
15415 In many cases you can provide a stable interface by not parameterizing a base;
15416 see ["stable base"](#Rt-abi) and [OO and GP](#Rt-generic-oo)
15418 ##### Enforcement
15420 * Flag virtual functions that depend on a template argument. ??? False positives
15422 ### <a name="Rt-array"></a>T.81: Do not mix hierarchies and arrays
15424 ##### Reason
15426 An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results.
15428 ##### Example
15430 Assume that `Apple` and `Pear` are two kinds of `Fruit`s.
15432     void maul(Fruit* p)
15433     {
15434         *p = Pear{};     // put a Pear into *p
15435         p[1] = Pear{};   // put a Pear into p[2]
15436     }
15438     Apple aa [] = { an_apple, another_apple };   // aa contains Apples (obviously!)
15440     maul(aa);
15441     Apple& a0 = &aa[0];   // a Pear?
15442     Apple& a1 = &aa[1];   // a Pear?
15444 Probably, `aa[0]` will be a `Pear` (without the use of a cast!).
15445 If `sizeof(Apple) != sizeof(Pear)` the access to `aa[1]` will not be aligned to the proper start of an object in the array.
15446 We have a type violation and possibly (probably) a memory corruption.
15447 Never write such code.
15449 Note that `maul()` violates the a `T*` points to an individual object [Rule](#???).
15451 **Alternative**: Use a proper (templatized) container:
15453     void maul2(Fruit* p)
15454     {
15455         *p = Pear{};   // put a Pear into *p
15456     }
15458     vector<Apple> va = { an_apple, another_apple };   // va contains Apples (obviously!)
15460     maul2(va);       // error: cannot convert a vector<Apple> to a Fruit*
15461     maul2(&va[0]);   // you asked for it
15463     Apple& a0 = &va[0];   // a Pear?
15465 Note that the assignment in `maul2()` violated the no-slicing [Rule](#???).
15467 ##### Enforcement
15469 * Detect this horror!
15471 ### <a name="Rt-linear"></a>T.82: Linearize a hierarchy when virtual functions are undesirable
15473 ##### Reason
15475  ???
15477 ##### Example
15479     ???
15481 ##### Enforcement
15485 ### <a name="Rt-virtual"></a>T.83: Do not declare a member function template virtual
15487 ##### Reason
15489 C++ does not support that.
15490 If it did, vtbls could not be generated until link time.
15491 And in general, implementations must deal with dynamic linking.
15493 ##### Example, don't
15495     class Shape {
15496         // ...
15497         template<class T>
15498         virtual bool intersect(T* p);   // error: template cannot be virtual
15499     };
15501 ##### Note
15503 We need a rule because people keep asking about this
15505 ##### Alternative
15507 Double dispatch, visitors, calculate which function to call
15509 ##### Enforcement
15511 The compiler handles that.
15513 ### <a name="Rt-abi"></a>T.84: Use a non-template core implementation to provide an ABI-stable interface
15515 ##### Reason
15517 Improve stability of code.
15518 Avoid code bloat.
15520 ##### Example
15522 It could be a base class:
15524     struct Link_base {   // stable
15525         Link* suc;
15526         Link* pre;
15527     };
15529     template<typename T>   // templated wrapper to add type safety
15530     struct Link : Link_base {
15531         T val;
15532     };
15534     struct List_base {
15535         Link_base* first;   // first element (if any)
15536         int sz;             // number of elements
15537         void add_front(Link_base* p);
15538         // ...
15539     };
15541     template<typename T>
15542     class List : List_base {
15543     public:
15544         void put_front(const T& e) { add_front(new Link<T>{e}); }   // implicit cast to Link_base
15545         T& front() { static_cast<Link<T>*>(first).val; }   // explicit cast back to Link<T>
15546         // ...
15547     };
15549     List<int> li;
15550     List<string> ls;
15552 Now there is only one copy of the operations linking and unlinking elements of a `List`.
15553 The `Link` and `List` classes do nothing but type manipulation.
15555 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.
15557 **Alternative**: Use a [PIMPL](#???) implementation.
15559 ##### Enforcement
15563 ## <a name="SS-variadic"></a>T.var: Variadic template rules
15567 ### <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
15569 ##### Reason
15571 Variadic templates is the most general mechanism for that, and is both efficient and type-safe. Don't use C varargs.
15573 ##### Example
15575     ??? printf
15577 ##### Enforcement
15579 * Flag uses of `va_arg` in user code.
15581 ### <a name="Rt-variadic-pass"></a>T.101: ??? How to pass arguments to a variadic template ???
15583 ##### Reason
15585  ???
15587 ##### Example
15589     ??? beware of move-only and reference arguments
15591 ##### Enforcement
15595 ### <a name="Rt-variadic-process"></a>T.102: How to process arguments to a variadic template
15597 ##### Reason
15599  ???
15601 ##### Example
15603     ??? forwarding, type checking, references
15605 ##### Enforcement
15609 ### <a name="Rt-variadic-not"></a>T.103: Don't use variadic templates for homogeneous argument lists
15611 ##### Reason
15613 There are more precise ways of specifying a homogeneous sequence, such as an `initializer_list`.
15615 ##### Example
15617     ???
15619 ##### Enforcement
15623 ## <a name="SS-meta"></a>T.meta: Template metaprogramming (TMP)
15625 Templates provide a general mechanism for compile-time programming.
15627 Metaprogramming is programming where at least one input or one result is a type.
15628 Templates offer Turing-complete (modulo memory capacity) duck typing at compile time.
15629 The syntax and techniques needed are pretty horrendous.
15631 ### <a name="Rt-metameta"></a>T.120: Use template metaprogramming only when you really need to
15633 ##### Reason
15635 Template metaprogramming is hard to get right, slows down compilation, and is often very hard to maintain.
15636 However, there are real-world examples where template metaprogramming provides better performance that any alternative short of expert-level assembly code.
15637 Also, there are real-world examples where template metaprogramming expresses the fundamental ideas better than run-time code.
15638 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++.
15640 ##### Example, bad
15642     ???
15644 ##### Example, bad
15646     enable_if
15648 Instead, use concepts. But see [How to emulate concepts if you don't have language support](#Rt-emulate).
15650 ##### Example
15652     ??? good
15654 **Alternative**: If the result is a value, rather than a type, use a [`constexpr` function](#Rt-fct).
15656 ##### Note
15658 If you feel the need to hide your template metaprogramming in macros, you have probably gone too far.
15660 ### <a name="Rt-emulate"></a>T.121: Use template metaprogramming primarily to emulate concepts
15662 ##### Reason
15664 Until concepts become generally available, we need to emulate them using TMP.
15665 Use cases that require concepts (e.g. overloading based on concepts) are among the most common (and simple) uses of TMP.
15667 ##### Example
15669     template<typename Iter>
15670         /*requires*/ enable_if<random_access_iterator<Iter>, void>
15671     advance(Iter p, int n) { p += n; }
15673     template<typename Iter>
15674         /*requires*/ enable_if<forward_iterator<Iter>, void>
15675     advance(Iter p, int n) { assert(n >= 0); while (n--) ++p;}
15677 ##### Note
15679 Such code is much simpler using concepts:
15681     void advance(RandomAccessIterator p, int n) { p += n; }
15683     void advance(ForwardIterator p, int n) { assert(n >= 0); while (n--) ++p;}
15685 ##### Enforcement
15689 ### <a name="Rt-tmp"></a>T.122: Use templates (usually template aliases) to compute types at compile time
15691 ##### Reason
15693 Template metaprogramming is the only directly supported and half-way principled way of generating types at compile time.
15695 ##### Note
15697 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
15699 ##### Example
15701     ??? big object / small object optimization
15703 ##### Enforcement
15707 ### <a name="Rt-fct"></a>T.123: Use `constexpr` functions to compute values at compile time
15709 ##### Reason
15711 A function is the most obvious and conventional way of expressing the computation of a value.
15712 Often a `constexpr` function implies less compile-time overhead than alternatives.
15714 ##### Note
15716 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
15718 ##### Example
15720     template<typename T>
15721         // requires Number<T>
15722     constexpr T pow(T v, int n)   // power/exponential
15723     {
15724         T res = 1;
15725         while (n--) res *= v;
15726         return res;
15727     }
15729     constexpr auto f7 = pow(pi, 7);
15731 ##### Enforcement
15733 * Flag template metaprograms yielding a value. These should be replaced with `constexpr` functions.
15735 ### <a name="Rt-std-tmp"></a>T.124: Prefer to use standard-library TMP facilities
15737 ##### Reason
15739 Facilities defined in the standard, such as `conditional`, `enable_if`, and `tuple`, are portable and can be assumed to be known.
15741 ##### Example
15743     ???
15745 ##### Enforcement
15749 ### <a name="Rt-lib"></a>T.125: If you need to go beyond the standard-library TMP facilities, use an existing library
15751 ##### Reason
15753 Getting advanced TMP facilities is not easy and using a library makes you part of a (hopefully supportive) community.
15754 Write your own "advanced TMP support" only if you really have to.
15756 ##### Example
15758     ???
15760 ##### Enforcement
15764 ## <a name="SS-temp-other"></a>Other template rules
15766 ### <a name="Rt-name"></a>T.140: Name all operations with potential for reuse
15768 ##### Reason
15770 Documentation, readability, opportunity for reuse.
15772 ##### Example
15774     struct Rec {
15775         string name;
15776         string addr;
15777         int id;         // unique identifier
15778     };
15780     bool same(const Rec& a, const Rec& b)
15781     {
15782         return a.id == b.id;
15783     }
15785     vector<Rec*> find_id(const string& name);    // find all records for "name"
15787     auto x = find_if(vr.begin(), vr.end(),
15788         [&](Rec& r) {
15789             if (r.name.size() != n.size()) return false; // name to compare to is in n
15790             for (int i = 0; i < r.name.size(); ++i)
15791                 if (tolower(r.name[i]) != tolower(n[i])) return false;
15792             return true;
15793         }
15794     );
15796 There is a useful function lurking here (case insensitive string comparison), as there often is when lambda arguments get large.
15798     bool compare_insensitive(const string& a, const string& b)
15799     {
15800         if (a.size() != b.size()) return false;
15801         for (int i = 0; i < a.size(); ++i) if (tolower(a[i]) != tolower(b[i])) return false;
15802         return true;
15803     }
15805     auto x = find_if(vr.begin(), vr.end(),
15806         [&](Rec& r) { compare_insensitive(r.name, n); }
15807     );
15809 Or maybe (if you prefer to avoid the implicit name binding to n):
15811     auto cmp_to_n = [&n](const string& a) { return compare_insensitive(a, n); };
15813     auto x = find_if(vr.begin(), vr.end(),
15814         [](const Rec& r) { return cmp_to_n(r.name); }
15815     );
15817 ##### Note
15819 whether functions, lambdas, or operators.
15821 ##### Exception
15823 * Lambdas logically used only locally, such as an argument to `for_each` and similar control flow algorithms.
15824 * Lambdas as [initializers](#???)
15826 ##### Enforcement
15828 * (hard) flag similar lambdas
15829 * ???
15831 ### <a name="Rt-lambda"></a>T.141: Use an unnamed lambda if you need a simple function object in one place only
15833 ##### Reason
15835 That makes the code concise and gives better locality than alternatives.
15837 ##### Example
15839     auto earlyUsersEnd = std::remove_if(users.begin(), users.end(),
15840                                         [](const User &a) { return a.id > 100; });
15843 ##### Exception
15845 Naming a lambda can be useful for clarity even if it is used only once.
15847 ##### Enforcement
15849 * Look for identical and near identical lambdas (to be replaced with named functions or named lambdas).
15851 ### <a name="Rt-var"></a>T.142?: Use template variables to simplify notation
15853 ##### Reason
15855 Improved readability.
15857 ##### Example
15859     ???
15861 ##### Enforcement
15865 ### <a name="Rt-nongeneric"></a>T.143: Don't write unintentionally nongeneric code
15867 ##### Reason
15869 Generality. Reusability. Don't gratuitously commit to details; use the most general facilities available.
15871 ##### Example
15873 Use `!=` instead of `<` to compare iterators; `!=` works for more objects because it doesn't rely on ordering.
15875     for (auto i = first; i < last; ++i) {   // less generic
15876         // ...
15877     }
15879     for (auto i = first; i != last; ++i) {   // good; more generic
15880         // ...
15881     }
15883 Of course, range-`for` is better still where it does what you want.
15885 ##### Example
15887 Use the least-derived class that has the functionality you need.
15889     class Base {
15890     public:
15891         Bar f();
15892         Bar g();
15893     };
15895     class Derived1 : public Base {
15896     public:
15897         Bar h();
15898     };
15900     class Derived2 : public Base {
15901     public:
15902         Bar j();
15903     };
15905     // bad, unless there is a specific reason for limiting to Derived1 objects only
15906     void my_func(Derived1& param)
15907     {
15908         use(param.f());
15909         use(param.g());
15910     }
15912     // good, uses only Base interface so only commit to that
15913     void my_func(Base& param)
15914     {
15915         use(param.f());
15916         use(param.g());
15917     }
15919 ##### Enforcement
15921 * Flag comparison of iterators using `<` instead of `!=`.
15922 * 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.
15923 * Flag functions that take a pointer or reference to a more-derived type but only use functions declared in a base type.
15925 ### <a name="Rt-specialize-function"></a>T.144: Don't specialize function templates
15927 ##### Reason
15929 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.
15931 ##### Example
15933     ???
15935 **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).
15937 ##### Enforcement
15939 * Flag all specializations of a function template. Overload instead.
15942 ### <a name="Rt-check-class"></a>T.150: Check that a class matches a concept using `static_assert`
15944 ##### Reason
15946 If you intend for a class to match a concept, verifying that early saves users pain.
15948 ###### Example
15950     class X {
15951         X() = delete;
15952         X(const X&) = default;
15953         X(X&&) = default;
15954         X& operator=(const X&) = default;
15955         // ...
15956     };
15958 Somewhere, possibly in an implementation file, let the compiler check the desired properties of `X`:
15960     static_assert(Default_constructible<X>);    // error: X has no default constructor
15961     static_assert(Copyable<X>);                 // error: we forgot to define X's move constructor
15964 ###### Enforcement
15966 Not feasible.
15968 # <a name="S-cpl"></a>CPL: C-style programming
15970 C and C++ are closely related languages.
15971 They both originate in "Classic C" from 1978 and have evolved in ISO committees since then.
15972 Many attempts have been made to keep them compatible, but neither is a subset of the other.
15974 C rule summary:
15976 * [CPL.1: Prefer C++ to C](#Rcpl-C)
15977 * [CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++](#Rcpl-subset)
15978 * [CPL.3: If you must use C for interfaces, use C++ in the code using such interfaces](#Rcpl-interface)
15980 ### <a name="Rcpl-C"></a>CPL.1: Prefer C++ to C
15982 ##### Reason
15984 C++ provides better type checking and more notational support.
15985 It provides better support for high-level programming and often generates faster code.
15987 ##### Example
15989     char ch = 7;
15990     void* pv = &ch;
15991     int* pi = pv;   // not C++
15992     *pi = 999;      // overwrite sizeof(int) bytes near &ch
15994 The rules for implicit casting to and from `void*` in C are subtle and unenforced.
15995 In particular, this example violates a rule against converting to a type with stricter alignment.
15997 ##### Enforcement
15999 Use a C++ compiler.
16001 ### <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++
16003 ##### Reason
16005 That subset can be compiled with both C and C++ compilers, and when compiled as C++ is better type checked than "pure C."
16007 ##### Example
16009     int* p1 = malloc(10 * sizeof(int));                      // not C++
16010     int* p2 = static_cast<int*>(malloc(10 * sizeof(int)));   // not C, C-style C++
16011     int* p3 = new int[10];                                   // not C
16012     int* p4 = (int*) malloc(10 * sizeof(int));               // both C and C++
16014 ##### Enforcement
16016 * Flag if using a build mode that compiles code as C.
16018   * The C++ compiler will enforce that the code is valid C++ unless you use C extension options.
16020 ### <a name="Rcpl-interface"></a>CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces
16022 ##### Reason
16024 C++ is more expressive than C and offers better support for many types of programming.
16026 ##### Example
16028 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.
16029 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.
16031 ##### Example
16033 You can call C from C++:
16035     // in C:
16036     double sqrt(double);
16038     // in C++:
16039     extern "C" double sqrt(double);
16041     sqrt(2);
16043 ##### Example
16045 You can call C++ from C:
16047     // in C:
16048     X call_f(struct Y*, int);
16050     // in C++:
16051     extern "C" X call_f(Y* p, int i)
16052     {
16053         return p->f(i);   // possibly a virtual function call
16054     }
16056 ##### Enforcement
16058 None needed
16060 # <a name="S-source"></a>SF: Source files
16062 Distinguish between declarations (used as interfaces) and definitions (used as implementations).
16063 Use header files to represent interfaces and to emphasize logical structure.
16065 Source file rule summary:
16067 * [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)
16068 * [SF.2: A `.h` file may not contain object definitions or non-inline function definitions](#Rs-inline)
16069 * [SF.3: Use `.h` files for all declarations used in multiple source files](#Rs-declaration-header)
16070 * [SF.4: Include `.h` files before other declarations in a file](#Rs-include-order)
16071 * [SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface](#Rs-consistency)
16072 * [SF.6: Use `using`-directives for transition, for foundation libraries (such as `std`), or within a local scope](#Rs-using)
16073 * [SF.7: Don't put a `using`-directive in a header file](#Rs-using-directive)
16074 * [SF.8: Use `#include` guards for all `.h` files](#Rs-guards)
16075 * [SF.9: Avoid cyclic dependencies among source files](#Rs-cycles)
16077 * [SF.20: Use `namespace`s to express logical structure](#Rs-namespace)
16078 * [SF.21: Don't use an unnamed (anonymous) namespace in a header](#Rs-unnamed)
16079 * [SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities](#Rs-unnamed2)
16081 ### <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
16083 ##### Reason
16085 It's a longstanding convention.
16086 But consistency is more important, so if your project uses something else, follow that.
16088 ##### Note
16090 This convention reflects a common use pattern:
16091 Headers are more often shared with C to compile as both C++ and C, which typically uses `.h`,
16092 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.
16093 On the other hand, implementation files are rarely shared with C and so should typically be distinguished from `.c` files,
16094 so it's normally best to name all C++ implementation files something else (such as `.cpp`).
16096 The specific names `.h` and `.cpp` are not required (just recommended as a default) and other names are in widespread use.
16097 Examples are `.hh`, `.C`, and `.cxx`. Use such names equivalently.
16098 In this document, we refer to `.h` and `.cpp` as a shorthand for header and implementation files,
16099 even though the actual extension may be different.
16101 Your IDE (if you use one) may have strong opinions about suffices.
16103 ##### Example
16105     // foo.h:
16106     extern int a;   // a declaration
16107     extern void foo();
16109     // foo.cpp:
16110     int a;   // a definition
16111     void foo() { ++a; }
16113 `foo.h` provides the interface to `foo.cpp`. Global variables are best avoided.
16115 ##### Example, bad
16117     // foo.h:
16118     int a;   // a definition
16119     void foo() { ++a; }
16121 `#include<foo.h>` twice in a program and you get a linker error for two one-definition-rule violations.
16123 ##### Enforcement
16125 * Flag non-conventional file names.
16126 * Check that `.h` and `.cpp` (and equivalents) follow the rules below.
16128 ### <a name="Rs-inline"></a>SF.2: A `.h` file may not contain object definitions or non-inline function definitions
16130 ##### Reason
16132 Including entities subject to the one-definition rule leads to linkage errors.
16134 ##### Example
16136     // file.h:
16137     namespace Foo {
16138         int x = 7;
16139         int xx() { return x+x; }
16140     }
16142     // file1.cpp:
16143     #include<file.h>
16144     // ... more ...
16146      // file2.cpp:
16147     #include<file.h>
16148     // ... more ...
16150 Linking `file1.cpp` and `file2.cpp` will give two linker errors.
16152 **Alternative formulation**: A `.h` file must contain only:
16154 * `#include`s of other `.h` files (possibly with include guards)
16155 * templates
16156 * class definitions
16157 * function declarations
16158 * `extern` declarations
16159 * `inline` function definitions
16160 * `constexpr` definitions
16161 * `const` definitions
16162 * `using` alias definitions
16163 * ???
16165 ##### Enforcement
16167 Check the positive list above.
16169 ### <a name="Rs-declaration-header"></a>SF.3: Use `.h` files for all declarations used in multiple source files
16171 ##### Reason
16173 Maintainability. Readability.
16175 ##### Example, bad
16177     // bar.cpp:
16178     void bar() { cout << "bar\n"; }
16180     // foo.cpp:
16181     extern void bar();
16182     void foo() { bar(); }
16184 A maintainer of `bar` cannot find all declarations of `bar` if its type needs changing.
16185 The user of `bar` cannot know if the interface used is complete and correct. At best, error messages come (late) from the linker.
16187 ##### Enforcement
16189 * Flag declarations of entities in other source files not placed in a `.h`.
16191 ### <a name="Rs-include-order"></a>SF.4: Include `.h` files before other declarations in a file
16193 ##### Reason
16195 Minimize context dependencies and increase readability.
16197 ##### Example
16199     #include<vector>
16200     #include<algorithm>
16201     #include<string>
16203     // ... my code here ...
16205 ##### Example, bad
16207     #include<vector>
16209     // ... my code here ...
16211     #include<algorithm>
16212     #include<string>
16214 ##### Note
16216 This applies to both `.h` and `.cpp` files.
16218 ##### Note
16220 There is an argument for insulating code from declarations and macros in header files by `#including` headers *after* the code we want to protect
16221 (as in the example labeled "bad").
16222 However
16224 * that only works for one file (at one level): Use that technique in a header included with other headers and the vulnerability reappears.
16225 * a namespace (an "implementation namespace") can protect against many context dependencies.
16226 * full protection and flexibility require [modules](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4592.pdf).
16227 [See also](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0141r0.pdf).
16230 ##### Enforcement
16232 Easy.
16234 ### <a name="Rs-consistency"></a>SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface
16236 ##### Reason
16238 This enables the compiler to do an early consistency check.
16240 ##### Example, bad
16242     // foo.h:
16243     void foo(int);
16244     int bar(long);
16245     int foobar(int);
16247     // foo.cpp:
16248     void foo(int) { /* ... */ }
16249     int bar(double) { /* ... */ }
16250     double foobar(int);
16252 The errors will not be caught until link time for a program calling `bar` or `foobar`.
16254 ##### Example
16256     // foo.h:
16257     void foo(int);
16258     int bar(long);
16259     int foobar(int);
16261     // foo.cpp:
16262     #include<foo.h>
16264     void foo(int) { /* ... */ }
16265     int bar(double) { /* ... */ }
16266     double foobar(int);   // error: wrong return type
16268 The return-type error for `foobar` is now caught immediately when `foo.cpp` is compiled.
16269 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.
16271 ##### Enforcement
16275 ### <a name="Rs-using"></a>SF.6: Use `using`-directives for transition, for foundation libraries (such as `std`), or within a local scope
16277 ##### Reason
16279  ???
16281 ##### Example
16283     ???
16285 ##### Enforcement
16289 ### <a name="Rs-using-directive"></a>SF.7: Don't put a `using`-directive in a header file
16291 ##### Reason
16293 Doing so takes away an `#include`r's ability to effectively disambiguate and to use alternatives.
16295 ##### Example
16297     ???
16299 ##### Enforcement
16303 ### <a name="Rs-guards"></a>SF.8: Use `#include` guards for all `.h` files
16305 ##### Reason
16307 To avoid files being `#include`d several times.
16309 ##### Example
16311     // file foobar.h:
16312     #ifndef FOOBAR_H
16313     #define FOOBAR_H
16314     // ... declarations ...
16315     #endif // FOOBAR_H
16317 ##### Enforcement
16319 Flag `.h` files without `#include` guards.
16321 ### <a name="Rs-cycles"></a>SF.9: Avoid cyclic dependencies among source files
16323 ##### Reason
16325 Cycles complicates comprehension and slows down compilation.
16326 Complicates conversion to use language-supported modules (when they become available).
16328 ##### Note
16330 Eliminate cycles; don't just break them with `#include` guards.
16332 ##### Example, bad
16334     // file1.h:
16335     #include "file2.h"
16337     // file2.h:
16338     #include "file3.h"
16340     // file3.h:
16341     #include "file1.h"
16343 ##### Enforcement
16345 Flag all cycles.
16347 ### <a name="Rs-namespace"></a>SF.20: Use `namespace`s to express logical structure
16349 ##### Reason
16351  ???
16353 ##### Example
16355     ???
16357 ##### Enforcement
16361 ### <a name="Rs-unnamed"></a>SF.21: Don't use an unnamed (anonymous) namespace in a header
16363 ##### Reason
16365 It is almost always a bug to mention an unnamed namespace in a header file.
16367 ##### Example
16369     ???
16371 ##### Enforcement
16373 * Flag any use of an anonymous namespace in a header file.
16375 ### <a name="Rs-unnamed2"></a>SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities
16377 ##### Reason
16379 Nothing external can depend on an entity in a nested unnamed namespace.
16380 Consider putting every definition in an implementation source file in an unnamed namespace unless that is defining an "external/exported" entity.
16382 ##### Example
16384 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.
16386     ???
16388 ##### Enforcement
16390 * ???
16392 # <a name="S-stdlib"></a>SL: The Standard Library
16394 Using only the bare language, every task is tedious (in any language).
16395 Using a suitable library any task can be reasonably simple.
16397 The standard library has steadily grown over the years.
16398 Its description in the standard is now larger than that of the language features.
16399 So, it is likely that this library section of the guidelines will eventually grow in size to equal or exceed all the rest.
16401 << ??? We need another level of rule numbering ??? >>
16403 C++ Standard library component summary:
16405 * [SL.con: Containers](#SS-con)
16406 * [SL.str: String](#SS-string)
16407 * [SL.io: Iostream](#SS-io)
16408 * [SL.regex: Regex](#SS-regex)
16409 * [SL.chrono: Time](#SS-chrono)
16410 * [SL.C: The C standard library](#SS-clib)
16412 Standard-library rule summary:
16414 * [SL.1: Use libraries wherever possible](#Rsl-lib)
16415 * [SL.2: Prefer the standard library to other libraries](#Rsl-sl)
16416 * ???
16418 ### <a name="Rsl-lib"></a>SL.1:  Use libraries wherever possible
16420 ##### Reason
16422 Save time. Don't re-invent the wheel.
16423 Don't replicate the work of others.
16424 Benefit from other people's work when they make improvements.
16425 Help other people when you make improvements.
16427 ### <a name="Rsl-sl"></a>SL.2: Prefer the standard library to other libraries
16429 ##### Reason
16431 More people know the standard library.
16432 It is more likely to be stable, well-maintained, and widely available than your own code or most other libraries.
16434 ## <a name="SS-con"></a>SL.con: Containers
16438 Container rule summary:
16440 * [SL.con.1: Prefer using STL `array` or `vector` instead of a C array](#Rsl-arrays)
16441 * [SL.con.2: Prefer using STL `vector` by default unless you have a reason to use a different container](#Rsl-vector)
16442 *  ???
16444 ### <a name="Rsl-arrays"></a>SL.con.1: Prefer using STL `array` or `vector` instead of a C array
16446 ##### Reason
16448 C arrays are less safe, and have no advantages over `array` and `vector`.
16449 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.
16450 Also, like a built-in array, a stack-allocated `std::array` keeps its elements on the stack.
16451 For a variable-length array, use `std::vector`, which additionally can change its size and handles memory allocation.
16453 ##### Example
16455     int v[SIZE];                        // BAD
16457     std::array<int, SIZE> w;             // ok
16459 ##### Example
16461     int* v = new int[initial_size];     // BAD, owning raw pointer
16462     delete[] v;                         // BAD, manual delete
16464     std::vector<int> w(initial_size);   // ok
16466 ##### Enforcement
16468 * 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`.
16470 ### <a name="Rsl-vector"></a>SL.con.2: Prefer using STL `vector` by default unless you have a reason to use a different container
16472 ##### Reason
16474 `vector` and `array` are the only standard containers that offer the fastest general-purpose access (random access, including being vectorization-friendly), the fastest default access pattern (begin-to-end or end-to-begin is prefetcher-friendly), and the lowest space overhead (contiguous layout has zero per-element overhead, which is cache-friendly).
16475 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`.
16477 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.
16479 ##### Note
16481 `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.
16483 ##### Exceptions
16485 If you have a good reason to use another container, use that instead. For example:
16487 * If `vector` suits your needs but you don't need the container to be variable size, use `array` instead.
16489 * 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.
16491 ##### Enforcement
16493 * 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.
16495 ## <a name="SS-string"></a>SL.str: String
16499 ## <a name="SS-io"></a>SL.io: Iostream
16503 Iostream rule summary:
16505 * [SL.io.1: Use character-level input only when you have to](#Rio-low)
16506 * [SL.io.2: When reading, always consider ill-formed input](#Rio-validate)
16507 * [???](#???)
16508 * [SL.io.50: Avoid `endl`](#Rio-endl)
16509 * [???](#???)
16511 ### <a name="Rio-low"></a>SL.io.1: Use character-level input only when you have to
16515 ### <a name="Rio-validate"></a>SL.io.2: When reading, always consider ill-formed input
16519 ### <a name="Rio-endl"></a>SL.io.50: Avoid `endl`
16521 ### Reason
16523 The `endl` manipulator is mostly equivalent to `'\n'` and `"\n"`;
16524 as most commonly used it simply slows down output by doing redundant `flush()`s.
16525 This slowdown can be significant compared to `printf`-style output.
16527 ##### Example
16529     cout << "Hello, World!" << endl;    // two output operations and a flush
16530     cout << "Hello, World!\n";          // one output operation and no flush
16532 ##### Note
16534 For `cin`/`cout` (and equivalent) interaction, there is no reason to flush; that's done automatically.
16535 For writing to a file, there is rarely a need to `flush`.
16537 ##### Note
16539 Apart from the (occasionally important) issue of performance,
16540 the choice between `'\n'` and `endl` is almost completely aesthetic.
16542 ## <a name="SS-regex"></a>SL.regex: Regex
16546 ## <a name="SS-chrono"></a>SL.chrono: Time
16550 ## <a name="SS-clib"></a>SL.C: The C standard library
16554 C standard library rule summary:
16556 * [???](#???)
16557 * [???](#???)
16558 * [???](#???)
16561 # <a name="S-A"></a>A: Architectural Ideas
16563 This section contains ideas about higher-level architectural ideas and libraries.
16565 Architectural rule summary:
16567 * [A.1 Separate stable from less stable part of code](#Ra-stable)
16568 * [A.2 Express potentially reusable parts as a library](#Ra-lib)
16569 * [A.4 There should be no cycles among libraries](#?Ra-dag)
16570 * [???](#???)
16571 * [???](#???)
16572 * [???](#???)
16573 * [???](#???)
16574 * [???](#???)
16575 * [???](#???)
16577 ### <a name="Ra-stable"></a>A.1 Separate stable from less stable part of code
16581 ### <a name="Ra-lib"></a>A.2 Express potentially reusable parts as a library
16583 ##### Reason
16585 ##### Note
16587 A library is a collection of declarations and definitions maintained, documented, and shipped together.
16588 A library could be a set of headers (a "header only library") or a set of headers plus a set of object files.
16589 A library can be statically or dynamically linked into a program, or it may be `#included`
16592 ### <a name="Ra-dag"></a>A.4 There should be no cycles among libraries
16594 ##### Reason
16596 * A cycle implies complication of the build process.
16597 * Cycles are hard to understand and may introduce indeterminism (unspecified behavior).
16599 ##### Note
16601 A library can contain cyclic references in the definition of its components.
16602 For example:
16604     ???
16606 However, a library should not depend on another that depends on it.
16609 # <a name="S-not"></a>NR: Non-Rules and myths
16611 This section contains rules and guidelines that are popular somewhere, but that we deliberately don't recommend.
16612 We know full well that there have been times and places where these rules made sense, and we have used them ourselves at times.
16613 However, in the context of the styles of programming we recommend and support with the guidelines, these "non-rules" would do harm.
16615 Even today, there can be contexts where the rules make sense.
16616 For example, lack of suitable tool support can make exceptions unsuitable in hard-real-time systems,
16617 but please don't blindly trust "common wisdom" (e.g., unsupported statements about "efficiency");
16618 such "wisdom" may be based on decades-old information or experienced from languages with very different properties than C++
16619 (e.g., C or Java).
16621 The positive arguments for alternatives to these non-rules are listed in the rules offered as "Alternatives".
16623 Non-rule summary:
16625 * [NR.1: Don't: All declarations should be at the top of a function](#Rnr-top)
16626 * [NR.2: Don't: Have only a single `return`-statement in a function](#Rnr-single-return)
16627 * [NR.3: Don't: Don't use exceptions](#Rnr-no-exceptions)
16628 * [NR.4: Don't: Place each class declaration in its own source file](#Rnr-lots-of-files)
16629 * [NR.5: Don't: Don't do substantive work in a constructor; instead use two-phase initialization](#Rnr-two-phase-init)
16630 * [NR.6: Don't: Place all cleanup actions at the end of a function and `goto exit`](#Rnr-goto-exit)
16631 * [NR.7: Don't: Make all data members `protected`](#Rnr-protected-data)
16632 * ???
16634 ### <a name="Rnr-top"></a>NR.1: Don't: All declarations should be at the top of a function
16636 ##### Reason (not to follow this rule)
16638 This rule is a legacy of old programming languages that didn't allow initialization of variables and constants after a statement.
16639 This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
16641 ##### Example, bad
16643     ???
16645 The larger the distance between the uninitialized variable and its use, the larger the chance of a bug.
16646 Fortunately, compilers catch many "used before set" errors.
16649 ##### Alternative
16651 * [Always initialize an object](#Res-always)
16652 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
16654 ### <a name="Rnr-single-return"></a>NR.2: Don't: Have only a single `return`-statement in a function
16656 ##### Reason (not to follow this rule)
16658 The single-return rule can lead to unnecessarily convoluted code and the introduction of extra state variables.
16659 In particular, the single-return rule makes it harder to concentrate error checking at the top of a function.
16661 ##### Example
16663     template<class T>
16664     //  requires Number<T>
16665     string sign(T x)
16666     {
16667         if (x < 0)
16668             return "negative";
16669         else if (x > 0)
16670             return "positive";
16671         return "zero";
16672     }
16674 to use a single return only we would have to do something like
16676     template<class T>
16677     //  requires Number<T>
16678     string sign(T x)        // bad
16679     {
16680         string res;
16681         if (x < 0)
16682             res = "negative";
16683         else if (x > 0)
16684             res = "positive";
16685         else
16686             res = "zero";
16687         return res;
16688     }
16690 This is both longer and likely to be less efficient.
16691 The larger and more complicated the function is, the more painful the workarounds get.
16692 Of course many simple functions will naturally have just one `return` because of their simpler inherent logic.
16694 ##### Example
16696     int index(const char* p)
16697     {
16698         if (p == nullptr) return -1;  // error indicator: alternatively "throw nullptr_error{}"
16699         // ... do a lookup to find the index for p
16700         return i;
16701     }
16703 If we applied the rule, we'd get something like
16705     int index2(const char* p)
16706     {
16707         int i;
16708         if (p == nullptr)
16709             i = -1;  // error indicator
16710         else {
16711             // ... do a lookup to find the index for p
16712         }
16713         return i;
16714     }
16716 Note that we (deliberately) violated the rule against uninitialized variables because this style commonly leads to that.
16717 Also, this style is a temptation to use the [goto exit](#Rnr-goto-exit) non-rule.
16719 ##### Alternative
16721 * Keep functions short and simple
16722 * Feel free to use multiple `return` statements (and to throw exceptions).
16724 ### <a name="Rnr-no-exceptions"></a>NR.3: Don't: Don't use exceptions
16726 ##### Reason (not to follow this rule)
16728 There seem to be three main reasons given for this non-rule:
16730 * exceptions are inefficient
16731 * exceptions lead to leaks and errors
16732 * exception performance is not predictable
16734 There is no way we can settle this issue to the satisfaction of everybody.
16735 After all, the discussions about exceptions have been going on for 40+ years.
16736 Some languages cannot be used without exceptions, but others do not support them.
16737 This leads to strong traditions for the use and non-use of exceptions, and to heated debates.
16739 However, we can briefly outline why we consider exceptions the best alternative for general-purpose programming
16740 and in the context of these guidelines.
16741 Simple arguments for and against are often inconclusive.
16742 There are specialized applications where exceptions indeed can be inappropriate
16743 (e.g., hard-real time systems without support for reliable estimates of the cost of handling an exception).
16745 Consider the major objections to exceptions in turn
16747 * Exceptions are inefficient:
16748 Compared to what?
16749 When comparing make sure that the same set of errors are handled and that they are handled equivalently.
16750 In particular, do not compare a program that immediately terminate on seeing an error with a program
16751 that carefully cleans up resources before logging an error.
16752 Yes, some systems have poor exception handling implementations; sometimes, such implementations force us to use
16753 other error-handling approaches, but that's not a fundamental problem with exceptions.
16754 When using an efficiency argument - in any context - be careful that you have good data that actually provides
16755 insight into the problem under discussion.
16756 * Exceptions lead to leaks and errors.
16757 They do not.
16758 If your program is a rat's nest of pointers without an overall strategy for resource management,
16759 you have a problem whatever you do.
16760 If your system consists of a million lines of such code,
16761 you probably will not be able to use exceptions,
16762 but that's a problem with excessive and undisciplined pointer use, rather than with exceptions.
16763 In our opinion, you need RAII to make exception-based error handling simple and safe -- simpler and safer than alternatives.
16764 * Exception performance is not predictable
16765 If you are in a hard-real-time system where you must guarantee completion of a task in a given time,
16766 you need tools to back up such guarantees.
16767 As far as we know such tools are not available (at least not to most programmers).
16769 Many, possibly most, problems with exceptions stem from historical needs to interact with messy old code.
16771 The fundamental arguments for the use of exceptions are
16773 * They clearly separates error return from ordinary return
16774 * They cannot be forgotten or ignored
16775 * They can be used systematically
16777 Remember
16779 * Exceptions are for reporting errors (in C++; other languages can have different uses for exceptions).
16780 * Exceptions are not for errors that can be handled locally.
16781 * Don't try to catch every exception in every function (that's tedious, clumsy, and leads to slow code).
16782 * Exceptions are not for errors that require instant termination of a module/system after a non-recoverable error.
16784 ##### Example
16786     ???
16788 ##### Alternative
16790 * [RAII](#Re-raii)
16791 * Contracts/assertions: Use GSL's `Expects` and `Ensures` (until we get language support for contracts)
16793 ### <a name="Rnr-lots-of-files"></a>NR.4: Don't: Place each class declaration in its own source file
16795 ##### Reason (not to follow this rule)
16797 The resulting number of files are hard to manage and can slow down compilation.
16798 Individual classes are rarely a good logical unit of maintenance and distribution.
16800 ##### Example
16802     ???
16804 ##### Alternative
16806 * Use namespaces containing logically cohesive sets of classes and functions.
16808 ### <a name="Rnr-two-phase-init"></a>NR.5: Don't: Don't do substantive work in a constructor; instead use two-phase initialization
16810 ##### Reason (not to follow this rule)
16812 Following this rule leads to weaker invariants,
16813 more complicated code (having to deal with semi-constructed objects),
16814 and errors (when we didn't deal correctly with semi-constructed objects consistently).
16816 ##### Example
16818     ???
16820 ##### Alternative
16822 * Always establish a class invariant in a constructor.
16823 * Don't define an object before it is needed.
16825 ### <a name="Rnr-goto-exit"></a>NR.6: Don't: Place all cleanup actions at the end of a function and `goto exit`
16827 ##### Reason (not to follow this rule)
16829 `goto` is error-prone.
16830 This technique is a pre-exception technique for RAII-like resource and error handling.
16832 ##### Example, bad
16834     void do_something(int n)
16835     {
16836         if (n < 100) goto exit;
16837         // ...
16838         int* p = (int*) malloc(n);
16839         // ...
16840         if (some_ error) goto_exit;
16841         // ...
16842     exit:
16843         free(p);
16844     }
16846 and spot the bug.
16848 ##### Alternative
16850 * Use exceptions and [RAII](#Re-raii)
16851 * for non-RAII resources, use [`finally`](#Re-finally).
16853 ### <a name="Rnr-protected-data"></a>NR.7: Don't: Make all data members `protected`
16855 ##### Reason (not to follow this rule)
16857 `protected` data is a source of errors.
16858 `protected` data can be manipulated from an unbounded amount of code in various places.
16859 `protected` data is the class hierarchy equivalent to global data.
16861 ##### Example
16863     ???
16865 ##### Alternative
16867 * [Make member data `public` or (preferably) `private`](#Rh-protected)
16870 # <a name="S-references"></a>RF: References
16872 Many coding standards, rules, and guidelines have been written for C++, and especially for specialized uses of C++.
16873 Many
16875 * focus on lower-level issues, such as the spelling of identifiers
16876 * are written by C++ novices
16877 * see "stopping programmers from doing unusual things" as their primary aim
16878 * aim at portability across many compilers (some 10 years old)
16879 * are written to preserve decades old code bases
16880 * aim at a single application domain
16881 * are downright counterproductive
16882 * are ignored (must be ignored by programmers to get their work done well)
16884 A bad coding standard is worse than no coding standard.
16885 However an appropriate set of guidelines are much better than no standards: "Form is liberating."
16887 Why can't we just have a language that allows all we want and disallows all we don't want ("a perfect language")?
16888 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.
16889 Also, your needs change over time and a general-purpose language is needed to allow you to adapt.
16890 A language that is ideal for today would be overly restrictive tomorrow.
16892 Coding guidelines adapt the use of a language to specific needs.
16893 Thus, there cannot be a single coding style for everybody.
16894 We expect different organizations to provide additions, typically with more restrictions and firmer style rules.
16896 Reference sections:
16898 * [RF.rules: Coding rules](#SS-rules)
16899 * [RF.books: Books with coding guidelines](#SS-books)
16900 * [RF.C++: C++ Programming (C++11/C++14)](#SS-Cplusplus)
16901 * [RF.web: Websites](#SS-web)
16902 * [RS.video: Videos about "modern C++"](#SS-vid)
16903 * [RF.man: Manuals](#SS-man)
16905 ## <a name="SS-rules"></a>RF.rules: Coding rules
16907 * [Boost Library Requirements and Guidelines](http://www.boost.org/development/requirements.html).
16908   ???.
16909 * [Bloomberg: BDE C++ Coding](https://github.com/bloomberg/bde/wiki/CodingStandards.pdf).
16910   Has a strong emphasis on code organization and layout.
16911 * Facebook: ???
16912 * [GCC Coding Conventions](https://gcc.gnu.org/codingconventions.html).
16913   C++03 and (reasonably) a bit backwards looking.
16914 * [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html).
16915   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.
16916 * [JSF++: JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS](http://www.stroustrup.com/JSF-AV-rules.pdf).
16917   Document Number 2RDU00001 Rev C. December 2005.
16918   For flight control software.
16919   For hard real time.
16920   This means that it is necessarily very restrictive ("if the program fails somebody dies").
16921   For example, no free store allocation or deallocation may occur after the plane takes off (no memory overflow and no fragmentation allowed).
16922   No exception may be used (because there was no available tool for guaranteeing that an exception would be handled within a fixed short time).
16923   Libraries used have to have been approved for mission critical applications.
16924   Any similarities to this set of guidelines are unsurprising because Bjarne Stroustrup was an author of JSF++.
16925   Recommended, but note its very specific focus.
16926 * [Mozilla Portability Guide](https://developer.mozilla.org/en-US/docs/Mozilla/C%2B%2B_Portability_Guide).
16927   As the name indicates, this aims for portability across many (old) compilers.
16928   As such, it is restrictive.
16929 * [Geosoft.no: C++ Programming Style Guidelines](http://geosoft.no/development/cppstyle.html).
16930   ???.
16931 * [Possibility.com: C++ Coding Standard](http://www.possibility.com/Cpp/CppCodingStandard.html).
16932   ???.
16933 * [SEI CERT: Secure C++ Coding Standard](https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=637).
16934   A very nicely done set of rules (with examples and rationales) done for security-sensitive code.
16935   Many of their rules apply generally.
16936 * [High Integrity C++ Coding Standard](http://www.codingstandard.com/).
16937 * [llvm](http://llvm.org/docs/CodingStandards.html).
16938   Somewhat brief, pre-C++11, and (not unreasonably) adjusted to its domain.
16939 * ???
16941 ## <a name="SS-books"></a>RF.books: Books with coding guidelines
16943 * [Meyers96](#Meyers96) Scott Meyers: *More Effective C++*. Addison-Wesley 1996.
16944 * [Meyers97](#Meyers97) Scott Meyers: *Effective C++, Second Edition*. Addison-Wesley 1997.
16945 * [Meyers01](#Meyers01) Scott Meyers: *Effective STL*. Addison-Wesley 2001.
16946 * [Meyers05](#Meyers05) Scott Meyers: *Effective C++, Third Edition*. Addison-Wesley 2005.
16947 * [Meyers15](#Meyers15) Scott Meyers: *Effective Modern C++*. O'Reilly 2015.
16948 * [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.
16949 * [Stroustrup05](#Stroustrup05) Bjarne Stroustrup: [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
16950   LCSD05. October 2005.
16951 * [Stroustrup14](#Stroustrup05) Stroustrup: [A Tour of C++](http://www.stroustrup.com/Tour.html).
16952   Addison Wesley 2014.
16953   Each chapter ends with an advice section consisting of a set of recommendations.
16954 * [Stroustrup13](#Stroustrup13) Stroustrup: [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html).
16955   Addison Wesley 2013.
16956   Each chapter ends with an advice section consisting of a set of recommendations.
16957 * Stroustrup: [Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
16958   for [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
16959   Mostly low-level naming and layout rules.
16960   Primarily a teaching tool.
16962 ## <a name="SS-Cplusplus"></a>RF.C++: C++ Programming (C++11/C++14)
16964 * [TC++PL4](http://www.stroustrup.com/4th.html):
16965 A thorough description of the C++ language and standard libraries for experienced programmers.
16966 * [Tour++](http://www.stroustrup.com/Tour.html):
16967 An overview of the C++ language and standard libraries for experienced programmers.
16968 * [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html):
16969 A textbook for beginners and relative novices.
16971 ## <a name="SS-web"></a>RF.web: Websites
16973 * [isocpp.org](https://isocpp.org)
16974 * [Bjarne Stroustrup's home pages](http://www.stroustrup.com)
16975 * [WG21](http://www.open-std.org/jtc1/sc22/wg21/)
16976 * [Boost](http://www.boost.org)<a name="Boost"></a>
16977 * [Adobe open source](http://www.adobe.com/open-source.html)
16978 * [Poco libraries](http://pocoproject.org/)
16979 * Sutter's Mill?
16980 * ???
16982 ## <a name="SS-vid"></a>RS.video: Videos about "modern C++"
16984 * Bjarne Stroustrup: [C++11 Style](http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style). 2012.
16985 * 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
16986 * All the talks from [CppCon '14](https://isocpp.org/blog/2014/11/cppcon-videos-c9)
16987 * Bjarne Stroustrup: [The essence of C++](https://www.youtube.com/watch?v=86xWVb4XIyE) at the University of Edinburgh. 2014.
16988 * Sutter: ???
16989 * CppCon 15
16990 * ??? C++ Next
16991 * ??? Meting C++
16992 * ??? more ???
16994 ## <a name="SS-man"></a>RF.man: Manuals
16996 * ISO C++ Standard C++11.
16997 * ISO C++ Standard C++14.
16998 * [ISO C++ Standard C++17 CD](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4606.pdf). Committee Draft.
16999 * [Palo Alto "Concepts" TR](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3351.pdf).
17000 * [ISO C++ Concepts TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
17001 * [WG21 Ranges report](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf). Draft.
17003 ## <a name="SS-ack"></a>Acknowledgements
17005 Thanks to the many people who contributed rules, suggestions, supporting information, references, etc.:
17007 * Peter Juhl
17008 * Neil MacIntosh
17009 * Axel Naumann
17010 * Andrew Pardoe
17011 * Gabriel Dos Reis
17012 * Zhuang, Jiangang (Jeff)
17013 * Sergey Zubkov
17015 and see the contributor list on the github.
17017 # <a name="S-profile"></a>Pro: Profiles
17019 A "profile" is a set of deterministic and portably enforceable subset rules (i.e., restrictions) that are designed to achieve a specific guarantee. "Deterministic" means they require only local analysis and could be implemented in a compiler (though they don't need to be). "Portably enforceable" means they are like language rules, so programmers can count on enforcement tools giving the same answer for the same code.
17021 Code written to be warning-free using such a language profile is considered to conform to the profile. Conforming code is considered to be safe by construction with regard to the safety properties targeted by that profile. Conforming code will not be the root cause of errors for that property, although such errors may be introduced into a program by other code, libraries or the external environment. A profile may also introduce additional library types to ease conformance and encourage correct code.
17023 Profiles summary:
17025 * [Pro.type: Type safety](#SS-type)
17026 * [Pro.bounds: Bounds safety](#SS-bounds)
17027 * [Pro.lifetime: Lifetime safety](#SS-lifetime)
17029 In the future, we expect to define many more profiles and add more checks to existing profiles.
17030 Candidates include:
17032 * narrowing arithmetic promotions/conversions (likely part of a separate safe-arithmetic profile)
17033 * arithmetic cast from negative floating point to unsigned integral type (ditto)
17034 * selected undefined behavior: ??? start with Gaby's UB list
17035 * selected unspecified behavior: ??? a portability concern?
17036 * `const` violations
17038 To suppress enforcement of a profile check, place a `suppress` annotation on a language contract. For example:
17040     [[suppress(bounds)]] char* raw_find(char* p, int n, char x)    // find x in p[0]..p[n-1]
17041     {
17042         // ...
17043     }
17045 Now `raw_find()` can scramble memory to its heart's content.
17046 Obviously, suppression should be very rare.
17048 ## <a name="SS-type"></a>Pro.safety: Type safety profile
17050 This profile makes it easier to construct code that uses types correctly and avoids inadvertent type punning.
17051 It does so by focusing on removing the primary sources of type violations, including unsafe uses of casts and unions.
17053 For the purposes of this section,
17054 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.
17055 Memory accessed as a type `T` should not be valid memory that actually contains an object of an unrelated type `U`.
17056 Note that the safety is intended to be complete when combined also with [Bounds safety](#SS-bounds) and [Lifetime safety](#SS-lifetime).
17058 An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic.
17060 Type safety profile summary:
17062 * [Type.1: Don't use `reinterpret_cast`](#Pro-type-reinterpretcast)
17063 * [Type.2: Don't use `static_cast` downcasts. Use `dynamic_cast` instead](#Pro-type-downcast)
17064 * [Type.3: Don't use `const_cast` to cast away `const` (i.e., at all)](#Pro-type-constcast)
17065 * [Type.4: Don't use C-style `(T)expression` casts that would perform a `static_cast` downcast, `const_cast`, or `reinterpret_cast`](#Pro-type-cstylecast)
17066 * [Type.5: Don't use a variable before it has been initialized](#Pro-type-init)
17067 * [Type.6: Always initialize a member variable](#Pro-type-memberinit)
17069 ### <a name="Pro-type-reinterpretcast"></a>Type.1: Don't use `reinterpret_cast`.
17071 ##### Reason
17073 Use of these 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`.
17075 ##### Example, bad
17077     std::string s = "hello world";
17078     double* p = reinterpret_cast<double*>(&s); // BAD
17080 ##### Enforcement
17082 Issue a diagnostic for any use of `reinterpret_cast`. To fix: Consider using a `variant` instead.
17084 ### <a name="Pro-type-downcast"></a>Type.2: Don't use `static_cast` downcasts. Use `dynamic_cast` instead.
17086 ##### Reason
17088 Use of these 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`.
17090 ##### Example, bad
17092     class Base { public: virtual ~Base() = 0; };
17094     class Derived1 : public Base { };
17096     class Derived2 : public Base {
17097         std::string s;
17098     public:
17099         std::string get_s() { return s; }
17100     };
17102     Derived1 d1;
17103     Base* p1 = &d1; // ok, implicit conversion to pointer to Base is fine
17105     // BAD, tries to treat d1 as a Derived2, which it is not
17106     Derived2* p2 = static_cast<Derived2*>(p1);
17107     // tries to access d1's nonexistent string member, instead sees arbitrary bytes near d1
17108     cout << p2->get_s();
17110 ##### Example, bad
17112     struct Foo { int a, b; };
17113     struct Foobar : Foo { int bar; };
17115     void use(int i, Foo& x)
17116     {
17117         if (0 < i) {
17118             Foobar& x1 = dynamic_cast<Foobar&>(x);  // error: Foo is not polymorphic
17119             Foobar& x2 = static_cast<Foobar&>(x);   // bad
17120             // ...
17121         }
17122         // ...
17123     }
17125     // ...
17127     use(99, *new Foo{1, 2});  // not a Foobar
17129 If a class hierarchy isn't polymorphic, avoid casting.
17130 It is entirely unsafe.
17131 Look for a better design.
17132 See also [C.146](#Rh-dynamic_cast).
17134 ##### Enforcement
17136 Issue a diagnostic for any use of `static_cast` to downcast, meaning to cast from a pointer or reference to `X` to a pointer or reference to a type that is not `X` or an accessible base of `X`. To fix: If this is a downcast or cross-cast then use a `dynamic_cast` instead, otherwise consider using a `variant` instead.
17138 ### <a name="Pro-type-constcast"></a>Type.3: Don't use `const_cast` to cast away `const` (i.e., at all).
17140 ##### Reason
17142 Casting away `const` is a lie. If the variable is actually declared `const`, it's a lie punishable by undefined behavior.
17144 ##### Example, bad
17146     void f(const int& i)
17147     {
17148         const_cast<int&>(i) = 42;   // BAD
17149     }
17151     static int i = 0;
17152     static const int j = 0;
17154     f(i); // silent side effect
17155     f(j); // undefined behavior
17157 ##### Example
17159 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:
17161     class Bar;
17163     class Foo {
17164     public:
17165         // BAD, duplicates logic
17166         Bar& get_bar() {
17167             /* complex logic around getting a non-const reference to my_bar */
17168         }
17170         const Bar& get_bar() const {
17171             /* same complex logic around getting a const reference to my_bar */
17172         }
17173     private:
17174         Bar my_bar;
17175     };
17177 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`:
17179     class Foo {
17180     public:
17181         // not great, non-const calls const version but resorts to const_cast
17182         Bar& get_bar() {
17183             return const_cast<Bar&>(static_cast<const Foo&>(*this).get_bar());
17184         }
17185         const Bar& get_bar() const {
17186             /* the complex logic around getting a const reference to my_bar */
17187         }
17188     private:
17189         Bar my_bar;
17190     };
17192 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.
17194 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:
17196     class Foo {
17197     public:                         // good
17198               Bar& get_bar()       { return get_bar_impl(*this); }
17199         const Bar& get_bar() const { return get_bar_impl(*this); }
17200     private:
17201         Bar my_bar;
17203         template<class T>           // good, deduces whether T is const or non-const
17204         static auto get_bar_impl(T& t) -> decltype(t.get_bar())
17205             { /* the complex logic around getting a possibly-const reference to my_bar */ }
17206     };
17208 ##### Exception
17210 You may need to cast away `const` when calling `const`-incorrect functions. Prefer to wrap such functions in inline `const`-correct wrappers to encapsulate the cast in one place.
17212 ##### Enforcement
17214 Issue a diagnostic for any use of `const_cast`. To fix: Either don't use the variable in a non-`const` way, or don't make it `const`.
17216 ### <a name="Pro-type-cstylecast"></a>Type.4: Don't use C-style `(T)expression` casts that would perform a `static_cast` downcast, `const_cast`, or `reinterpret_cast`.
17218 ##### Reason
17220 Use of these 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`.
17221 Note that a C-style `(T)expression` cast means to perform the first of the following that is possible: a `const_cast`, a `static_cast`, a `static_cast` followed by a `const_cast`, a `reinterpret_cast`, or a `reinterpret_cast` followed by a `const_cast`. This rule bans `(T)expression` only when used to perform an unsafe cast.
17223 ##### Example, bad
17225     std::string s = "hello world";
17226     double* p0 = (double*)(&s); // BAD
17228     class Base { public: virtual ~Base() = 0; };
17230     class Derived1 : public Base { };
17232     class Derived2 : public Base {
17233         std::string s;
17234     public:
17235         std::string get_s() { return s; }
17236     };
17238     Derived1 d1;
17239     Base* p1 = &d1; // ok, implicit conversion to pointer to Base is fine
17241     // BAD, tries to treat d1 as a Derived2, which it is not
17242     Derived2* p2 = (Derived2*)(p1);
17243     // tries to access d1's nonexistent string member, instead sees arbitrary bytes near d1
17244     cout << p2->get_s();
17246     void f(const int& i) {
17247         (int&)(i) = 42;   // BAD
17248     }
17250     static int i = 0;
17251     static const int j = 0;
17253     f(i); // silent side effect
17254     f(j); // undefined behavior
17256 ##### Enforcement
17258 Issue a diagnostic for any use of a C-style `(T)expression` cast that would invoke a `static_cast` downcast, `const_cast`, or `reinterpret_cast`. To fix: Use a `dynamic_cast`, `const`-correct declaration, or `variant`, respectively.
17260 ### <a name="Pro-type-init"></a>Type.5: Don't use a variable before it has been initialized.
17262 [ES.20: Always initialize an object](#Res-always) is required.
17264 ### <a name="Pro-type-memberinit"></a>Type.6: Always initialize a member variable.
17266 ##### Reason
17268 Before a variable has been initialized, it does not contain a deterministic valid value of its type. It could contain any arbitrary bit pattern, which could be different on each call.
17270 ##### Example
17272     struct X { int i; };
17274     X x;
17275     use(x); // BAD, x has not been initialized
17277     X x2{}; // GOOD
17278     use(x2);
17280 ##### Enforcement
17282 * Issue a diagnostic for any constructor of a non-trivially-constructible type that does not initialize all member variables. To fix: Write a data member initializer, or mention it in the member initializer list.
17283 * Issue a diagnostic when constructing an object of a trivially constructible type without `()` or `{}` to initialize its members. To fix: Add `()` or `{}`.
17285 ### <a name="Pro-type-unions"></a>Type.7: Avoid accessing members of raw unions. Prefer `variant` instead.
17287 ##### Reason
17289 Reading from a union member assumes that member was the last one written, and writing to a union member assumes another member with a nontrivial destructor had its destructor called. 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.
17291 ##### Example
17293     union U { int i; double d; };
17295     U u;
17296     u.i = 42;
17297     use(u.d); // BAD, undefined
17299     variant<int, double> u;
17300     u = 42; // u now contains int
17301     use(u.get<int>()); // ok
17302     use(u.get<double>()); // throws ??? update this when standardization finalizes the variant design
17304 Note that just copying a union is not type-unsafe, so safe code can pass a union from one piece of unsafe code to another.
17306 ##### Enforcement
17308 * Issue a diagnostic for accessing a member of a union. To fix: Use a `variant` instead.
17310 ### <a name="Pro-type-varargs"></a>Type.8: Avoid reading from varargs or passing vararg arguments. Prefer variadic template parameters instead.
17312 ##### Reason
17314 Reading from a vararg assumes that the correct type was actually passed. Passing to varargs assumes the correct type will be read. 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.
17316 ##### Example
17318     int sum(...) {
17319         // ...
17320         while (/*...*/)
17321             result += va_arg(list, int); // BAD, assumes it will be passed ints
17322         // ...
17323     }
17325     sum(3, 2); // ok
17326     sum(3.14159, 2.71828); // BAD, undefined
17328     template<class ...Args>
17329     auto sum(Args... args) { // GOOD, and much more flexible
17330         return (... + args); // note: C++17 "fold expression"
17331     }
17333     sum(3, 2); // ok: 5
17334     sum(3.14159, 2.71828); // ok: ~5.85987
17336 Note: 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.
17338 ##### Enforcement
17340 * Issue a diagnostic for using `va_list`, `va_start`, or `va_arg`. To fix: Use a variadic template parameter list instead.
17341 * 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)]]`.
17343 ## <a name="SS-bounds"></a>Pro.bounds: Bounds safety profile
17345 This profile makes it easier to construct code that operates within the bounds of allocated blocks of memory. It does so by focusing on removing the primary sources of bounds violations: pointer arithmetic and array indexing. One of the core features of this profile is to restrict pointers to only refer to single objects, not arrays.
17347 For the purposes of this document, bounds-safety is defined to be the property that a program does not use a variable to access memory outside of the range that was allocated and assigned to that variable. (Note that the safety is intended to be complete when combined also with [Type safety](#SS-type) and [Lifetime safety](#SS-lifetime), which cover other unsafe operations that allow bounds violations, such as type-unsafe casts that 'widen' pointers.)
17349 The following are under consideration but not yet in the rules below, and may be better in other profiles:
17351 * ???
17353 An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic.
17355 ### <a name="Pro-bounds-arithmetic"></a>Bounds.1: Don't use pointer arithmetic. Use `span` instead.
17357 ##### Reason
17359 Pointers should only refer to single objects, and pointer arithmetic is fragile and easy to get wrong. `span` is a bounds-checked, safe type for accessing arrays of data.
17361 ##### Example, bad
17363     void f(int* p, int count)
17364     {
17365         if (count < 2) return;
17367         int* q = p + 1; // BAD
17369         ptrdiff_t d;
17370         int n;
17371         d = (p - &n); // OK
17372         d = (q - p); // OK
17374         int n = *p++; // BAD
17376         if (count < 6) return;
17378         p[4] = 1; // BAD
17380         p[count - 1] = 2; // BAD
17382         use(&p[0], 3); // BAD
17383     }
17385 ##### Example, good
17387     void f(span<int> a) // BETTER: use span in the function declaration
17388     {
17389         if (a.length() < 2) return;
17391         int n = *a++; // OK
17393         span<int> q = a + 1; // OK
17395         if (a.length() < 6) return;
17397         a[4] = 1; // OK
17399         a[count - 1] = 2; // OK
17401         use(a.data(), 3); // OK
17402     }
17404 ##### Enforcement
17406 Issue a diagnostic for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
17408 ### <a name="Pro-bounds-arrayindex"></a>Bounds.2: Only index into arrays using constant expressions.
17410 ##### Reason
17412 Dynamic accesses into arrays are difficult for both tools and humans to validate as safe. `span` is a bounds-checked, safe type for accessing arrays of data. `at()` is another alternative that ensures single accesses are bounds-checked. If iterators are needed to access an array, use the iterators from a `span` constructed over the array.
17414 ##### Example, bad
17416     void f(array<int, 10> a, int pos)
17417     {
17418         a[pos / 2] = 1; // BAD
17419         a[pos - 1] = 2; // BAD
17420         a[-1] = 3;    // BAD -- no replacement, just don't do this
17421         a[10] = 4;    // BAD -- no replacement, just don't do this
17422     }
17424 ##### Example, good
17426     // ALTERNATIVE A: Use a span
17428     // A1: Change parameter type to use span
17429     void f1(span<int, 10> a, int pos)
17430     {
17431         a[pos / 2] = 1; // OK
17432         a[pos - 1] = 2; // OK
17433     }
17435     // A2: Add local span and use that
17436     void f2(array<int, 10> arr, int pos)
17437     {
17438         span<int> a = {arr, pos}
17439         a[pos / 2] = 1; // OK
17440         a[pos - 1] = 2; // OK
17441     }
17443     // ALTERNATIVE B: Use at() for access
17444     void f3(array<int, 10> a, int pos)
17445     {
17446         at(a, pos / 2) = 1; // OK
17447         at(a, pos - 1) = 2; // OK
17448     }
17450 ##### Example, bad
17452     void f()
17453     {
17454         int arr[COUNT];
17455         for (int i = 0; i < COUNT; ++i)
17456             arr[i] = i; // BAD, cannot use non-constant indexer
17457     }
17459 ##### Example, good
17461     // ALTERNATIVE A: Use a span
17462     void f1()
17463     {
17464         int arr[COUNT];
17465         span<int> av = arr;
17466         for (int i = 0; i < COUNT; ++i)
17467             av[i] = i;
17468     }
17470     // ALTERNATIVE B: Use at() for access
17471     void f2()
17472     {
17473         int arr[COUNT];
17474         for (int i = 0; i < COUNT; ++i)
17475             at(arr, i) = i;
17476     }
17478 ##### Enforcement
17480 Issue a diagnostic for 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.
17482 Issue a diagnostic for any indexing expression on an expression or variable of array type (either static array or `std::array`) where the indexer is not a value between `0` or and the upper bound of the array.
17484 **Rewrite support**: Tooling can offer rewrites of array accesses that involve dynamic index expressions to use `at()` instead:
17486     static int a[10];
17488     void f(int i, int j)
17489     {
17490         a[i + j] = 12;      // BAD, could be rewritten as ...
17491         at(a, i + j) = 12;  // OK -- bounds-checked
17492     }
17494 ### <a name="Pro-bounds-decay"></a>Bounds.3: No array-to-pointer decay.
17496 ##### Reason
17498 Pointers should not be used as arrays. `span` is a bounds-checked, safe alternative to using pointers to access arrays.
17500 ##### Example, bad
17502     void g(int* p, size_t length);
17504     void f()
17505     {
17506         int a[5];
17507         g(a, 5);        // BAD
17508         g(&a[0], 1);    // OK
17509     }
17511 ##### Example, good
17513     void g(int* p, size_t length);
17514     void g1(span<int> av); // BETTER: get g() changed.
17516     void f()
17517     {
17518         int a[5];
17519         span<int> av = a;
17521         g(av.data(), av.length());   // OK, if you have no choice
17522         g1(a);                       // OK -- no decay here, instead use implicit span ctor
17523     }
17525 ##### Enforcement
17527 Issue a diagnostic for any expression that would rely on implicit conversion of an array type to a pointer type.
17529 ### <a name="Pro-bounds-stdlib"></a>Bounds.4: Don't use standard library functions and types that are not bounds-checked.
17531 ##### Reason
17533 These functions all have bounds-safe overloads that take `span`. 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()`.
17535 ##### Example, bad
17537     void f()
17538     {
17539         array<int, 10> a, b;
17540         memset(a.data(), 0, 10);         // BAD, and contains a length error (length = 10 * sizeof(int))
17541         memcmp(a.data(), b.data(), 10);  // BAD, and contains a length error (length = 10 * sizeof(int))
17542     }
17544 Also, `std::array<>::fill()` or `std::fill()` or even an empty initializer are better candidate than `memset()`.
17546 ##### Example, good
17548     void f()
17549     {
17550         array<int, 10> a, b, c{};       // c is initialized to zero
17551         a.fill(0);
17552         fill(b.begin(), b.end(), 0);    // std::fill()
17553         fill(b, 0);                     // std::fill() + Ranges TS
17555         if ( a == b ) {
17556           // ...
17557         }
17558     }
17560 ##### Example
17562 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.
17564     void f(std::vector<int>& v, std::array<int, 12> a, int i)
17565     {
17566         v[0] = a[0];        // BAD
17567         v.at(0) = a[0];     // OK (alternative 1)
17568         at(v, 0) = a[0];    // OK (alternative 2)
17570         v.at(0) = a[i];     // BAD
17571         v.at(0) = a.at(i);  // OK (alternative 1)
17572         v.at(0) = at(a, i); // OK (alternative 2)
17573     }
17575 ##### Enforcement
17577 * Issue a diagnostic for any call to a standard library function that is not bounds-checked. ??? insert link to a list of banned functions
17579 **TODO Notes**:
17581 * Impact on the standard library will require close coordination with WG21, if only to ensure compatibility even if never standardized.
17582 * We are considering specifying bounds-safe overloads for stdlib (especially C stdlib) functions like `memcmp` and shipping them in the GSL.
17583 * 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).
17585 ## <a name="SS-lifetime"></a>Pro.lifetime: Lifetime safety profile
17589 # <a name="S-gsl"></a>GSL: Guideline support library
17591 The GSL is a small library of facilities designed to support this set of guidelines.
17592 Without these facilities, the guidelines would have to be far more restrictive on language details.
17594 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.
17596 The GSL is header only, and can be found at [GSL: Guideline support library](https://github.com/Microsoft/GSL).
17597 The support library facilities are designed to be extremely lightweight (zero-overhead) so that they impose no overhead compared to using conventional alternatives.
17598 Where desirable, they can be "instrumented" with additional functionality (e.g., checks) for tasks such as debugging.
17600 These Guidelines assume a `variant` type, but this is not currently in GSL.
17601 Eventually, use [the one voted into C++17](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0088r3.html).
17603 Summary of GSL components:
17605 * [GSL.view: Views](#SS-views)
17606 * [GSL.owner](#SS-ownership)
17607 * [GSL.assert: Assertions](#SS-assertions)
17608 * [GSL.util: Utilities](#SS-utilities)
17609 * [GSL.concept: Concepts](#SS-gsl-concepts)
17611 We plan for a "ISO C++ standard style" semi-formal specification of the GSL.
17613 We rely on the ISO C++ standard library and hope for parts of the GSL to be absorbed into the standard library.
17615 ## <a name="SS-views"></a>GSL.view: Views
17617 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.
17619 These "views" are never owners.
17621 References are never owners.
17623 The names are mostly ISO standard-library style (lower case and underscore):
17625 * `T*`      // The `T*` is not an owner, may be null; assumed to be pointing to a single element.
17626 * `T&`      // The `T&` is not an owner and can never be a "null reference"; references are always bound to objects.
17628 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.
17629 Owners should be converted to resource handles (e.g., `unique_ptr` or `vector<T>`) or marked `owner<T*>`
17631 * `owner<T*>`   // a `T*`that owns the object pointed/referred to; may be `nullptr`.
17632 * `owner<T&>`   // a `T&` that owns the object pointed/referred to.
17634 `owner` is used to mark owning pointers in code that cannot be upgraded to use proper resource handles.
17635 Reasons for that include:
17637 * Cost of conversion.
17638 * The pointer is used with an ABI.
17639 * The pointer is part of the implementation of a resource handle.
17641 An `owner<T>` differs from a resource handle for a `T` by still requiring an explicit `delete`.
17643 An `owner<T>` is assumed to refer to an object on the free store (heap).
17645 If something is not supposed to be `nullptr`, say so:
17647 * `not_null<T>`   // `T` is usually a pointer type (e.g., `not_null<int*>` and `not_null<owner<Foo*>>`) that may not be `nullptr`.
17648   `T` can be any type for which `==nullptr` is meaningful.
17650 * `span<T>`       // `[`p`:`p+n`), constructor from `{p, q}` and `{p, n}`; `T` is the pointer type
17651 * `span_p<T>`     // `{p, predicate}` \[`p`:`q`) where `q` is the first element for which `predicate(*p)` is true
17652 * `string_span`   // `span<char>`
17653 * `cstring_span`  // `span<const char>`
17655 A `span<T>` refers to zero or more mutable `T`s unless `T` is a `const` type.
17657 "Pointer arithmetic" is best done within `span`s.
17658 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`.
17660 * `zstring`    // a `char*` supposed to be a C-style string; that is, a zero-terminated sequence of `char` or `nullptr`
17661 * `czstring`   // a `const char*` supposed to be a C-style string; that is, a zero-terminated sequence of `const` `char` or `nullptr`
17663 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.
17664 A sequence of characters that is not assumed to be zero-terminated should be a `char*`, rather than a `zstring`.
17665 French accent optional.
17667 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?
17669 ## <a name="SS-ownership"></a>GSL.owner: Ownership pointers
17671 * `unique_ptr<T>`     // unique ownership: `std::unique_ptr<T>`
17672 * `shared_ptr<T>`     // shared ownership: `std::shared_ptr<T>` (a counted pointer)
17673 * `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.
17674 * `dyn_array<T>`      // ??? needed ??? A heap-allocated array. The number of elements are determined at construction and fixed thereafter.
17675   The elements are mutable unless `T` is a `const` type. Basically a `span` that allocates and owns its elements.
17677 ## <a name="SS-assertions"></a>GSL.assert: Assertions
17679 * `Expects`     // precondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
17680                 // `Expects(p)` terminates the program unless `p == true`
17681                 // `Expect` in under control of some options (enforcement, error message, alternatives to terminate)
17682 * `Ensures`     // postcondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
17684 These assertions is currently macros (yuck!) and must appear in function definitions (only)
17685 pending standard commission decisions on contracts and assertion syntax.
17686 See [the contract proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf) uses the attribute syntax,
17687 for example, `Expects(p!=nullptr)` will become`[[expects: p!=nullptr]]`.
17689 ## <a name="SS-utilities"></a>GSL.util: Utilities
17691 * `finally`       // `finally(f)` makes a `final_action{f}` with a destructor that invokes `f`
17692 * `narrow_cast`   // `narrow_cast<T>(x)` is `static_cast<T>(x)`
17693 * `narrow`        // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
17694 * `[[implicit]]`  // "Marker" to put on single-argument constructors to explicitly make them non-explicit.
17695 * `move_owner`    // `p = move_owner(q)` means `p = q` but ???
17697 ## <a name="SS-gsl-concepts"></a>GSL.concept: Concepts
17699 These concepts (type predicates) are borrowed from
17700 Andrew Sutton's Origin library,
17701 the Range proposal,
17702 and the ISO WG21 Palo Alto TR.
17703 They are likely to be very similar to what will become part of the ISO C++ standard.
17704 The notation is that of the ISO WG21 [Concepts TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
17705 Most of the concepts below are defined in [the Ranges TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf).
17707 * `Range`
17708 * `String`   // ???
17709 * `Number`   // ???
17710 * `Sortable`
17711 * `Pointer`  // A type with `*`, `->`, `==`, and default construction (default construction is assumed to set the singular "null" value); see [smart pointers](#Rr-smartptrconcepts)
17712 * `Unique_ptr`  // A type that matches `Pointer`, has move (not copy), and matches the Lifetime profile criteria for a `unique` owner type; see [smart pointers](#Rr-smartptrconcepts)
17713 * `Shared_ptr`   // A type that matches `Pointer`, has copy, and matches the Lifetime profile criteria for a `shared` owner type; see [smart pointers](#Rr-smartptrconcepts)
17714 * `EqualityComparable`   // ???Must we suffer CaMelcAse???
17715 * `Convertible`
17716 * `Common`
17717 * `Boolean`
17718 * `Integral`
17719 * `SignedIntegral`
17720 * `SemiRegular` // ??? Copyable?
17721 * `Regular`
17722 * `TotallyOrdered`
17723 * `Function`
17724 * `RegularFunction`
17725 * `Predicate`
17726 * `Relation`
17727 * ...
17729 ### <a name="SS-gsl-smartptrconcepts"></a>Smart pointer concepts
17731 Described in [Lifetimes paper](https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/Lifetimes%20I%20and%20II%20-%20v0.9.1.pdf).
17733 # <a name="S-naming"></a>NL: Naming and layout rules
17735 Consistent naming and layout are helpful.
17736 If for no other reason because it minimizes "my style is better than your style" arguments.
17737 However, there are many, many, different styles around and people are passionate about them (pro and con).
17738 Also, most real-world projects includes code from many sources, so standardizing on a single style for all code is often impossible.
17739 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.
17740 IDEs and tools can help (as well as hinder).
17742 Naming and layout rules:
17744 * [NL.1: Don't say in comments what can be clearly stated in code](#Rl-comments)
17745 * [NL.2: State intent in comments](#Rl-comments-intent)
17746 * [NL.3: Keep comments crisp](#Rl-comments-crisp)
17747 * [NL.4: Maintain a consistent indentation style](#Rl-indent)
17748 * [NL.5: Don't encode type information in names](#Rl-name-type)
17749 * [NL.7: Make the length of a name roughly proportional to the length of its scope](#Rl-name-length)
17750 * [NL.8: Use a consistent naming style](#Rl-name)
17751 * [NL.9: Use `ALL_CAPS` for macro names only](#Rl-all-caps)
17752 * [NL.10: Avoid CamelCase](#Rl-camel)
17753 * [NL.15: Use spaces sparingly](#Rl-space)
17754 * [NL.16: Use a conventional class member declaration order](#Rl-order)
17755 * [NL.17: Use K&R-derived layout](#Rl-knr)
17756 * [NL.18: Use C++-style declarator layout](#Rl-ptr)
17757 * [NL.19: Avoid names that are easily misread](#Rl-misread)
17758 * [NL.20: Don't place two statements on the same line](#Rl-stmt)
17759 * [NL.21: Declare one name (only) per declaration](#Rl-dcl)
17760 * [NL.25: Don't use `void` as an argument type](#Rl-void)
17761 * [NL.26: Use conventional `const` notation](#Rl-const)
17763 Most of these rules are aesthetic and programmers hold strong opinions.
17764 IDEs also tend to have defaults and a range of alternatives.
17765 These rules are suggested defaults to follow unless you have reasons not to.
17767 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.
17768 We are not "legislating" (see the previous paragraph).
17769 However, we have had many requests for a set of naming and layout conventions to use when there are no external constraints.
17771 More specific and detailed rules are easier to enforce.
17773 These rules bear a strong resemblance to the recommendations in the [PPP Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
17774 written in support of Stroustrup's [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
17776 ### <a name="Rl-comments"></a>NL.1: Don't say in comments what can be clearly stated in code
17778 ##### Reason
17780 Compilers do not read comments.
17781 Comments are less precise than code.
17782 Comments are not updated as consistently as code.
17784 ##### Example, bad
17786     auto x = m * v1 + vv;   // multiply m with v1 and add the result to vv
17788 ##### Enforcement
17790 Build an AI program that interprets colloquial English text and see if what is said could be better expressed in C++.
17792 ### <a name="Rl-comments-intent"></a>NL.2: State intent in comments
17794 ##### Reason
17796 Code says what is done, not what is supposed to be done. Often intent can be stated more clearly and concisely than the implementation.
17798 ##### Example
17800     void stable_sort(Sortable& c)
17801         // sort c in the order determined by <, keep equal elements (as defined by ==) in
17802         // their original relative order
17803     {
17804         // ... quite a few lines of non-trivial code ...
17805     }
17807 ##### Note
17809 If the comment and the code disagrees, both are likely to be wrong.
17811 ### <a name="Rl-comments-crisp"></a>NL.3: Keep comments crisp
17813 ##### Reason
17815 Verbosity slows down understanding and makes the code harder to read by spreading it around in the source file.
17817 ##### Note
17819 Use intelligible English.
17820 I may be fluent in Danish, but most programmers are not; the maintainers of my code may not be.
17821 Avoid SMS lingo and watch your grammar, punctuation, and capitalization.
17822 Aim for professionalism, not "cool."
17824 ##### Enforcement
17826 not possible.
17828 ### <a name="Rl-indent"></a>NL.4: Maintain a consistent indentation style
17830 ##### Reason
17832 Readability. Avoidance of "silly mistakes."
17834 ##### Example, bad
17836     int i;
17837     for (i = 0; i < max; ++i); // bug waiting to happen
17838     if (i == j)
17839         return i;
17841 ##### Note
17843 Always indenting the statement after `if (...)`, `for (...)`, and `while (...)` is usually a good idea:
17845     if (i < 0) error("negative argument");
17847     if (i < 0)
17848         error("negative argument");
17850 ##### Enforcement
17852 Use a tool.
17854 ### <a name="Rl-name-type"></a>NL.5 Don't encode type information in names
17856 ##### Rationale
17858 If names reflect types rather than functionality, it becomes hard to change the types used to provide that functionality.
17859 Also, if the type of a variable is changed, code using it will have to be modified.
17860 Minimize unintentional conversions.
17862 ##### Example, bad
17864     void print_int(int i);
17865     void print_string(const char*);
17867     print_int(1);   // OK
17868     print_int(x);   // conversion to int if x is a double
17870 ##### Note
17872 Names with types encoded are either verbose or cryptic.
17874     printS  // print a std::string
17875     prints  // print a C-style string
17876     printi  // print an int
17878 PS. Hungarian notation is evil (at least in a strongly statically-typed language).
17880 ##### Note
17882 Some styles distinguishes members from local variable, and/or from global variable.
17884     struct S {
17885         int m_;
17886         S(int m) :m_{abs(m)} { }
17887     };
17889 This is not evil.
17891 ##### Note
17893 Like C++, some styles distinguishes types from non-types.
17894 For example, by capitalizing type names, but not the names of functions and variables.
17896     typename<typename T>
17897     class Hash_tbl {   // maps string to T
17898         // ...
17899     };
17901     Hash_tbl<int> index;
17903 This is not evil.
17905 ### <a name="Rl-name-length"></a>NL.7: Make the length of a name roughly proportional to the length of its scope
17907 **Rationale**: The larger the scope the greater the chance of confusion and of an unintended name clash.
17909 ##### Example
17911     double sqrt(double x);   // return the square root of x; x must be non-negative
17913     int length(const char* p);  // return the number of characters in a zero-terminated C-style string
17915     int length_of_string(const char zero_terminated_array_of_char[])    // bad: verbose
17917     int g;      // bad: global variable with a cryptic name
17919     int open;   // bad: global variable with a short, popular name
17921 The use of `p` for pointer and `x` for a floating-point variable is conventional and non-confusing in a restricted scope.
17923 ##### Enforcement
17927 ### <a name="Rl-name"></a>NL.8: Use a consistent naming style
17929 **Rationale**: Consistence in naming and naming style increases readability.
17931 ##### Note
17933 There are many styles and when you use multiple libraries, you can't follow all their different conventions.
17934 Choose a "house style", but leave "imported" libraries with their original style.
17936 ##### Example
17938 ISO Standard, use lower case only and digits, separate words with underscores:
17940 * `int`
17941 * `vector`
17942 * `my_map`
17944 Avoid double underscores `__`.
17946 ##### Example
17948 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
17949 ISO Standard, but with upper case used for your own types and concepts:
17951 * `int`
17952 * `vector`
17953 * `My_map`
17955 ##### Example
17957 CamelCase: capitalize each word in a multi-word identifier:
17959 * `int`
17960 * `vector`
17961 * `MyMap`
17962 * `myMap`
17964 Some conventions capitalize the first letter, some don't.
17966 ##### Note
17968 Try to be consistent in your use of acronyms and lengths of identifiers:
17970     int mtbf {12};
17971     int mean_time_between_failures {12}; // make up your mind
17973 ##### Enforcement
17975 Would be possible except for the use of libraries with varying conventions.
17977 ### <a name="Rl-all-caps"></a>NL.9: Use `ALL_CAPS` for macro names only
17979 ##### Reason
17981 To avoid confusing macros with names that obey scope and type rules.
17983 ##### Example
17985     void f()
17986     {
17987         const int SIZE{1000};  // Bad, use 'size' instead
17988         int v[SIZE];
17989     }
17991 ##### Note
17993 This rule applies to non-macro symbolic constants:
17995     enum bad { BAD, WORSE, HORRIBLE }; // BAD
17997 ##### Enforcement
17999 * Flag macros with lower-case letters
18000 * Flag `ALL_CAPS` non-macro names
18002 ### <a name="Rl-camel"></a>NL.10: Avoid CamelCase
18004 ##### Reason
18006 The use of underscores to separate parts of a name is the original C and C++ style and used in the C++ standard library.
18007 If you prefer CamelCase, you have to choose among different flavors of camelCase.
18009 ##### Note
18011 This rule is a default to use only if you have a choice.
18012 Often, you don't have a choice and must follow an established style for [consistency](#Rl-name).
18013 The need for consistency beats personal taste.
18015 ##### Example
18017 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
18018 ISO Standard, but with upper case used for your own types and concepts:
18020 * `int`
18021 * `vector`
18022 * `My_map`
18024 ##### Enforcement
18026 Impossible.
18028 ### <a name="Rl-space"></a>NL.15: Use spaces sparingly
18030 ##### Reason
18032 Too much space makes the text larger and distracts.
18034 ##### Example, bad
18036     #include < map >
18038     int main(int argc, char * argv [ ])
18039     {
18040         // ...
18041     }
18043 ##### Example
18045     #include<map>
18047     int main(int argc, char* argv[])
18048     {
18049         // ...
18050     }
18052 ##### Note
18054 Some IDEs have their own opinions and add distracting space.
18056 ##### Note
18058 We value well-placed whitespace as a significant help for readability. Just don't overdo it.
18060 ### <a name="Rl-order"></a>NL.16: Use a conventional class member declaration order
18062 ##### Reason
18064 A conventional order of members improves readability.
18066 When declaring a class use the following order
18068 * types: classes, enums, and aliases (`using`)
18069 * constructors, assignments, destructor
18070 * functions
18071 * data
18073 Use the `public` before `protected` before `private` order.
18075 Private types and functions can be placed with private data.
18077 Avoid multiple blocks of declarations of one access (e.g., `public`) dispersed among blocks of declarations with different access (e.g. `private`).
18079 ##### Example
18081     class X {
18082     public:
18083         // interface
18084     protected:
18085         // unchecked function for use by derived class implementations
18086     private:
18087         // implementation details
18088     };
18090 ##### Note
18092 The use of macros to declare groups of members often violates any ordering rules.
18093 However, macros obscures what is being expressed anyway.
18095 ##### Enforcement
18097 Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule.
18099 ### <a name="Rl-knr"></a>NL.17: Use K&R-derived layout
18101 ##### Reason
18103 This is the original C and C++ layout. It preserves vertical space well. It distinguishes different language constructs (such as functions and classes) well.
18105 ##### Note
18107 In the context of C++, this style is often called "Stroustrup".
18109 ##### Example
18111     struct Cable {
18112         int x;
18113         // ...
18114     };
18116     double foo(int x)
18117     {
18118         if (0 < x) {
18119             // ...
18120         }
18122         switch (x) {
18123             case 0:
18124                 // ...
18125                 break;
18126             case amazing:
18127                 // ...
18128                 break;
18129             default:
18130                 // ...
18131                 break;
18132         }
18134         if (0 < x)
18135             ++x;
18137         if (x < 0)
18138             something();
18139         else
18140             something_else();
18142         return some_value;
18143     }
18145 Note the space between `if` and `(`
18147 ##### Note
18149 Use separate lines for each statement, the branches of an `if`, and the body of a `for`.
18151 ##### Note
18153 The `{` for a `class` and a `struct` in *not* on a separate line, but the `{` for a function is.
18155 ##### Note
18157 Capitalize the names of your user-defined types to distinguish them from standards-library types.
18159 ##### Note
18161 Do not capitalize function names.
18163 ##### Enforcement
18165 If you want enforcement, use an IDE to reformat.
18167 ### <a name="Rl-ptr"></a>NL.18: Use C++-style declarator layout
18169 ##### Reason
18171 The C-style layout emphasizes use in expressions and grammar, whereas the C++-style emphasizes types.
18172 The use in expressions argument doesn't hold for references.
18174 ##### Example
18176     T& operator[](size_t);   // OK
18177     T &operator[](size_t);   // just strange
18178     T & operator[](size_t);   // undecided
18180 ##### Enforcement
18182 Impossible in the face of history.
18185 ### <a name="Rl-misread"></a>NL.19: Avoid names that are easily misread
18187 ##### Reason
18189 Readability.
18190 Not everyone has screens and printers that make it easy to distinguish all characters.
18191 We easily confuse similarly spelled and slightly misspelled words.
18193 ##### Example
18195     int oO01lL = 6; // bad
18197     int splunk = 7;
18198     int splonk = 8; // bad: splunk and splonk are easily confused
18200 ##### Enforcement
18204 ### <a name="Rl-stmt"></a>NL.20: Don't place two statements on the same line
18206 ##### Reason
18208 Readability.
18209 It is really easy to overlook a statement when there is more on a line.
18211 ##### Example
18213     int x = 7; char* p = 29;    // don't
18214     int x = 7; f(x);  ++x;      // don't
18216 ##### Enforcement
18218 Easy.
18220 ### <a name="Rl-dcl"></a>NL.21: Declare one name (only) per declaration
18222 ##### Reason
18224 Readability.
18225 Minimizing confusion with the declarator syntax.
18227 ##### Note
18229 For details, see [ES.10](#Res-name-one).
18232 ### <a name="Rl-void"></a>NL.25: Don't use `void` as an argument type
18234 ##### Reason
18236 It's verbose and only needed where C compatibility matters.
18238 ##### Example
18240     void f(void);   // bad
18242     void g();       // better
18244 ##### Note
18246 Even Dennis Ritchie deemed `void f(void)` an abomination.
18247 You can make an argument for that abomination in C when function prototypes were rare so that banning:
18249     int f();
18250     f(1, 2, "weird but valid C89");   // hope that f() is defined int f(a, b, c) char* c; { /* ... */ }
18252 would have caused major problems, but not in the 21st century and in C++.
18254 ### <a name="Rl-const"></a>NL.26: Use conventional `const` notation
18256 ##### Reason
18258 Conventional notation is more familiar to more programmers.
18259 Consistency in large code bases.
18261 ##### Example
18263     const int x = 7;    // OK
18264     int const y = 9;    // bad
18266     const int *const p = nullptr;   // OK, constant pointer to constant int
18267     int const *const p = nullptr;   // bad, constant pointer to constant int
18269 ##### Note
18271 We are well aware that you could claim the "bad" examples more logical than the ones marked "OK",
18272 but they also confuse more people, especially novices relying on teaching material using the far more common, conventional OK style.
18274 As ever, remember that the aim of these naming and layout rules is consistency and that aesthetics vary immensely.
18276 ##### Enforcement
18278 Flag `const` used as a suffix for a type.
18280 # <a name="S-faq"></a>FAQ: Answers to frequently asked questions
18282 This section covers answers to frequently asked questions about these guidelines.
18284 ### <a name="Faq-aims"></a>FAQ.1: What do these guidelines aim to achieve?
18286 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.
18288 ### <a name="Faq-announced"></a>FAQ.2: When and where was this work first announced?
18290 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).
18292 ### <a name="Faq-maintainers"></a>FAQ.3: Who are the authors and maintainers of these guidelines?
18294 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!"
18296 ### <a name="Faq-contribute"></a>FAQ.4: How can I contribute?
18298 See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help!
18300 ### <a name="Faq-maintainer"></a>FAQ.5: How can I become an editor/maintainer?
18302 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!
18304 ### <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?
18306 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.
18308 ### <a name="Faq-isocpp"></a>FAQ.7: If these guidelines are not approved by the committee, why are they under `github.com/isocpp`?
18310 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.
18312 ### <a name="Faq-cpp98"></a>FAQ.8: Will there be a C++98 version of these Guidelines? a C++11 version?
18314 No. These guidelines are about how to best use Standard C++14 (and, if you have an implementation available, the Concepts Lite Technical Specification) and write code assuming you have a modern conforming compiler.
18316 ### <a name="Faq-language-extensions"></a>FAQ.9: Do these guidelines propose new language features?
18318 No. These guidelines are about how to best use Standard C++14 + the Concepts Lite Technical Specification, and they limit themselves to recommending only those features.
18320 ### <a name="Faq-markdown"></a>FAQ.10: What version of Markdown do these guidelines use?
18322 These coding standards are written using [CommonMark](http://commonmark.org), and `<a>` HTML anchors.
18324 We are considering the following extensions from [GitHub Flavored Markdown (GFM)](https://help.github.com/articles/github-flavored-markdown/):
18326 * fenced code blocks (consistently using indented vs. fenced is under discussion)
18327 * tables (none yet but we'll likely need them, and this is a GFM extension)
18329 Avoid other HTML tags and other extensions.
18331 Note: We are not yet consistent with this style.
18333 ### <a name="Faq-gsl"></a>FAQ.50: What is the GSL (guideline support library)?
18335 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.
18337 ### <a name="Faq-msgsl"></a>FAQ.51: Is [github.com/Microsoft/GSL](https://github.com/Microsoft/GSL) the GSL?
18339 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.
18341 ### <a name="Faq-gsl-implementation"></a>FAQ.52: Why not supply an actual GSL implementation in/with these guidelines?
18343 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.
18345 ### <a name="Faq-boost"></a>FAQ.53: Why weren't the GSL types proposed through Boost?
18347 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.
18349 ### <a name="Faq-gsl-iso"></a>FAQ.54: Has the GSL (guideline support library) been approved by the ISO C++ standards committee?
18351 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.
18353 ### <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`?
18355 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.
18357 ### <a name="Faq-gsl-owner"></a>FAQ.56: Is `owner` the same as the proposed `observer_ptr`?
18359 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.
18361 ### <a name="Faq-gsl-stack-array"></a>FAQ.57: Is `stack_array` the same as the standard `array`?
18363 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.
18365 ### <a name="Faq-gsl-dyn-array"></a>FAQ.58: Is `dyn_array` the same as `vector` or the proposed `dynarray`?
18367 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.
18369 ### <a name="Faq-gsl-expects"></a>FAQ.59: Is `Expects` the same as `assert`?
18371 No. It is a placeholder for language support for contract preconditions.
18373 ### <a name="Faq-gsl-ensures"></a>FAQ.60: Is `Ensures` the same as `assert`?
18375 No. It is a placeholder for language support for contract postconditions.
18377 # <a name="S-libraries"></a>Appendix A: Libraries
18379 This section lists recommended libraries, and explicitly recommends a few.
18381 ??? Suitable for the general guide? I think not ???
18383 # <a name="S-modernizing"></a>Appendix B: Modernizing code
18385 Ideally, we follow all rules in all code.
18386 Realistically, we have to deal with a lot of old code:
18388 * application code written before the guidelines were formulated or known
18389 * libraries written to older/different standards
18390 * code written under "unusual" constraints
18391 * code that we just haven't gotten around to modernizing
18393 If we have a million lines of new code, the idea of "just changing it all at once" is typically unrealistic.
18394 Thus, we need a way of gradually modernizing a code base.
18396 Upgrading older code to modern style can be a daunting task.
18397 Often, the old code is both a mess (hard to understand) and working correctly (for the current range of uses).
18398 Typically, the original programmer is not around and the test cases incomplete.
18399 The fact that the code is a mess dramatically increases the effort needed to make any change and the risk of introducing errors.
18400 Often, messy old code runs unnecessarily slowly because it requires outdated compilers and cannot take advantage of modern hardware.
18401 In many cases, automated "modernizer"-style tool support would be required for major upgrade efforts.
18403 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.
18404 Making code "look pretty" or "follow modern style" are not by themselves reasons for change.
18405 There are risks implied by every change and costs (including the cost of lost opportunities) implied by having an outdated code base.
18406 The cost reductions must outweigh the risks.
18408 But how?
18410 There is no one approach to modernizing code.
18411 How best to do it depends on the code, the pressure for updates, the backgrounds of the developers, and the available tool.
18412 Here are some (very general) ideas:
18414 * The ideal is "just upgrade everything." That gives the most benefits for the shortest total time.
18415   In most circumstances, it is also impossible.
18416 * 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.
18417 * 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.
18418 * We could start by focusing on the interfaces, e.g., make sure that no resources are lost and no pointer is misused.
18419   This would be a set of changes across the whole code base, but would most likely have huge benefits.
18420   Afterwards, code hidden behind those interfaces can be gradually modernized without affecting other code.
18422 Whichever way you choose, please note that the most advantages come with the highest conformance to the guidelines.
18423 The guidelines are not a random set of unrelated rules where you can randomly pick and choose with an expectation of success.
18425 We would dearly love to hear about experience and about tools used.
18426 Modernization can be much faster, simpler, and safer when supported with analysis tools and even code transformation tools.
18428 # <a name="S-discussion"></a>Appendix C: Discussion
18430 This section contains follow-up material on rules and sets of rules.
18431 In particular, here we present further rationale, longer examples, and discussions of alternatives.
18433 ### <a name="Sd-order"></a>Discussion: Define and initialize member variables in the order of member declaration
18435 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.
18437     class Employee {
18438         string email, first, last;
18439     public:
18440         Employee(const char* firstName, const char* lastName);
18441         // ...
18442     };
18444     Employee::Employee(const char* firstName, const char* lastName)
18445       : first(firstName),
18446         last(lastName),
18447         // BAD: first and last not yet constructed
18448         email(first + "." + last + "@acme.com")
18449     {}
18451 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.
18453 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.
18455 **References**:
18457 [\[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
18459 ### <a name="TBD"></a>Use of `=`, `{}`, and `()` as initializers
18463 ### <a name="Sd-factory"></a>Discussion: Use a factory function if you need "virtual behavior" during initialization
18465 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:
18467 * *Pass the buck:* Just document that user code must call the post-initialization function right after constructing an object.
18468 * *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.
18469 * *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).)
18470 * *Use a factory function:* This way, you can easily force a mandatory invocation of a post-constructor function.
18472 Here is an example of the last option:
18474     class B {
18475     public:
18476         B() { /* ... */ f(); /* ... */ }   // BAD: see Item 49.1
18478         virtual void f() = 0;
18480         // ...
18481     };
18483     class B {
18484     protected:
18485         B() { /* ... */ }
18486         virtual void PostInitialize()    // called right after construction
18487             { /* ... */ f(); /* ... */ }   // GOOD: virtual dispatch is safe
18488     public:
18489         virtual void f() = 0;
18491         template<class T>
18492         static shared_ptr<T> Create()    // interface for creating objects
18493         {
18494             auto p = make_shared<T>();
18495             p->PostInitialize();
18496             return p;
18497         }
18498     };
18501     class D : public B {                 // some derived class
18502     public:
18503         void f() override { /* ...  */ };
18505     protected:
18506         D() {}
18508         template<class T>
18509         friend shared_ptr<T> B::Create();
18510     };
18512     shared_ptr<D> p = D::Create<D>();    // creating a D object
18514 This design requires the following discipline:
18516 * Derived classes such as `D` must not expose a public constructor. Otherwise, `D`'s users could create `D` objects that don't invoke `PostInitialize`.
18517 * Allocation is limited to `operator new`. `B` can, however, override `new` (see Items 45 and 46).
18518 * `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.
18520 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.
18522 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).
18524 **References**: [\[Alexandrescu01\]](#Alexandrescu01) §3, [\[Boost\]](#Boost), [\[Dewhurst03\]](#Dewhurst03) §75, [\[Meyers97\]](#Meyers97) §46, [\[Stroustrup00\]](#Stroustrup00) §15.4.3, [\[Taligent94\]](#Taligent94)
18526 ### <a name="Sd-dtor"></a>Discussion: Make base class destructors public and virtual, or protected and nonvirtual
18528 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 virtual.
18530 ##### Example
18532 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>`:
18534     class Base {
18535     public:
18536         ~Base();                   // BAD, not virtual
18537         virtual ~Base();           // GOOD
18538         // ...
18539     };
18541     class Derived : public Base { /* ... */ };
18543     {
18544         unique_ptr<Base> pb = make_unique<Derived>();
18545         // ...
18546     } // ~pb invokes correct destructor only when ~Base is virtual
18548 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:
18550     class My_policy {
18551     public:
18552         virtual ~My_policy();      // BAD, public and virtual
18553     protected:
18554         ~My_policy();              // GOOD
18555         // ...
18556     };
18558     template<class Policy>
18559     class customizable : Policy { /* ... */ }; // note: private inheritance
18561 ##### Note
18563 This simple guideline illustrates a subtle issue and reflects modern uses of inheritance and object-oriented design principles.
18565 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.
18567 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:
18569 * Whether it should behave virtually or not.
18570 * Whether it should be publicly available to all callers using a pointer to `Base` or else be a hidden internal implementation detail.
18572 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.
18574 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.
18576 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.)
18578 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.
18580 ##### Exception
18582 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.
18584 Consider also this rare case:
18586 * `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.
18587 * 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.
18589 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.
18591 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`.
18593 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.
18595 **References**: [\[C++CS\]](#C++CS) 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
18597 ### <a name="Sd-noexcept"></a>Discussion: Usage of noexcept
18601 ### <a name="Sd-never-fail"></a>Discussion: Destructors, deallocation, and swap must never fail
18603 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.
18605 ##### Example
18607     class Nefarious {
18608     public:
18609         Nefarious()  { /* code that could throw */ }   // ok
18610         ~Nefarious() { /* code that could throw */ }   // BAD, should not throw
18611         // ...
18612     };
18614 1. `Nefarious` objects are hard to use safely even as local variables:
18617         void test(string& s)
18618         {
18619             Nefarious n;          // trouble brewing
18620             string copy = s;      // copy the string
18621         } // destroy copy and then n
18623     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.
18625 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:
18628         class Innocent_bystander {
18629             Nefarious member;     // oops, poisons the enclosing class's destructor
18630             // ...
18631         };
18633         void test(string& s)
18634         {
18635             Innocent_bystander i; // more trouble brewing
18636             string copy2 = s;      // copy the string
18637         } // destroy copy and then i
18639     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`.
18641 3. You can't reliably create global or static `Nefarious` objects either:
18644         static Nefarious n;       // oops, any destructor exception can't be caught
18646 4. You can't reliably create arrays of `Nefarious`:
18649         void test()
18650         {
18651             std::array<Nefarious, 10> arr; // this line can std::terminate(!)
18652         }
18654     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.
18656 5. You can't use `Nefarious` objects in standard containers:
18659         std::vector<Nefarious> vec(10);   // this line can std::terminate()
18661     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.
18663 ##### Note
18665 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.
18667 Consider the following advice and requirements found in the C++ Standard:
18669 > 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\]](#C++03) §15.2(3)
18671 > 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\]](#C++03) §17.4.4.8(3)
18673 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.
18674 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`:
18676     T& T::operator=(const T& other) {
18677         auto temp = other;
18678         swap(temp);
18679     }
18681 (See also Item 56. ???)
18683 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).
18685 When using exceptions as your error handling mechanism, always document this behavior by declaring these functions `noexcept`. (See Item 75.)
18687 **References**: [\[C++CS\]](#C++CS) Item 51; [\[C++03\]](#C++03) §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
18689 ## <a name="Sd-consistent"></a>Define Copy, move, and destroy consistently
18691 ##### Reason
18693  ???
18695 ##### Note
18697 If you define a copy constructor, you must also define a copy assignment operator.
18699 ##### Note
18701 If you define a move constructor, you must also define a move assignment operator.
18703 ##### Example
18705     class X {
18706         // ...
18707     public:
18708         X(const X&) { /* stuff */ }
18710         // BAD: failed to also define a copy assignment operator
18712         X(x&&) { /* stuff */ }
18714         // BAD: failed to also define a move assignment operator
18715     };
18717     X x1;
18718     X x2 = x1; // ok
18719     x2 = x1;   // pitfall: either fails to compile, or does something suspicious
18721 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.
18723     class X {
18724         HANDLE hnd;
18725         // ...
18726     public:
18727         ~X() { /* custom stuff, such as closing hnd */ }
18728         // suspicious: no mention of copying or moving -- what happens to hnd?
18729     };
18731     X x1;
18732     X x2 = x1; // pitfall: either fails to compile, or does something suspicious
18733     x2 = x1;   // pitfall: either fails to compile, or does something suspicious
18735 If you define copying, and any base or member has a type that defines a move operation, you should also define a move operation.
18737     class X {
18738         string s; // defines more efficient move operations
18739         // ... other data members ...
18740     public:
18741         X(const X&) { /* stuff */ }
18742         X& operator=(const X&) { /* stuff */ }
18744         // BAD: failed to also define a move construction and move assignment
18745         // (why wasn't the custom "stuff" repeated here?)
18746     };
18748     X test()
18749     {
18750         X local;
18751         // ...
18752         return local;  // pitfall: will be inefficient and/or do the wrong thing
18753     }
18755 If you define any of the copy constructor, copy assignment operator, or destructor, you probably should define the others.
18757 ##### Note
18759 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:
18761 * 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.)
18762 * 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.
18763 * If you explicitly write the destructor, you probably need to explicitly write or disable copying: If you have to write a nontrivial 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.
18765 In many cases, holding properly encapsulated resources using RAII "owning" objects can eliminate the need to write these operations yourself. (See Item 13.)
18767 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.
18769 **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.
18770 In rare cases, classes that have members of strange types (such as reference members) are an exception because they have peculiar copy semantics.
18771 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.)
18773 **References**: [\[C++CS\]](#C++CS) Item 52; [\[Cline99\]](#Cline99) §30.01-14, [\[Koenig97\]](#Koenig97) §4, [\[Stroustrup00\]](#Stroustrup00) §5.5, §10.4, [\[SuttHysl04b\]](#SuttHysl04b)
18775 Resource management rule summary:
18777 * [Provide strong resource safety; that is, never leak anything that you think of as a resource](#Cr-safety)
18778 * [Never throw while holding a resource not owned by a handle](#Cr-never)
18779 * [A "raw" pointer or reference is never a resource handle](#Cr-raw)
18780 * [Never let a pointer outlive the object it points to](#Cr-outlive)
18781 * [Use templates to express containers (and other resource handles)](#Cr-templates)
18782 * [Return containers by value (relying on move or copy elision for efficiency)](#Cr-value-return)
18783 * [If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations](#Cr-handle)
18784 * [If a class is a container, give it an initializer-list constructor](#Cr-list)
18786 ### <a name="Cr-safety"></a>Provide strong resource safety; that is, never leak anything that you think of as a resource
18788 ##### Reason
18790 Prevent leaks. Leaks can lead to performance degradation, mysterious error, system crashes, and security violations.
18792 **Alternative formulation**: Have every resource represented as an object of some class managing its lifetime.
18794 ##### Example
18796     template<class T>
18797     class Vector {
18798     // ...
18799     private:
18800         T* elem;   // sz elements on the free store, owned by the class object
18801         int sz;
18802     };
18804 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.).
18806 ##### Example
18808     ??? "odd" non-memory resource ???
18810 ##### Enforcement
18812 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.
18814 ### <a name="Cr-never"></a>Never throw while holding a resource not owned by a handle
18816 ##### Reason
18818 That would be a leak.
18820 ##### Example
18822     void f(int i)
18823     {
18824         FILE* f = fopen("a file", "r");
18825         ifstream is { "another file" };
18826         // ...
18827         if (i == 0) return;
18828         // ...
18829         fclose(f);
18830     }
18832 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:
18834     void f(int i)
18835     {
18836         unique_ptr<FILE, int(*)(FILE*)> f(fopen("a file", "r"), fclose);
18837         // ...
18838         if (i == 0) return;
18839         // ...
18840     }
18842 Better:
18844     void f(int i)
18845     {
18846         ifstream input {"a file"};
18847         // ...
18848         if (i == 0) return;
18849         // ...
18850     }
18852 ##### Enforcement
18854 A checker must consider all "naked pointers" suspicious.
18855 A checker probably must rely on a human-provided list of resources.
18856 For starters, we know about the standard-library containers, `string`, and smart pointers.
18857 The use of `span` and `string_span` should help a lot (they are not resource handles).
18859 ### <a name="Cr-raw"></a>A "raw" pointer or reference is never a resource handle
18861 ##### Reason
18863 To be able to distinguish owners from views.
18865 ##### Note
18867 This is independent of how you "spell" pointer: `T*`, `T&`, `Ptr<T>` and `Range<T>` are not owners.
18869 ### <a name="Cr-outlive"></a>Never let a pointer outlive the object it points to
18871 ##### Reason
18873 To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system.
18875 ##### Example
18877     string* bad()   // really bad
18878     {
18879         vector<string> v = { "This", "will", "cause", "trouble", "!" };
18880         // leaking a pointer into a destroyed member of a destroyed object (v)
18881         return &v[0];
18882     }
18884     void use()
18885     {
18886         string* p = bad();
18887         vector<int> xx = {7, 8, 9};
18888         // undefined behavior: x may not be the string "This"
18889         string x = *p;
18890         // undefined behavior: we don't know what (if anything) is allocated a location p
18891         *p = "Evil!";
18892     }
18894 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.
18896 ##### Enforcement
18898 Most compilers already warn about simple cases and has 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.
18900 ### <a name="Cr-templates"></a>Use templates to express containers (and other resource handles)
18902 ##### Reason
18904 To provide statically type-safe manipulation of elements.
18906 ##### Example
18908     template<typename T> class Vector {
18909         // ...
18910         T* elem;   // point to sz elements of type T
18911         int sz;
18912     };
18914 ### <a name="Cr-value-return"></a>Return containers by value (relying on move or copy elision for efficiency)
18916 ##### Reason
18918 To simplify code and eliminate a need for explicit memory management. To bring an object into a surrounding scope, thereby extending its lifetime. See also [F.20, the general item about "out" output values](#Rf-out).
18920 ##### Example
18922     vector<int> get_large_vector()
18923     {
18924         return ...;
18925     }
18927     auto v = get_large_vector(); //  return by value is ok, most modern compilers will do copy elision
18929 ##### Exception
18931 See the Exceptions in [F.20](#Rf-out).
18933 ##### Enforcement
18935 Check for pointers and references returned from functions and see if they are assigned to resource handles (e.g., to a `unique_ptr`).
18937 ### <a name="Cr-handle"></a>If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations
18939 ##### Reason
18941 To provide complete control of the lifetime of the resource. To provide a coherent set of operations on the resource.
18943 ##### Example
18945     ??? Messing with pointers
18947 ##### Note
18949 If all members are resource handles, rely on the default special operations where possible.
18951     template<typename T> struct Named {
18952         string name;
18953         T value;
18954     };
18956 Now `Named` has a default constructor, a destructor, and efficient copy and move operations, provided `T` has.
18958 ##### Enforcement
18960 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.
18962 ### <a name="Cr-list"></a>If a class is a container, give it an initializer-list constructor
18964 ##### Reason
18966 It is common to need an initial set of elements.
18968 ##### Example
18970     template<typename T> class Vector {
18971     public:
18972         Vector(std::initializer_list<T>);
18973         // ...
18974     };
18976     Vector<string> vs { "Nygaard", "Ritchie" };
18978 ##### Enforcement
18980 When is a class a container? ???
18982 # <a name="S-glossary"></a>Glossary
18984 A relatively informal definition of terms used in the guidelines
18985 (based of the glossary in [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html))
18987 * *abstract class*: a class that cannot be directly used to create objects; often used to define an interface to derived classes.
18988   A class is made abstract by having a pure virtual function or only protected constructors.
18989 * *abstraction*: a description of something that selectively and deliberately ignores (hides) details (e.g., implementation details); selective ignorance.
18990 * *address*: a value that allows us to find an object in a computer's memory.
18991 * *algorithm*: a procedure or formula for solving a problem; a finite series of computational steps to produce a result.
18992 * *alias*: an alternative way of referring to an object; often a name, pointer, or reference.
18993 * *application*: a program or a collection of programs that is considered an entity by its users.
18994 * *approximation*: something (e.g., a value or a design) that is close to the perfect or ideal (value or design).
18995   Often an approximation is a result of trade-offs among ideals.
18996 * *argument*: a value passed to a function or a template, in which it is accessed through a parameter.
18997 * *array*: a homogeneous sequence of elements, usually numbered, e.g., \[0:max).
18998 * *assertion*: a statement inserted into a program to state (assert) that something must always be true at this point in the program.
18999 * *base class*: a class used as the base of a class hierarchy. Typically a base class has one or more virtual functions.
19000 * *bit*: the basic unit of information in a computer. A bit can have the value 0 or the value 1.
19001 * *bug*: an error in a program.
19002 * *byte*: the basic unit of addressing in most computers. Typically, a byte holds 8 bits.
19003 * *class*: a user-defined type that may contain data members, function members, and member types.
19004 * *code*: a program or a part of a program; ambiguously used for both source code and object code.
19005 * *compiler*: a program that turns source code into object code.
19006 * *complexity*: a hard-to-precisely-define notion or measure of the difficulty of constructing a solution to a problem or of the solution itself.
19007   Sometimes complexity is used to (simply) mean an estimate of the number of operations needed to execute an algorithm.
19008 * *computation*: the execution of some code, usually taking some input and producing some output.
19009 * *concept*: (1) a notion, and idea; (2) a set of requirements, usually for a template argument.
19010 * *concrete class*: class for which objects can be created.
19011 * *constant*: a value that cannot be changed (in a given scope); not mutable.
19012 * *constructor*: an operation that initializes ("constructs") an object.
19013   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).
19014 * *container*: an object that holds elements (other objects).
19015 * *copy*: an operation that makes two object have values that compare equal. See also move.
19016 * *correctness*: a program or a piece of a program is correct if it meets its specification.
19017   Unfortunately, a specification can be incomplete or inconsistent, or can fail to meet users' reasonable expectations.
19018   Thus, to produce acceptable code, we sometimes have to do more than just follow the formal specification.
19019 * *cost*: the expense (e.g., in programmer time, run time, or space) of producing a program or of executing it.
19020   Ideally, cost should be a function of complexity.
19021 * *customization point*: ???
19022 * *data*: values used in a computation.
19023 * *debugging*: the act of searching for and removing errors from a program; usually far less systematic than testing.
19024 * *declaration*: the specification of a name with its type in a program.
19025 * *definition*: a declaration of an entity that supplies all information necessary to complete a program using the entity.
19026   Simplified definition: a declaration that allocates memory.
19027 * *derived class*: a class derived from one or more base classes.
19028 * *design*: an overall description of how a piece of software should operate to meet its specification.
19029 * *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.
19030 * *encapsulation*: protecting something meant to be private (e.g., implementation details) from unauthorized access.
19031 * *error*: a mismatch between reasonable expectations of program behavior (often expressed as a requirement or a users' guide) and what a program actually does.
19032 * *executable*: a program ready to be run (executed) on a computer.
19033 * *feature creep*: a tendency to add excess functionality to a program "just in case."
19034 * *file*: a container of permanent information in a computer.
19035 * *floating-point number*: a computer's approximation of a real number, such as 7.93 and 10.78e-3.
19036 * *function*: a named unit of code that can be invoked (called) from different parts of a program; a logical unit of computation.
19037 * *generic programming*: a style of programming focused on the design and efficient implementation of algorithms.
19038   A generic algorithm will work for all argument types that meet its requirements. In C++, generic programming typically uses templates.
19039 * *global variable*: technically, a named object in namespace scope.
19040 * *handle*: a class that allows access to another through a member pointer or reference. See also resource, copy, move.
19041 * *header*: a file containing declarations used to share interfaces between parts of a program.
19042 * *hiding*: the act of preventing a piece of information from being directly seen or accessed.
19043   For example, a name from a nested (inner) scope can prevent that same name from an outer (enclosing) scope from being directly used.
19044 * *ideal*: the perfect version of something we are striving for. Usually we have to make trade-offs and settle for an approximation.
19045 * *implementation*: (1) the act of writing and testing code; (2) the code that implements a program.
19046 * *infinite loop*: a loop where the termination condition never becomes true. See iteration.
19047 * *infinite recursion*: a recursion that doesn't end until the machine runs out of memory to hold the calls.
19048   In reality, such recursion is never infinite but is terminated by some hardware error.
19049 * *information hiding*: the act of separating interface and implementation, thus hiding implementation details not meant for the user's attention and providing an abstraction.
19050 * *initialize*: giving an object its first (initial) value.
19051 * *input*: values used by a computation (e.g., function arguments and characters typed on a keyboard).
19052 * *integer*: a whole number, such as 42 and -99.
19053 * *interface*: a declaration or a set of declarations specifying how a piece of code (such as a function or a class) can be called.
19054 * *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.
19055 * *iteration*: the act of repeatedly executing a piece of code; see recursion.
19056 * *iterator*: an object that identifies an element of a sequence.
19057 * *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.
19058 * *lifetime*: the time from the initialization of an object until it becomes unusable (goes out of scope, is deleted, or the program terminates).
19059 * *linker*: a program that combines object code files and libraries into an executable program.
19060 * *literal*: a notation that directly specifies a value, such as 12 specifying the integer value "twelve."
19061 * *loop*: a piece of code executed repeatedly; in C++, typically a for-statement or a while-statement.
19062 * *move*: an operation that transfers a value from one object to another leaving behind a value representing "empty." See also copy.
19063 * *mutable*: changeable; the opposite of immutable, constant, and invariable.
19064 * *object*: (1) an initialized region of memory of a known type which holds a value of that type; (2) a region of memory.
19065 * *object code*: output from a compiler intended as input for a linker (for the linker to produce executable code).
19066 * *object file*: a file containing object code.
19067 * *object-oriented programming*: (OOP) a style of programming focused on the design and use of classes and class hierarchies.
19068 * *operation*: something that can perform some action, such as a function and an operator.
19069 * *output*: values produced by a computation (e.g., a function result or lines of characters written on a screen).
19070 * *overflow*: producing a value that cannot be stored in its intended target.
19071 * *overload*: defining two functions or operators with the same name but different argument (operand) types.
19072 * *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.
19073 * *owner*: an object responsible for releasing a resource.
19074 * *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.
19075 * *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.
19076 * *pointer*: (1) a value used to identify a typed object in memory; (2) a variable holding such a value.
19077 * *post-condition*: a condition that must hold upon exit from a piece of code, such as a function or a loop.
19078 * *pre-condition*: a condition that must hold upon entry into a piece of code, such as a function or a loop.
19079 * *program*: code (possibly with associated data) that is sufficiently complete to be executed by a computer.
19080 * *programming*: the art of expressing solutions to problems as code.
19081 * *programming language*: a language for expressing programs.
19082 * *pseudo code*: a description of a computation written in an informal notation rather than a programming language.
19083 * *pure virtual function*: a virtual function that must be overridden in a derived class.
19084 * *RAII*: ("Resource Acquisition Is Initialization") a basic technique for resource management based on scopes.
19085 * *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.
19086 * *recursion*: the act of a function calling itself; see also iteration.
19087 * *reference*: (1) a value describing the location of a typed value in memory; (2) a variable holding such a value.
19088 * *regular expression*: a notation for patterns in character strings.
19089 * *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.
19090 * *resource*: something that is acquired and must later be released, such as a file handle, a lock, or memory. See also handle, owner.
19091 * *rounding*: conversion of a value to the mathematically nearest value of a less precise type.
19092 * *RTTI*: Run-Time Type Information. ???
19093 * *scope*: the region of program text (source code) in which a name can be referred to.
19094 * *sequence*: elements that can be visited in a linear order.
19095 * *software*: a collection of pieces of code and associated data; often used interchangeably with program.
19096 * *source code*: code as produced by a programmer and (in principle) readable by other programmers.
19097 * *source file*: a file containing source code.
19098 * *specification*: a description of what a piece of code should do.
19099 * *standard*: an officially agreed upon definition of something, such as a programming language.
19100 * *state*: a set of values.
19101 * *STL*: the containers, iterators, and algorithms part of the standard library.
19102 * *string*: a sequence of characters.
19103 * *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.
19104 * *subtype*: derived type; a type that has all the properties of a type and possibly more.
19105 * *supertype*: base type; a type that has a subset of the properties of a type.
19106 * *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.
19107 * *template*: a class or a function parameterized by one or more types or (compile-time) values; the basic C++ language construct supporting generic programming.
19108 * *testing*: a systematic search for errors in a program.
19109 * *trade-off*: the result of balancing several design and implementation criteria.
19110 * *truncation*: loss of information in a conversion from a type into another that cannot exactly represent the value to be converted.
19111 * *type*: something that defines a set of possible values and a set of operations for an object.
19112 * *uninitialized*: the (undefined) state of an object before it is initialized.
19113 * *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.
19114 * *use case*: a specific (typically simple) use of a program meant to test its functionality and demonstrate its purpose.
19115 * *value*: a set of bits in memory interpreted according to a type.
19116 * *variable*: a named object of a given type; contains a value unless uninitialized.
19117 * *virtual function*: a member function that can be overridden in a derived class.
19118 * *word*: a basic unit of memory in a computer, often the unit used to hold an integer.
19120 # <a name="S-unclassified"></a>To-do: Unclassified proto-rules
19122 This is our to-do list.
19123 Eventually, the entries will become rules or parts of rules.
19124 Alternatively, we will decide that no change is needed and delete the entry.
19126 * No long-distance friendship
19127 * Should physical design (what's in a file) and large-scale design (libraries, groups of libraries) be addressed?
19128 * Namespaces
19129 * 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?
19130 * Should there be inline namespaces (à la `std::literals::*_literals`)?
19131 * Avoid implicit conversions
19132 * 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
19133 * Always initialize variables, use initialization lists for member variables.
19134 * 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. :)
19135 * Use `const`-ness wherever possible: member functions, variables and (yippee) `const_iterators`
19136 * Use `auto`
19137 * `(size)` vs. `{initializers}` vs. `{Extent{size}}`
19138 * Don't overabstract
19139 * Never pass a pointer down the call stack
19140 * falling through a function bottom
19141 * 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?
19142 * Speaking of virtual functions, should non-virtual interface be promoted? YES. (public non-virtual `foo()` calling private/protected `do_foo()`)? Not a new thing, seeing as locales/streams use it, but it seems to be under-emphasized.
19143 * 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?
19144 * Speaking of lambdas, what would weigh in on the decision between lambdas and (local?) classes in algorithm calls and other callback scenarios?
19145 * 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?
19146 * What to do with leaks out of temporaries? : `p = (s1 + s2).c_str();`
19147 * pointer/iterator invalidation leading to dangling pointers:
19149         void bad()
19150         {
19151             int* p = new int[700];
19152             int* q = &p[7];
19153             delete p;
19155             vector<int> v(700);
19156             int* q2 = &v[7];
19157             v.resize(900);
19159             // ... use q and q2 ...
19160         }
19162 * LSP
19163 * private inheritance vs/and membership
19164 * avoid static class members variables (race conditions, almost-global variables)
19166 * Use RAII lock guards (`lock_guard`, `unique_lock`, `shared_lock`), never call `mutex.lock` and `mutex.unlock` directly (RAII)
19167 * Prefer non-recursive locks (often used to work around bad reasoning, overhead)
19168 * 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`?
19169 * If two or more mutexes must be acquired at the same time, use `std::lock` (or another deadlock avoidance algorithm?)
19170 * 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.
19171 * 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)
19172 * 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)
19173 * 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)
19175 * rules for arithmetic
19177 # Bibliography
19179 * <a name="Alexandrescu01"></a>
19180   \[Alexandrescu01]:  A. Alexandrescu. Modern C++ Design (Addison-Wesley, 2001).
19181 * <a name="Cplusplus03"></a>
19182   \[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).
19183 * <a name="CplusplusCS"></a>
19184   \[C++CS]:
19185 * <a name="Cargill92"></a>
19186   \[Cargill92]:       T. Cargill. C++ Programming Style (Addison-Wesley, 1992).
19187 * <a name="Cline99"></a>
19188   \[Cline99]:         M. Cline, G. Lomow, and M. Girou. C++ FAQs (2ndEdition) (Addison-Wesley, 1999).
19189 * <a name="Dewhurst03"></a>
19190   \[Dewhurst03]:      S. Dewhurst. C++ Gotchas (Addison-Wesley, 2003).
19191 * <a name="Henricson97"></a>
19192   \[Henricson97]:     M. Henricson and E. Nyquist. Industrial Strength C++ (Prentice Hall, 1997).
19193 * <a name="Koenig97"></a>
19194   \[Koenig97]:        A. Koenig and B. Moo. Ruminations on C++ (Addison-Wesley, 1997).
19195 * <a name="Lakos96"></a>
19196   \[Lakos96]:         J. Lakos. Large-Scale C++ Software Design (Addison-Wesley, 1996).
19197 * <a name="Meyers96"></a>
19198   \[Meyers96]:        S. Meyers. More Effective C++ (Addison-Wesley, 1996).
19199 * <a name="Meyers97"></a>
19200   \[Meyers97]:        S. Meyers. Effective C++ (2nd Edition) (Addison-Wesley, 1997).
19201 * <a name="Meyers15"></a>
19202   \[Meyers15]:        S. Meyers. Effective Modern C++ (O'Reilly, 2015).
19203 * <a name="Murray93"></a>
19204   \[Murray93]:        R. Murray. C++ Strategies and Tactics (Addison-Wesley, 1993).
19205 * <a name="Stroustrup00"></a>
19206   \[Stroustrup00]:    B. Stroustrup. The C++ Programming Language (Special 3rdEdition) (Addison-Wesley, 2000).
19207 * <a name="Stroustrup05"></a>
19208   \[Stroustrup05]:    B. Stroustrup. [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
19209 * <a name="Stroustrup13"></a>
19210   \[Stroustrup13]:    B. Stroustrup. [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html). Addison Wesley 2013.
19211 * <a name="Stroustrup14"></a>
19212   \[Stroustrup14]:    B. Stroustrup. [A Tour of C++](http://www.stroustrup.com/Tour.html).
19213   Addison Wesley 2014.
19214 * <a name="SuttHysl04b"></a>
19215   \[SuttHysl04b]:     H. Sutter and J. Hyslop. "Collecting Shared Objects" (C/C++ Users Journal, 22(8), August 2004).
19216 * <a name="SuttAlex05"></a>
19217   \[SuttAlex05]:      H. Sutter and  A. Alexandrescu. C++ Coding Standards. Addison-Wesley 2005.
19218 * <a name="Sutter00"></a>
19219   \[Sutter00]:        H. Sutter. Exceptional C++ (Addison-Wesley, 2000).
19220 * <a name="Sutter02"></a>
19221   \[Sutter02]:        H. Sutter. More Exceptional C++ (Addison-Wesley, 2002).
19222 * <a name="Sutter04"></a>
19223   \[Sutter04]:        H. Sutter. Exceptional C++ Style (Addison-Wesley, 2004).
19224 * <a name="Taligent94"></a>
19225   \[Taligent94]: Taligent's Guide to Designing Programs (Addison-Wesley, 1994).